easemob-websdk 5.0.0 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/bundle/im-sdk-web.iife.js +1 -1
  2. package/cache/cache-manager.d.ts +3 -0
  3. package/cache/cache-store.d.ts +6 -4
  4. package/cache/cache-utils.d.ts +1 -1
  5. package/chunks/cache-utils-B99glc0H.js +1 -0
  6. package/chunks/cache-utils-gowrxNr8.cjs +1 -0
  7. package/chunks/chat-manager-5wHx7UeW.cjs +1 -0
  8. package/chunks/chat-manager-DdAnJpcH.js +2 -0
  9. package/chunks/common-BIpcR2uQ.cjs +1 -0
  10. package/chunks/common-BW2KLpvb.js +1 -0
  11. package/chunks/{group-user-info-resolver-FNRqDg18.js → group-user-info-resolver-Diqjmjyj.js} +1 -1
  12. package/chunks/{group-user-info-resolver-C5pdiqox.cjs → group-user-info-resolver-Ds35Z1Uf.cjs} +1 -1
  13. package/chunks/index-BItCF8E7.cjs +1 -0
  14. package/chunks/{index-uKWbjx-u.js → index-DKksD5YM.js} +1 -1
  15. package/chunks/{index-BKg4EGcI.cjs → index-DKmdsV1-.cjs} +1 -1
  16. package/chunks/index-VEUtqiDw.js +1 -0
  17. package/chunks/query-params-BHyPuD2k.cjs +1 -0
  18. package/chunks/query-params-Bu3Xq4b6.js +1 -0
  19. package/chunks/{session-list-query-B6dh-b4Y.cjs → session-list-query-C4OQMvPf.cjs} +1 -1
  20. package/chunks/{session-list-query-Dnp2HbpW.js → session-list-query-DtoToipt.js} +1 -1
  21. package/chunks/{user-info-BfRwS4ZA.js → user-info-22jZtcSi.js} +1 -1
  22. package/chunks/{user-info-icpL0Eaw.cjs → user-info-DsDDTJrw.cjs} +1 -1
  23. package/index.cjs +1 -1
  24. package/index.js +2 -2
  25. package/managers/chat/index.cjs +1 -1
  26. package/managers/chat/index.js +1 -1
  27. package/managers/chat-thread/index.cjs +1 -1
  28. package/managers/chat-thread/index.js +1 -1
  29. package/managers/chatroom/index.cjs +1 -1
  30. package/managers/chatroom/index.js +1 -1
  31. package/managers/contact/index.cjs +1 -1
  32. package/managers/contact/index.js +1 -1
  33. package/managers/group/index.cjs +1 -1
  34. package/managers/group/index.js +1 -1
  35. package/managers/presence/index.cjs +1 -1
  36. package/managers/presence/index.js +1 -1
  37. package/managers/push/index.cjs +1 -1
  38. package/managers/push/index.js +1 -1
  39. package/managers/user-info/index.cjs +1 -1
  40. package/managers/user-info/index.js +1 -1
  41. package/package.json +1 -1
  42. package/platform/env.d.ts +1 -0
  43. package/utils/query-params.d.ts +16 -0
  44. package/utils/runtime-global.d.ts +13 -0
  45. package/utils/storage-error.d.ts +8 -0
  46. package/chunks/cache-utils-BwRPIZ7n.js +0 -1
  47. package/chunks/cache-utils-CKbcYPlM.cjs +0 -1
  48. package/chunks/chat-manager-ChdK26ck.cjs +0 -1
  49. package/chunks/chat-manager-DH8a6Qj9.js +0 -2
  50. package/chunks/common-CfAlncj9.cjs +0 -1
  51. package/chunks/common-DN_g4O3n.js +0 -1
  52. package/chunks/index-CK3GHdGU.cjs +0 -1
  53. package/chunks/index-CjofwvEQ.js +0 -1
@@ -4,6 +4,7 @@
4
4
  import type { ContactSnapshot } from '../types/contact';
5
5
  import type { UserInfo, UserInfoNotifyPatch } from '../types/user-info';
6
6
  import type { JoinedGroupSnapshot } from '../types/group';
7
+ import type { StorageAdapter } from '../platform';
7
8
  import type { CacheConfig, ContactCacheMeta, ContactRelationRecord, ContactVersionState, ConversationSummary, GroupNamecardCacheRecord, SessionListCheckpoint, UserInfoSummary } from './cache-types';
8
9
  import type { ConversationMark, ConversationType, ConversationItem, SessionListRemindType } from '../types/conversation';
9
10
  import type { Message } from '../types';
@@ -12,6 +13,8 @@ export interface CacheManagerOptions {
12
13
  readonly appKey: string;
13
14
  readonly userId: string;
14
15
  readonly cacheEncryptionMode?: 'auto' | 'off';
16
+ /** [zh-CN] 跨平台存储适配器;缺失或不可用时允许降级。 [en-US] Cross-platform storage adapter; persistence may gracefully degrade when unavailable. */
17
+ readonly storageAdapter?: StorageAdapter;
15
18
  readonly config?: Partial<CacheConfig>;
16
19
  }
17
20
  export interface ConversationMergeResult {
@@ -1,11 +1,13 @@
1
1
  /**
2
- * localStorage 访问封装
2
+ * 跨平台键值存储访问封装
3
3
  */
4
+ import type { StorageAdapter } from '../platform';
4
5
  import type { CacheCryptoAdapter } from './cache-crypto';
5
6
  export declare class CacheStore {
6
- private readonly available;
7
+ private readonly storage;
7
8
  private readonly cryptoAdapter;
8
- constructor(cryptoAdapter?: CacheCryptoAdapter);
9
+ constructor(cryptoAdapter?: CacheCryptoAdapter, storageAdapter?: StorageAdapter);
10
+ private static createLocalStorageAdapter;
9
11
  static checkAvailable(): boolean;
10
12
  readAsync<T>(key: string, fallback: T): Promise<T>;
11
13
  writeAsync(key: string, value: unknown): Promise<void>;
@@ -15,5 +17,5 @@ export declare class CacheStore {
15
17
  */
16
18
  writeStrictAsync(key: string, value: unknown): Promise<void>;
17
19
  private writeInternal;
18
- remove(key: string): void;
20
+ remove(key: string): Promise<void>;
19
21
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * 缓存工具方法
3
3
  */
4
+ export { isStorageQuotaExceededError as isQuotaExceededError } from '../utils/storage-error';
4
5
  export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
5
6
  export declare const safeJsonParse: <T>(raw: string | null, fallback: T) => T;
6
7
  export declare const safeJsonStringify: (value: unknown) => string | null;
7
- export declare const isQuotaExceededError: (error: unknown) => boolean;
@@ -0,0 +1 @@
1
+ const r=r=>"object"==typeof r&&null!==r&&!Array.isArray(r),t=(r,t)=>{if(!r)return t;try{return JSON.parse(r)}catch{return t}},a=r=>{try{return JSON.stringify(r)}catch{return null}};export{a,r as i,t as s};
@@ -0,0 +1 @@
1
+ "use strict";exports.isRecord=r=>"object"==typeof r&&null!==r&&!Array.isArray(r),exports.safeJsonParse=(r,t)=>{if(!r)return t;try{return JSON.parse(r)}catch{return t}},exports.safeJsonStringify=r=>{try{return JSON.stringify(r)}catch{return null}};
@@ -0,0 +1 @@
1
+ "use strict";const e=require("./common-BIpcR2uQ.cjs"),t=require("./cache-utils-gowrxNr8.cjs"),r=require("./session-list-query-C4OQMvPf.cjs"),a=require("./group-user-info-resolver-Ds35Z1Uf.cjs"),i=require("zod"),s=require("./query-params-BHyPuD2k.cjs"),o={DISCONNECTED:"disconnected",CONNECTING:"connecting",CONNECTED:"connected",RECONNECTING:"reconnecting",RECONNECT_FAILED:"reconnectFailed"},n=new WeakMap;const d=new class{constructor(){this.store=new Map}set(e,t){e&&this.store.set(e,t)}get(e){if(e)return this.store.get(e)}consume(e){const t=this.get(e);return t&&this.store.delete(e),t}delete(e){e&&this.store.delete(e)}clear(){this.store.clear()}},l=e=>{if((e=>"undefined"!=typeof File&&e instanceof File)(e)){if("undefined"==typeof URL||"function"!=typeof URL.createObjectURL)return;return URL.createObjectURL(e)}return(e=>"object"==typeof e&&null!==e&&"path"in e&&"string"==typeof e.path)(e)?e.path:(e=>"object"==typeof e&&null!==e&&"uri"in e&&"string"==typeof e.uri)(e)?e.uri:void 0},c=()=>{const t=e.getRuntimeGlobal().crypto;return t&&"function"==typeof t.randomUUID?t.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},g=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),u=(t,r,a)=>{throw new e.ValidationError(t,{code:a,details:{fields:[{path:r,message:t,rule:"invalid_format"}]}})},m=e=>{if("combine"!==e.type)return 0;const t=e.combineLevel;return"number"==typeof t?t:g(e.body)&&"number"==typeof e.body.combineLevel?e.body.combineLevel:0},p=(t,r)=>{if(t.sender.userId||u(`messageList[${r}] sender.userId is required`,`messageList[${r}].sender.userId`,e.ERROR_CODES.COMBINE_INVALID_INPUT),t.conversationId&&["singleChat","groupChat","chatRoom"].includes(t.conversationType)||u(`messageList[${r}] conversation is invalid`,`messageList[${r}].conversationId`,e.ERROR_CODES.COMBINE_INVALID_INPUT),(!Number.isInteger(t.timestamp)||t.timestamp<=0)&&u(`messageList[${r}] timestamp must be positive integer`,`messageList[${r}].timestamp`,e.ERROR_CODES.COMBINE_INVALID_INPUT),g(t.body)||u(`messageList[${r}] body must be object`,`messageList[${r}].body`,e.ERROR_CODES.COMBINE_INVALID_INPUT),"combine"===t.type){const a=m(t);(!Number.isInteger(a)||a<0)&&u(`messageList[${r}] combineLevel is invalid`,`messageList[${r}].combineLevel`,e.ERROR_CODES.COMBINE_INVALID_INPUT),a>10&&u(`messageList[${r}] combineLevel exceeds limit`,`messageList[${r}].combineLevel`,e.ERROR_CODES.COMBINE_LEVEL_EXCEEDED)}},h=(t,r=300)=>{(!Number.isInteger(t)||t<=0)&&u("messageList must not be empty","messageList",e.ERROR_CODES.COMBINE_INVALID_INPUT),(!Number.isInteger(r)||r<=0||r>300)&&u("max items is invalid","maxItems",e.ERROR_CODES.COMBINE_INVALID_INPUT),t>r&&u(`messageList max length is ${r}`,"messageList",e.ERROR_CODES.COMBINE_ITEM_LIMIT_EXCEEDED)},y=t=>{h(t.length);for(let r=0;r<t.length;r+=1){const a=t[r];void 0!==a?p(a,r):u(`messageList[${r}] is required`,`messageList[${r}]`,e.ERROR_CODES.COMBINE_INVALID_INPUT)}},v=e=>{let t=0;for(const r of e){if("combine"!==r.type)continue;const e=m(r);e>t&&(t=e)}return t+1},I=t=>{(!Number.isInteger(t)||t<=0)&&u("combineLevel must be positive integer","combineLevel",e.ERROR_CODES.COMBINE_INVALID_INPUT),t>10&&u("combineLevel must be <= 10","combineLevel",e.ERROR_CODES.COMBINE_LEVEL_EXCEEDED)};class E{static validate(t,r){try{return{success:!0,data:t.parse(r)}}catch(a){if(a instanceof i.ZodError){const t=a.errors.map(e=>({path:e.path.length>0?e.path.join("."):"root",message:e.message,rule:e.code})),r=`Validation failed: ${t.map(e=>`${e.path}: ${e.message}`).join("; ")}`,i=a.errors.some(e=>"invalid_type"===e.code&&"undefined"===e.received)?e.ERROR_CODES.VALIDATION_REQUIRED:e.ERROR_CODES.VALIDATION_INVALID_FORMAT;return{success:!1,error:new e.ValidationError(r,{code:i,details:{fields:t}})}}return{success:!1,error:new e.ValidationError("Unknown validation error",{code:e.ERROR_CODES.VALIDATION_UNKNOWN,details:{fields:[]}})}}}static validateOrThrow(t,r){const a=this.validate(t,r);if(a.success&&void 0!==a.data)return a.data;if(a.error)throw a.error;throw new e.ValidationError("Unknown validation error",{code:e.ERROR_CODES.VALIDATION_UNKNOWN,details:{fields:[]}})}static safeParse(e,t){return this.validate(e,t)}}const f=(t,r)=>new e.ValidationError(r,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:r,rule:"invalid_format"}]}}),_=(t,r)=>{if("string"!=typeof t||0===t.trim().length)throw(t=>new e.ValidationError(`${t} is required`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}}))(r);return t.trim()},R=e=>`mark_${String(e)}`,b=(e,t)=>{if("singleChat"===e||"groupChat"===e||"chatRoom"===e)return e;throw f(t,`${t} must be one of singleChat, groupChat, chatRoom`)},C=e=>"singleChat"===e?"chat":"groupChat"===e?"groupchat":"chatroom",T=e=>"string"==typeof e&&e.length>0?e:void 0,O=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}},L=e=>t.isRecord(e)?e:void 0,N=(e,r)=>{const a=L(e);if(!a)return;const i=(e=>"string"==typeof e?t.safeJsonParse(e,{}):L(e)??{})(a.payload),s=Array.isArray(i.bodies)?i.bodies:[],o=L(s[0])??L(i.body),n=(e=>"txt"===e||"text"===e?"text":"custom"===e?"custom":"cmd"===e?"cmd":"image"===e||"file"===e||"voice"===e||"video"===e||"location"===e||"combine"===e?e:null)(o?.type??i.type);if(!o||!n)return;const d=((e,t)=>{if("text"===e)return{content:T(t.msg)??T(t.content)??""};if("custom"===e){const e=L(t.customExts)??L(t.params)??{},r={};for(const[t,a]of Object.entries(e))"string"==typeof a&&(r[t]=a);return{event:T(t.customEvent)??T(t.event)??"",params:r}}if("cmd"===e)return{action:T(t.action)??""};if("image"===e){const e=T(t.url)??T(t.remotePath)??"";return{localUrl:"",filename:T(t.filename)??T(t.displayName),filetype:T(t.filetype)??"application/octet-stream",width:O(t.width),height:O(t.height),isGif:!0===t.isGif||1===t.subType,isOriginalImage:!0===t.isOriginalImage,originalImageUrl:e,bigImageUrl:T(t.bigImageUrl),thumbnailUrl:T(t.thumbnailUrl)??T(t.thumbnailRemotePath),secret:T(t.secret)??T(t.secretKey),fileLength:O(t.fileLength)}}return"file"===e?{url:T(t.url)??T(t.remotePath),filename:T(t.filename)??T(t.displayName),filetype:T(t.filetype)??"application/octet-stream",fileSize:O(t.fileSize),fileLength:O(t.fileLength),secret:T(t.secret)??T(t.secretKey)}:"voice"===e?{url:T(t.url)??T(t.remotePath),filename:T(t.filename)??T(t.displayName),filetype:T(t.filetype)??"application/octet-stream",duration:O(t.duration)??0,fileLength:O(t.fileLength),secret:T(t.secret)??T(t.secretKey)}:"video"===e?{url:T(t.url)??T(t.remotePath),filename:T(t.filename)??T(t.displayName),filetype:T(t.filetype)??"application/octet-stream",duration:O(t.duration)??0,width:O(t.width),height:O(t.height),fileLength:O(t.fileLength),secret:T(t.secret)??T(t.secretKey),thumbnailUrl:T(t.thumbnailUrl)??T(t.thumbnailRemotePath)}:"location"===e?{latitude:O(t.latitude)??0,longitude:O(t.longitude)??0,address:T(t.address),buildingName:T(t.buildingName)}:null})(n,o);if(!d)return;const l=T(i.from)??T(a.from)??"",c=T(i.to)??r.conversationId,g=L(i.sender),u={userId:T(g?.userId)??l,nickname:T(g?.nickname),avatarUrl:T(g?.avatarUrl)},m=L(i.ext)??{},p=(e=>{const t=L(e);if(!t)return;const r=T(t.operatorId)??T(t.operator),a=O(t.operationCount)??O(t.count),i=O(t.operationTime)??O(t.edit_time);return r&&void 0!==a&&void 0!==i?{operatorId:r,operationCount:a,operationTime:i}:void 0})(i.modifiedInfo??L(i.meta)?.edit_msg);return{msgServerId:T(a.id)??r.messageId,msgLocalId:T(a.msgLocalId)??"",from:l,to:c,sender:u,conversationId:r.conversationId,conversationType:r.conversationType,type:n,sendStatus:"sent",ext:m,timestamp:O(a.timestamp)??r.timestamp,body:d,direct:l===r.currentUserId?"SEND":"RECEIVE",...p?{modifiedInfo:p}:{}}},S=e=>`${e.conversationType}:${e.conversationId}`,w=t=>{const{orgName:r,appName:a}=e.parseAppKey(t.appKey);return{orgName:r,appName:a,encodedUserId:encodeURIComponent(t.userId),encodedResource:encodeURIComponent(t.clientResource)}},A=async(e,r,a,i)=>{const s=w(r),o=(e=>{const r=e,a=r.conversations;if(void 0!==a){if(!Array.isArray(a)||0===a.length)throw f("params.conversations","params.conversations must be a non-empty array");return a.map((e,r)=>{if(!t.isRecord(e))throw f(`params.conversations.${String(r)}`,`params.conversations.${String(r)} must be an object`);return{conversationId:_(e.conversationId,`params.conversations.${String(r)}.conversationId`),conversationType:b(e.conversationType,`params.conversations.${String(r)}.conversationType`)}})}return[{conversationId:_(r.conversationId,"params.conversationId"),conversationType:b(r.conversationType,"params.conversationType")}]})(a),n=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0||e>19)throw f(t,`${t} must be an integer between 0 and 19`);return e})(a.mark,"params.mark"),d=await e.request(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channels/mark?resource=${s.encodedResource}`,{method:i?"POST":"DELETE",body:{mark:R(n),targets:o.map(e=>({to:e.conversationId,type:C(e.conversationType)}))},operation:i?"addConversationMark":"removeConversationMark"}),l=(e=>{if(!Array.isArray(e))return new Set;const r=new Set;return e.forEach(e=>{if(!t.isRecord(e))return;const a="string"==typeof e.to?e.to.trim():"",i=(e=>"chat"===e||"singleChat"===e?"singleChat":"groupchat"===e||"groupChat"===e?"groupChat":"chatroom"===e||"chatRoom"===e?"chatRoom":null)(e.type);a&&i&&r.add(S({conversationId:a,conversationType:i}))}),r})((t.isRecord(d)&&t.isRecord(d.data)?d.data:{}).ignore),c=[],g=[];for(const t of o){const e={conversationId:t.conversationId,conversationType:t.conversationType};l.has(S(t))?g.push({...e,reason:"ignored_by_server"}):c.push(e)}return{succeeded:c,failed:g,mark:n,operation:i?"addMark":"removeMark"}},M=async(e,t,r,a)=>{const i=w(t),s=_(r.conversationId,"params.conversationId"),o=b(r.conversationType,"params.conversationType"),n=_(r.messageId,"params.messageId");return await e.request(`/${i.orgName}/${i.appName}/sdk/user/${i.encodedUserId}/user_channel/pin?resource=${i.encodedResource}`,{method:a?"POST":"DELETE",body:{to:s,type:C(o),pin_msg_id:n},operation:a?"pinMessage":"unpinMessage"}),{conversationId:s,conversationType:o,messageId:n,operation:a?"pin":"unpin"}},D=i.z.enum(["singleChat","groupChat","chatRoom"]),U=i.z.record(i.z.unknown()).refine(e=>(e=>"object"==typeof e&&null!==e&&!Array.isArray(e))(e),"ext must be an object").refine(e=>(e=>{try{return JSON.stringify(e),!0}catch{return!1}})(e),"ext must be JSON serializable"),x=i.z.object({path:i.z.string().min(1,"data.path is required"),size:i.z.number().optional(),name:i.z.string().optional(),type:i.z.string().optional()}),z=i.z.object({uri:i.z.string().min(1,"data.uri is required"),size:i.z.number().optional(),name:i.z.string().optional(),type:i.z.string().optional()}),$="undefined"!=typeof File?i.z.instanceof(File):i.z.never(),V=i.z.union([$,x,z]),k=i.z.object({conversationId:i.z.string().min(1,"conversationId is required"),conversationType:D,ext:U.optional(),timestamp:i.z.number().int().positive("timestamp must be a positive integer").optional(),receiverList:i.z.array(i.z.string().min(1,"receiverList item is required")).nonempty("receiverList must not be empty").optional(),deliverOnlineOnly:i.z.boolean().optional(),webhookEnv:i.z.string().optional(),priority:i.z.enum(["high","normal","low"]).optional(),needReadReceipt:i.z.boolean().optional(),isChatThread:i.z.boolean().optional()}),P=i.z.object({type:i.z.string().min(1,"messageList.type is required"),sender:i.z.object({userId:i.z.string().min(1,"messageList.sender.userId is required"),nickname:i.z.string().optional(),avatarUrl:i.z.string().optional()}),conversationId:i.z.string().min(1,"messageList.conversationId is required"),conversationType:D,timestamp:i.z.number().int().positive("messageList.timestamp must be positive"),body:i.z.record(i.z.unknown()),combineLevel:i.z.number().int().min(0).max(10).optional()}).passthrough(),q=e=>e.superRefine((e,t)=>{e.receiverList&&"singleChat"===e.conversationType&&t.addIssue({code:i.z.ZodIssueCode.custom,message:"receiverList is only allowed for group or chat room conversation",path:["receiverList"]}),e.isChatThread&&"groupChat"!==e.conversationType&&t.addIssue({code:i.z.ZodIssueCode.custom,message:"isChatThread is only allowed for group conversation",path:["isChatThread"]}),e.needReadReceipt&&"chatRoom"===e.conversationType&&t.addIssue({code:i.z.ZodIssueCode.custom,message:"needReadReceipt is not allowed for chatRoom conversation",path:["needReadReceipt"]})}),F=q(k.extend({content:i.z.string().min(1,"content is required"),targetLanguages:i.z.array(i.z.string().min(1)).optional()})),B=q(k.extend({originalUrl:i.z.string().min(1,"originalUrl is required").optional(),filename:i.z.string().min(1,"filename is required").optional(),filetype:i.z.string().min(1,"filetype is required").optional(),width:i.z.number().positive("width must be positive").optional(),height:i.z.number().positive("height must be positive").optional(),isGif:i.z.boolean().optional(),isOriginalImage:i.z.boolean().optional(),fileLength:i.z.number().positive("fileLength must be positive").optional(),data:V.optional(),thumbnailUrl:i.z.string().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),G=q(k.extend({originalUrl:i.z.string().min(1,"originalUrl is required").optional(),filename:i.z.string().min(1,"filename is required").optional(),filetype:i.z.string().min(1,"filetype is required").optional(),fileSize:i.z.number().positive("fileSize must be positive").optional(),fileLength:i.z.number().positive("fileLength must be positive").optional(),data:V.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),K=q(k.extend({originalUrl:i.z.string().min(1,"originalUrl is required").optional(),filename:i.z.string().min(1,"filename is required").optional(),filetype:i.z.string().min(1,"filetype is required").optional(),duration:i.z.number().positive("duration must be positive"),fileLength:i.z.number().positive("fileLength must be positive").optional(),data:V.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),j=q(k.extend({originalUrl:i.z.string().min(1,"originalUrl is required").optional(),filename:i.z.string().min(1,"filename is required").optional(),filetype:i.z.string().min(1,"filetype is required").optional(),duration:i.z.number().positive("duration must be positive"),width:i.z.number().positive("width must be positive").optional(),height:i.z.number().positive("height must be positive").optional(),fileLength:i.z.number().positive("fileLength must be positive").optional(),thumbnailUrl:i.z.string().min(1).optional(),data:V.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),H=q(k.extend({latitude:i.z.number(),longitude:i.z.number(),address:i.z.string().min(1).optional(),buildingName:i.z.string().min(1).optional()})),X=q(k.extend({action:i.z.string().min(1,"action is required")})),Q=q(k.extend({event:i.z.string().min(1,"event is required"),params:i.z.record(i.z.string()).optional()})),W=q(k.extend({title:i.z.string().min(1,"title is required"),summary:i.z.string().min(1,"summary is required"),compatibleText:i.z.string().min(1).optional(),messageList:i.z.array(P).min(1,"messageList must not be empty").max(300,"messageList max length is 300")})),Y=t=>{const r=t?.userId?.trim();if(!r)throw new e.ValidationError("sender.userId is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});return{userId:r,nickname:t?.nickname,avatarUrl:t?.avatarUrl}},Z=()=>c(),J=(t,r)=>{if(t)return t;if(!r)throw new e.ValidationError("url or data is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"url",message:"url or data is required",rule:"required"}]}});const a=l(r);if(!a)throw new e.ValidationError("Failed to resolve local url",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"url",message:"Failed to resolve local url",rule:"invalid_format"}]}});return a},ee=e=>!!e.isGif||(e.isOriginalImage??!1),te=(e,t,r,a,i)=>({msgServerId:"",msgLocalId:i??c(),from:t.userId,to:e.conversationId,sender:t,conversationId:e.conversationId,conversationType:e.conversationType,type:r,sendStatus:"sending",ext:e.ext??{},timestamp:e.timestamp??Date.now(),body:a,direct:"SEND",isOnline:!0,receiverList:e.receiverList,deliverOnlineOnly:e.deliverOnlineOnly,webhookEnv:e.webhookEnv,priority:e.priority,needReadReceipt:e.needReadReceipt,isPeerRead:"singleChat"!==e.conversationType&&void 0,isChatThread:e.isChatThread}),re=(e,t)=>{const r=E.validateOrThrow(W,e),a=r.messageList,i=Y(t);y(a);const s=v(a);I(s);const o={title:r.title,summary:r.summary,messageList:a,filename:"combine",filetype:"application/octet-stream",combineLevel:s},d=te(r,i,"combine",o);return((e,t)=>{t&&n.set(e,t)})(d,r.compatibleText),d},ae=t=>{const{orgName:r,appName:a}=e.parseAppKey(t.appKey);return`/${r}/${a}`},ie=e=>{if("undefined"!=typeof Buffer)return new Uint8Array(Buffer.from(e,"base64"));const t=atob(e),r=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)r[a]=t.charCodeAt(a);return r},se=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),oe=async t=>{try{return await t()}catch(r){if(!(r instanceof e.RestBusinessError))throw r;const t=(t=>{const r="string"==typeof t.details?.serverMessage?t.details.serverMessage:void 0;switch(t.code){case e.ERROR_CODES.SERVICE_NOT_ENABLED:case e.ERROR_CODES.TRANSLATE_SERVICE_NOT_ENABLED:return"Translation service is not enabled";case e.ERROR_CODES.TRANSLATE_PARAM_INVALID:return r?.includes("too long")?"Translation text is too long":r?.includes("target language")?"Invalid target language":"Invalid translation request";case e.ERROR_CODES.TRANSLATE_USAGE_LIMIT:return"Translation quota has been reached";case e.ERROR_CODES.TRANSLATE_FAILED:return"Translation service error";default:return}})(r);if(!t)throw r;throw new e.RestBusinessError(`REST business error: ${t}`,{code:r.code,details:r.details})}},ne=e=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):"",de=e=>{if("string"!=typeof e)return"";const t=e.trim();return t&&"undefined"!==t&&"null"!==t?t:""},le=e=>({userId:e}),ce=(t,r)=>{if(!se(t)||!se(t.data))throw e.createRestBusinessError({apiName:r,message:`${r} response data is invalid`,mapped:!1});return t.data},ge=(t,r)=>{if(!se(t)||!Array.isArray(t.data))throw e.createRestBusinessError({apiName:r,message:`${r} response data is invalid`,mapped:!1});return t.data},ue=(e,t)=>Array.isArray(e)?e:ge(e,t),me={txt:"text",img:"image",video:"video",file:"file",loc:"location",custom:"custom",combine:"combine"},pe={text:"txt",image:"img",video:"video",file:"file",location:"loc",custom:"custom",combine:"combine"},he={chat:"singleChat",chatroom:"chatRoom",groupchat:"groupChat",singleChat:"singleChat",chatRoom:"chatRoom",groupChat:"groupChat"},ye=(t,r,a)=>{if(!r)return"";if(r.includes("em-redirect"))return r;const{orgName:i,appName:s}=e.parseAppKey(t.appKey),o=r.indexOf("/chatfiles/"),n=o>=0?r.slice(o):r,d=`${t.restBaseUrl}/${i}/${s}${n}`;return e.appendAttachUrlParams(d,a)},ve=e=>{if(!e||"object"!=typeof e)return;if(Array.isArray(e))return e;const t=Object.values(e),r=[];for(const a of t)Array.isArray(a)&&r.push(...a);return r.length>0?r:void 0},Ie=(e,t,r)=>{const a=ne(r.contentType??r.type),i=pe[a];if(!i)return null;const s=se(r.content)?r.content:{},o=((e,t)=>{const r=ne(t.conversationType);if("groupchat"===r||"chatroom"===r)return ne(t.receiverId);const a=ne(t.senderId);return a===e?ne(t.receiverId):a})(t,r),n=he[ne(r.conversationType)]??"singleChat",d={msgServerId:ne(r.messageId),msgLocalId:ne(r.messageId),from:ne(r.senderId),to:ne(r.receiverId),conversationId:o,conversationType:n,type:i,ext:se(r.ext)?r.ext:{},timestamp:"number"==typeof r.sentTime?r.sentTime:new Date(ne(r.sentTime)).getTime(),sender:{userId:ne(r.senderId)},highlight:ve(r.highlight),text:"string"==typeof r.text?r.text:void 0};let l;const c=ne(s.remotePath??s.url),g=ne(s.secret??s.secretKey);switch(i){case"txt":l={type:"txt",content:ne(s.message??r.text)};break;case"img":{const t=ye(e,c,g);l={type:"img",url:t,thumb:s.thumb?ye(e,ne(s.thumb),ne(s.thumb_secret??s.thumbnailSecretKey)):`${t}&thumbnail=true`,secret:g,width:Number(s.width??(se(s.size)?s.size.width:0))||0,height:Number(s.height??(se(s.size)?s.size.height:0))||0,fileLength:Number(s.file_length??s.fileLength??0)};break}case"video":l={type:"video",url:ye(e,c,g),thumb:s.thumb||s.thumbnailRemotePath?ye(e,ne(s.thumb??s.thumbnailRemotePath),ne(s.thumb_secret??s.thumbnailSecretKey)):"",secret:g,filename:ne(s.filename??s.displayName),duration:Number(s.length??s.duration??0),fileLength:Number(s.file_length??s.fileLength??0)};break;case"file":l={type:"file",url:ye(e,c,g),secret:g,filename:ne(s.filename??s.displayName),fileLength:Number(s.file_length??s.fileLength??0)};break;case"loc":l={type:"loc",latitude:Number(s.lat??s.latitude??0),longitude:Number(s.lng??s.longitude??0),address:ne(s.addr??s.address),buildingName:ne(s.buildingName)};break;case"custom":l={type:"custom",customEvent:ne(s.customEvent),customExts:se(s.customExts)?s.customExts:{}};break;default:return null}return{...d,body:l}},Ee=async(e,t,r)=>{const a=`${ae(t)}/users/${t.userId}/messages/search/get`,i=((e,t)=>{const{option:r,pageNum:a=1,pageSize:i=20}=e,s=r.keywordList.map(e=>e.trim()).filter(e=>e.length>0),o={searchMode:"default",highlightEnable:!0,page:a,size:i};return 1===s.length?o.keyword=s[0]:(o.keywords=s,o.keywordMatch="and"===r.keywordListMatchType?"all":"any"),r.conversationId&&("singleChat"===r.conversationType?o.participantPairs=[{userId1:t,userId2:r.conversationId}]:"groupChat"===r.conversationType?o.groupIds=[r.conversationId]:"chatRoom"===r.conversationType&&(o.chatroomIds=[r.conversationId])),r.msgTypes&&r.msgTypes.length>0&&(o.contentType=r.msgTypes.map(e=>me[e]??e).join(",")),void 0!==r.startTime&&(o.startTime=r.startTime),void 0!==r.endTime&&(o.endTime=r.endTime),r.searchScope&&(o.searchExt=r.searchScope),r.direction&&(o.sort="up"===r.direction?"sentTime:asc":"sentTime:desc"),{data:o}})(r,t.userId),s=await e.post(a,i,{operation:"searchMessages"}),o=se(s)?s:{},n=se(o.data)?o.data:o,d=se(n.data)?n.data:n,l=Array.isArray(d.items)?d.items:Array.isArray(d.list)?d.list:[],c=se(d.pagination)?d.pagination:d,g=Number(c.pageNum??c.page??r.pageNum??1),u=Number(c.pageSize??c.size??r.pageSize??20),m=Number(c.totalPages??0),p=1===c.isFinished||g>=m,h=[];for(const y of l){if(!se(y))continue;const e=Ie(t,t.userId,y);e&&h.push(e)}return{messages:h,pageNum:g,pageSize:u,totalPages:m,isLast:p}},fe=t=>{const{orgName:r,appName:a}=e.parseAppKey(t.appKey);return`/api/sdk/v1/${r}/${a}`},_e=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Re=e=>_e(e)&&"string"==typeof e.path&&e.path.trim().length>0,be=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||Re(e),Ce=e=>{if(!_e(e))return;return{data:_e(e.data)?e.data:void 0,error:_e(e.error)?e.error:void 0}},Te=(t,r)=>{const a=Ce(t),i=a?.data?.text;if("string"!=typeof i)throw new e.SDKError(`${r} response data is invalid`,e.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:{api:r,response:t}});return i},Oe=(t,r,a,i="sdk")=>"auth"===i?new e.AuthenticationError(t,{code:r,details:a}):"validation"===i?new e.ValidationError(t,{code:r,details:a}):new e.SDKError(t,r,{details:a}),Le=e=>!(void 0===e||_e(e)&&!Array.isArray(e))||(void 0!==e?.format&&"string"!=typeof e.format||(void 0!==e?.sampleRate&&"number"!=typeof e.sampleRate||(void 0!==e?.bitsPerSample&&"number"!=typeof e.bitsPerSample||void 0!==e?.channels&&"number"!=typeof e.channels))),Ne=e=>{if(!e)return;const t=(e.split("#")[0]?.split("?")[0]??"").split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0},Se=t=>{const{serviceCode:r,serviceMessage:a}=(t=>{const r=t instanceof e.SDKError&&_e(t.details)?t.details:void 0,a=Ce(r?.rawResponse??r?.response??t),i=r?.serverCode??a?.error?.code,s=r?.serverMessage??a?.error?.message;return{serviceCode:"string"==typeof i||"number"==typeof i?String(i):void 0,serviceMessage:"string"==typeof s?s:void 0}})(t);if(t instanceof e.UploadError)return Oe("File upload failed",e.ERROR_CODES.UPLOAD_REQUEST_FAILED,{cause:t.details});if(t instanceof e.SDKError&&!r)return t;if(r)switch(r){case"4041001":return Oe("File not found",e.ERROR_CODES.VOICE_TO_TEXT_FILE_NOT_FOUND,{serviceCode:r,serviceMessage:a});case"4001002":return Oe("Invalid file",e.ERROR_CODES.VOICE_TO_TEXT_FILE_INVALID,{serviceCode:r,serviceMessage:a},"validation");case"5021001":return Oe("File upload failed",e.ERROR_CODES.UPLOAD_REQUEST_FAILED,{serviceCode:r,serviceMessage:a});case"4001003":return Oe("Voice duration exceeds 60 seconds",e.ERROR_CODES.VOICE_TO_TEXT_FILE_DURATION_TOO_LONG,{serviceCode:r,serviceMessage:a},"validation");case"4031001":return Oe("Voice-to-text service is not enabled",e.ERROR_CODES.SERVICE_NOT_ENABLED,{serviceCode:r,serviceMessage:a});case"4031002":return Oe("Beta service usage limit exceeded",e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,{serviceCode:r,serviceMessage:a});case"4001001":return"string"==typeof(i=a)&&i.toLowerCase().includes("uploaded file exceeds")?Oe("File too large",e.ERROR_CODES.VOICE_TO_TEXT_FILE_TOO_LARGE,{serviceCode:r,serviceMessage:a}):Oe(a||"Missing or invalid request parameter",e.ERROR_CODES.VALIDATION_REQUIRED,{serviceCode:r,serviceMessage:a},"validation");case"5021003":case"5001003":return Oe("Voice-to-text failed",e.ERROR_CODES.VOICE_TO_TEXT_FAILED,{serviceCode:r,serviceMessage:a});case"4011001":return Oe(a||"Unauthorized or invalid token",e.ERROR_CODES.AUTH_UNAUTHORIZED,{serviceCode:r,serviceMessage:a},"auth");default:return Oe(a||(t instanceof Error?t.message:"Voice-to-text failed"),e.ERROR_CODES.VOICE_TO_TEXT_FAILED,{serviceCode:r,serviceMessage:a})}var i;return t instanceof e.SDKError?Oe(t.message,t.code,t.details):Oe(t instanceof Error?t.message:"Voice-to-text failed",e.ERROR_CODES.VOICE_TO_TEXT_FAILED)},we=(t,r)=>{if(!_e(a=t)||"string"!=typeof a.filename||"string"!=typeof a.filetype||"number"!=typeof a.duration||"type"in a&&void 0!==a.type&&"voice"!==a.type)throw Oe("Invalid file",e.ERROR_CODES.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody"},"validation");var a;if(Le(r))throw Oe("Invalid file",e.ERROR_CODES.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!t.url)throw Oe("File not found",e.ERROR_CODES.VOICE_TO_TEXT_FILE_NOT_FOUND,{path:"voiceMessageBody.url"});if(!Ne(t.url))throw Oe("Invalid file",e.ERROR_CODES.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody.url"},"validation");return t},Ae=(t,r)=>{if(Le(r))throw Oe("Invalid file",e.ERROR_CODES.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!be(t))throw Oe("Invalid file",e.ERROR_CODES.VOICE_TO_TEXT_FILE_INVALID,{path:"file"},"validation");return t},Me=async(t,r,a,i)=>{const s=we(a,i),o=Ne(s.url);if(!o)throw((t,r,a,i="invalid")=>new e.ValidationError(t,{code:r,details:{fields:[{path:a,message:t,rule:i}]}}))("File not found",e.ERROR_CODES.VOICE_TO_TEXT_FILE_NOT_FOUND,"voiceMessageBody.url");try{const e=await t.post(`${fe(r)}/speech/transcriptions`,{data:{fileId:o,username:r.userId,...i?{audio:i}:{}}},{operation:"voiceMessageToText"});return{text:Te(e,"voiceMessageToText")}}catch(n){throw Se(n)}},De=i.z.object({keywordList:i.z.array(i.z.string()).min(1,"keywordList must not be empty").max(5,"keywordList must have at most 5 keywords").refine(e=>e.map(e=>e.trim()).filter(e=>e.length>0).length>0,"keywordList must contain at least one non-empty keyword"),keywordListMatchType:i.z.enum(["or","and"]).optional(),conversationId:i.z.string().min(1).optional(),conversationType:i.z.enum(["singleChat","groupChat","chatRoom"]).optional(),msgTypes:i.z.array(i.z.enum(["txt","img","video","file","loc","custom","combine"])).optional(),startTime:i.z.number().optional(),endTime:i.z.number().optional(),searchScope:i.z.enum(["none","with","only"]).optional(),direction:i.z.enum(["up","down"]).optional()}).refine(e=>void 0!==e.conversationId===(void 0!==e.conversationType),{message:"conversationId and conversationType must be provided together"}).refine(e=>void 0!==e.startTime===(void 0!==e.endTime),{message:"startTime and endTime must be provided together"}).refine(e=>void 0===e.startTime||void 0===e.endTime||e.endTime>=e.startTime,{message:"endTime must be >= startTime"}),Ue=i.z.object({option:De,pageNum:i.z.number().int().min(1).default(1),pageSize:i.z.number().int().min(1).max(100).default(20)}),xe=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{sendMessage:{range:"1,4,100,108,110,202,210,213-215,219-222,300-301,303,305,402,405-406,500-501,505-510,602-603,606-607,1200,1299",localErrors:{sendMessage:{operation_cancelled:{code:1,retryable:!1},upload_invalid_appkey:{code:100,retryable:!1},validation_invalid:{code:110,retryable:!1},not_connected:{code:300,retryable:!0},request_timeout:{code:301,retryable:!0},send_failed:{code:303,retryable:!1},upload_failed:{code:402,retryable:!0},file_too_large:{code:405,retryable:!1},file_content_improper:{code:406,retryable:!1},encode_failed:{code:500,retryable:!1}}},errors:{SERVICE_LIMIT_EXCEEDED:{code:4,retryable:!1},TOKEN_EXPIRED:{code:108,retryable:!1},AUTH_FAILED:{code:202,retryable:!1},PERMISSION_DENIED:{code:210,retryable:!1},BIND_ANOTHER_DEVICE:{code:213,retryable:!1},TOO_MANY_DEVICES:{code:214,retryable:!1},USER_MUTED:{code:215,retryable:!1},USER_MUTED_BY_ADMIN:{code:219,retryable:!1},USER_DEVICE_CHANGED:{code:220,retryable:!1},USER_NOT_ON_ROSTER:{code:221,retryable:!1},BLOCKED_BY_RECIPIENT:{code:222,retryable:!1,aliases:["blocked"]},SERVER_SERVING_DISABLED:{code:305,retryable:!1},MESSAGE_INCLUDE_ILLEGAL_CONTENT:{code:501,retryable:!1},SERVICE_NOT_ENABLED:{code:505,retryable:!1},MESSAGE_EXPIRED:{code:506,retryable:!1},MESSAGE_ILLEGAL_WHITELIST:{code:507,retryable:!1},MESSAGE_EXTERNAL_LOGIC_BLOCKED:{code:508,retryable:!1},MESSAGE_CURRENT_LIMITING:{code:509,retryable:!0},MESSAGE_SIZE_LIMIT:{code:510,retryable:!1},GROUP_NOT_JOINED:{code:602,retryable:!1},GROUP_PERMISSION_DENIED:{code:603,retryable:!1},GROUP_NOT_EXIST:{code:606,retryable:!1},GROUP_DISABLED:{code:607,retryable:!1},MESSAGE_BLOCKED:{code:1200,retryable:!1},THIRD_DEFAULT_FAILED:{code:1299,retryable:!1}}},getHistoryMessages:{range:"4,110,202,505",localErrors:{getHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},page_size_exceeded:{code:110,aliases:["pull number cannot be greater","limit is to large"],retryable:!1}}},removeHistoryMessages:{range:"110,112,202,505",localErrors:{removeHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},query_param_reaches_limit:{code:112,aliases:["delete msg list limit"],retryable:!1}}},getGroupMessageReadUsers:{range:"4,110,500",localErrors:{getGroupMessageReadUsers:{validation_invalid:{code:110,retryable:!1}}},errors:{message_not_found:{code:500,retryable:!1}}},recallMessage:{range:"110,201,300,504,505",localErrors:{recallMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},recall_time_limit:{code:504,retryable:!1},recall_disabled:{code:505,retryable:!1}}},updateMessage:{range:"110,111,201,210,300,511",localErrors:{modifyMessage:{validation_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1},not_login:{code:201,retryable:!0},permission_denied:{code:210,retryable:!1},not_connected:{code:300,retryable:!0},edit_failed:{code:511,retryable:!0}}},downloadMessageAttachment:{range:"400,401,403,407",localErrors:{downloadAttachment:{validation_invalid:{code:401,retryable:!1}}},errors:{not_found:{code:400,httpStatus:404,retryable:!1},invalid:{code:401,retryable:!1},download_failed:{code:403,retryable:!0},expired:{code:407,httpStatus:404,retryable:!1}}},downloadAndParseCombineMessage:{range:"110,401,403,500",localErrors:{downloadAndParseCombineMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_param:{code:110,retryable:!1},invalid_type:{code:500,retryable:!1},parse_failed:{code:401,retryable:!0},download_failed:{code:403,retryable:!0}}},addReaction:{range:"110,302,505,600,602,1300-1302",localErrors:{addReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{reaction_already_operated:{code:1301,retryable:!1},reaction_reach_limit:{code:1300,retryable:!1},group_not_joined:{code:602,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1},service_not_enabled:{code:505,retryable:!1},server_busy:{code:302,retryable:!0}}},removeReaction:{range:"110,505,1301,1302",localErrors:{removeReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},getReactionList:{range:"110,505,600",localErrors:{getReactionList:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},group_invalid_id:{code:600,retryable:!1}}},getReactionDetail:{range:"110,505,1302",localErrors:{getReactionDetail:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},pinMessage:{range:"4,110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_limit:{code:4,aliases:["91101"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102"],retryable:!1}}},unpinMessage:{range:"110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getPinnedMessageList:{range:"110,111",errors:{operation_unsupported:{code:111,aliases:["15002"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getSupportedTranslationLanguages:{range:"505",errors:{service_not_enabled:{code:505,aliases:["service not open!"],retryable:!1}}},translateMessage:{range:"505,1110-1113",localErrors:{translateMessage:{validation_invalid:{code:1110,retryable:!1}}},errors:{translate_text_too_long:{code:1110,runtimeMessage:"Translation text is too long",retryable:!1},translate_param_invalid:{code:1110,runtimeMessage:"Invalid target language",retryable:!1},service_not_enabled:{code:1111,runtimeMessage:"Translation service is not enabled",aliases:["service not open!"],retryable:!1},translate_usage_limit:{code:1112,runtimeMessage:"Translation quota has been reached",aliases:["The request has reached the maximum limit"],retryable:!1},translate_failed:{code:1113,runtimeMessage:"Translation service error",aliases:["The request failed, please try again later."],retryable:!1}}},voiceMessageToText:{range:"4,110,202,407-411,505",localErrors:{voiceMessageToText:{validation_invalid:{code:407,retryable:!1},file_not_found:{code:410,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},file_not_found:{code:410,retryable:!1,aliases:["4041001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},voiceFileToText:{range:"4,110,202,402,407-411,505",localErrors:{voiceFileToText:{validation_invalid:{code:407,retryable:!1},upload_required:{code:110,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},upload_failed:{code:402,retryable:!0,aliases:["5021001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},getConversationList:{range:"110",localErrors:{getConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPinnedConversationList:{range:"110",localErrors:{getPinnedConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getConversationListByMark:{range:"110",localErrors:{getConversationListByMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},deleteConversation:{range:"110",localErrors:{deleteConversation:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearConversationUnreadMessageCount:{range:"110,201,300,500",localErrors:{clearConversationUnreadMessageCount:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},clearAllConversationUnreadMessageCount:{range:"201,300,500",errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},sendMessageReadReceipts:{range:"110,300",localErrors:{sendMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_direction:{code:110,retryable:!1},not_connected:{code:300,retryable:!0}}},getGroupMessageReadReceipts:{range:"110,202,210,303",localErrors:{getGroupMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},auth_bad_access_token:{code:202,httpStatus:401,retryable:!1},forbidden_op:{code:210,httpStatus:403,retryable:!1},unknown_exception_error:{code:303,httpStatus:500,retryable:!0}}},setConversationPinned:{range:"110",localErrors:{setConversationPinned:{validation_invalid:{code:110,retryable:!1}}},errors:{}},addConversationMark:{range:"110",localErrors:{addConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},removeConversationMark:{range:"110",localErrors:{removeConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearAllMessagesAndConversations:{range:"",errors:{}},searchMessages:{range:"110,202,303,505",localErrors:{searchMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{parameter_error:{code:110,httpStatus:400,retryable:!1,aliases:["4000005","4000006"]},token_invalid:{code:202,httpStatus:401,retryable:!1,aliases:["4010101"]},service_not_enabled:{code:505,httpStatus:403,retryable:!1,aliases:["4030204"]},app_not_found:{code:110,httpStatus:404,retryable:!1,aliases:["4040302"]},server_error:{code:303,httpStatus:500,retryable:!0,aliases:["5000701","5020801"]}}}}}),ze=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}async sendMessage(e,t){return this.getClientOrThrow().sendMessage(e,t)}createTextMessage(e){return((e,t)=>{const r=E.validateOrThrow(F,e),a=Y(t),i=Z(),s={content:r.content};return r.targetLanguages&&(s.targetLanguages=r.targetLanguages),te(r,a,"text",s,i)})(e,this.buildMessageSenderOrThrow())}createImageMessage(t){return((t,r,a)=>{const i=E.validateOrThrow(B,t),s=Y(r),o=Z(),n=i.data?J(void 0,i.data):"",l=i.originalUrl?e.deriveImageUrls(i.originalUrl,{deriveVariants:!a?.useCustomAttachmentUpload}):void 0;i.data&&d.set(o,i.data);const c=i.isGif??!1,g={localUrl:n,filename:i.filename,filetype:i.filetype,width:i.width,height:i.height,isGif:c,isOriginalImage:ee({isGif:c,isOriginalImage:i.isOriginalImage})};return l?.originalImageUrl&&(g.originalImageUrl=l.originalImageUrl,g.bigImageUrl=l.bigImageUrl,g.thumbnailUrl=l.thumbnailUrl),void 0!==i.fileLength&&(g.fileLength=i.fileLength),i.thumbnailUrl&&(g.thumbnailUrl=i.thumbnailUrl),te(i,s,"image",g,o)})(t,this.buildMessageSenderOrThrow(),this.getClientOrThrow().getMessageCreationOptions())}createFileMessage(e){return((e,t)=>{const r=E.validateOrThrow(G,e),a=Y(t),i=Z(),s=J(r.originalUrl,r.data);r.data&&d.set(i,r.data);const o={url:s,filename:r.filename,filetype:r.filetype};return void 0!==r.fileSize&&(o.fileSize=r.fileSize),void 0!==r.fileLength&&(o.fileLength=r.fileLength),te(r,a,"file",o,i)})(e,this.buildMessageSenderOrThrow())}createVoiceMessage(e){return((e,t)=>{const r=E.validateOrThrow(K,e),a=Y(t),i=Z(),s=J(r.originalUrl,r.data);r.data&&d.set(i,r.data);const o={url:s,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.fileLength&&(o.fileLength=r.fileLength),te(r,a,"voice",o,i)})(e,this.buildMessageSenderOrThrow())}createVideoMessage(e){return((e,t)=>{const r=E.validateOrThrow(j,e),a=Y(t),i=Z(),s=J(r.originalUrl,r.data);r.data&&d.set(i,r.data);const o={url:s,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.width&&(o.width=r.width),void 0!==r.height&&(o.height=r.height),void 0!==r.fileLength&&(o.fileLength=r.fileLength),r.thumbnailUrl&&(o.thumbnailUrl=r.thumbnailUrl),te(r,a,"video",o,i)})(e,this.buildMessageSenderOrThrow())}createLocationMessage(e){return((e,t)=>{const r=E.validateOrThrow(H,e),a=Y(t),i={latitude:r.latitude,longitude:r.longitude};return r.address&&(i.address=r.address),r.buildingName&&(i.buildingName=r.buildingName),te(r,a,"location",i)})(e,this.buildMessageSenderOrThrow())}createCmdMessage(e){return((e,t)=>{const r=E.validateOrThrow(X,e),a=Y(t),i={action:r.action};return void 0!==r.deliverOnlineOnly&&(i.deliverOnlineOnly=r.deliverOnlineOnly),te(r,a,"cmd",i)})(e,this.buildMessageSenderOrThrow())}createCustomMessage(e){return((e,t)=>{const r=E.validateOrThrow(Q,e),a=Y(t),i={event:r.event};return r.params&&(i.params=r.params),te(r,a,"custom",i)})(e,this.buildMessageSenderOrThrow())}createCombineMessage(e){return re(e,this.buildMessageSenderOrThrow())}getConversationList(t){if(void 0!==t?.mark&&(!Number.isInteger(t.mark)||t.mark<0||t.mark>19))throw new e.ValidationError("filter.mark must be an integer between 0 and 19",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"filter.mark",message:"filter.mark must be an integer between 0 and 19",rule:"invalid_format"}]}});const a=(this.getClientOrThrow().getCacheManager()?.loadSessionList()??[]).filter(e=>null!==e.lastMessage&&((void 0===t?.isPinned||e.isPinned===t.isPinned)&&!(void 0!==t?.mark&&!r.hasSessionMark(e,t.mark)))).map(r.toConversationItem);return this.getClientOrThrow().markConversationAccess(a.map(e=>({conversationId:e.conversationId,type:e.conversationType}))),a}setCurrentConversation(e){this.validateConversationLocator(e),this.getClientOrThrow().getCacheManager()?.setCurrentConversation({conversationId:e.conversationId,type:e.conversationType})}resetCurrentConversation(){this.getClientOrThrow().getCacheManager()?.resetCurrentConversation()}getCurrentConversation(){const e=this.getClientOrThrow().getCacheManager()?.getCurrentConversation()??null;return e?{conversationId:e.conversationId,conversationType:e.type}:null}refreshSessionList(e){return this.getClientOrThrow().refreshSessionList(e)}async deleteConversation(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const a=w(t),i=_(r.conversationId,"params.conversationId"),s=b(r.conversationType,"params.conversationType"),o=r.deleteRoamingMessages??!1;if("boolean"!=typeof o)throw f("params.deleteRoamingMessages","params.deleteRoamingMessages must be a boolean");return await e.request(`/${a.orgName}/${a.appName}/user/${a.encodedUserId}/user_channel?resource=${a.encodedResource}`,{method:"DELETE",body:{channel:i,type:"groupChat"===s?"groupChat":C(s),delete_roam:o},operation:"deleteConversation"}),{conversationId:i,conversationType:s,operation:"delete"}})(this.getRestClient(t),t,e),a=this.getClientOrThrow(),i=a.getCacheManager()?.deleteConversation({conversationId:r.conversationId,type:r.conversationType});return i?.changed&&a.emitConversationListUpdate("local"),r}async setConversationPinned(e){const r=this.getRestContextOrThrow(),a=await(async(e,r,a)=>{const i=w(r),s=_(a.conversationId,"params.conversationId"),o=b(a.conversationType,"params.conversationType");if("boolean"!=typeof a.pinned)throw f("params.pinned","params.pinned must be a boolean");const n="groupChat"===o?"groupChat":C(o),d=a.pinned?await e.post(`/${i.orgName}/${i.appName}/sdk/user/${i.encodedUserId}/user_channel/top?resource=${i.encodedResource}`,{type:n,to:s},{operation:"setConversationPinned"}):await e.delete(`/${i.orgName}/${i.appName}/sdk/user/${i.encodedUserId}/user_channel/top?type=${encodeURIComponent(n)}&to=${encodeURIComponent(s)}&resource=${i.encodedResource}`,{operation:"setConversationPinned"}),l=t.isRecord(d)&&t.isRecord(d.data)?d.data:{};return{conversationId:s,conversationType:o,operation:"setPinned",isPinned:"boolean"==typeof l.is_top?l.is_top:a.pinned,pinnedTime:"number"==typeof l.update_top_status_time?l.update_top_status_time:a.pinned?Date.now():0}})(this.getRestClient(r),r,e),i=this.getClientOrThrow().getCacheManager(),s=i?.applyConversationPinnedMutation({conversationId:a.conversationId,type:a.conversationType,isPinned:a.isPinned??e.pinned,pinnedTime:a.pinnedTime});return s?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),a}async addConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>A(e,t,r,!0))(this.getRestClient(t),t,e),a=this.getClientOrThrow().getCacheManager(),i=a?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return i?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async removeConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>A(e,t,r,!1))(this.getRestClient(t),t,e),a=this.getClientOrThrow().getCacheManager(),i=a?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return i?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async clearAllMessagesAndConversations(){const e=this.getRestContextOrThrow();await(async(e,t)=>{const r=w(t);await e.post(`/${r.orgName}/${r.appName}/sdk/message/roaming/user/${r.encodedUserId}/delete/all?resource=${r.encodedResource}`,void 0,{operation:"clearAllMessagesAndConversations"})})(this.getRestClient(e),e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversations();r?.changed&&t.emitConversationListUpdate("local")}async pinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>M(e,t,r,!0))(this.getRestClient(t),t,e))}async unpinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>M(e,t,r,!1))(this.getRestClient(t),t,e))}async getPinnedMessageList(e){const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,r,a)=>{const i=w(r),s=_(a.conversationId,"params.conversationId"),o=b(a.conversationType,"params.conversationType"),n=await e.get(`/${i.orgName}/${i.appName}/sdk/user/${i.encodedUserId}/user_channel/pin?to=${encodeURIComponent(s)}&type=${encodeURIComponent(C(o))}&limit=${String(20)}`,{operation:"getPinnedMessageList"}),d=t.isRecord(n)&&t.isRecord(n.data)?n.data:{};return{items:(Array.isArray(d.msg_infos)?d.msg_infos:[]).reduce((e,a)=>{if(!t.isRecord(a))return e;const i="string"==typeof a.pin_msg_id?a.pin_msg_id:t.isRecord(a.message)&&"string"==typeof a.message.id?a.message.id:"";if(!i)return e;const n="number"==typeof a.pin_opt_at?a.pin_opt_at:0,d=N(a.message,{messageId:i,conversationId:s,conversationType:o,currentUserId:r.userId,timestamp:n});return d?(e.push({messageId:i,conversationId:s,conversationType:o,operatorId:"string"==typeof a.pin_operator?a.pin_operator:void 0,pinnedAt:n,message:d}),e):e},[])}})(this.getRestClient(r),r,e))}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async clearConversationUnreadMessageCount(t){this.validateUnreadConversationLocator(t);const r=this.getClientOrThrow(),a=r.getCacheManager()?.clearConversationUnreadMessageCount({conversationId:t.conversationId,type:t.conversationType});a?.changed&&r.emitConversationListUpdate("local");try{await this.requireConnectedClient().sendMessageAction({kind:"clearConversationUnreadMessageCount",conversationId:t.conversationId,conversationType:t.conversationType,sendToPeer:!1},(e,t)=>this.buildActionError(e,t))}catch(i){if(!a?.matched)throw i;e.logger.warn("Conversation unread remote sync failed after local clear",{conversationId:t.conversationId,conversationType:t.conversationType,error:i})}}async sendMessageReadReceipts(e){this.validateSendMessageReadReceiptsParams(e),await this.requireConnectedClient().sendMessageAction({kind:"sendMessageReadReceipts",conversationId:e.conversationId,conversationType:e.conversationType,messageIds:e.messageIds},(e,t)=>this.buildActionError(e,t))}async clearAllConversationUnreadMessageCount(){await this.requireConnectedClient().sendMessageAction({kind:"clearAllConversationUnreadMessageCount",conversationId:this.getCurrentUserIdOrThrow(),conversationType:"singleChat",sendToPeer:!1,clearAllUnreadMessageCount:!0},(e,t)=>this.buildActionError(e,t));const e=this.getClientOrThrow(),t=e.getCacheManager()?.clearAllConversationUnreadMessageCount();t?.changed&&e.emitConversationListUpdate("local")}async recallMessage(e){this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId"),await this.requireConnectedClient().sendMessageAction({kind:"recall",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,ext:e.ext},(e,t)=>this.buildActionError(e,t));return{messageId:e.messageId,conversationId:e.conversationId,conversationType:e.conversationType,timestamp:Date.now()}}async modifyMessage(t){if(this.validateConversationLocator(t),this.requireNonEmptyString(t.messageId,"messageId"),"text"!==t.message.type&&"custom"!==t.message.type)throw new e.ValidationError("only text and custom messages are editable",{code:e.ERROR_CODES.OPERATION_UNSUPPORTED});await this.requireConnectedClient().sendMessageAction({kind:"update",conversationId:t.conversationId,conversationType:t.conversationType,messageId:t.messageId,body:t.message.body,messageType:t.message.type,ext:t.message.ext},(e,t)=>this.buildActionError(e,t));const r=Date.now(),a=this.getCurrentUserIdOrThrow(),i={operatorId:a,operationCount:1,operationTime:r};return{msgServerId:t.messageId,msgLocalId:"",from:a,to:t.conversationId,sender:{userId:a},conversationId:t.conversationId,conversationType:t.conversationType,type:t.message.type,sendStatus:"sent",ext:t.message.ext,timestamp:r,body:t.message.body,direct:"SEND",modifiedInfo:i}}async getHistoryMessages(e){if(this.validateConversationLocator(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r,a)=>{const i=`${ae(t)}/users/${t.userId}/messageroaming`,s=await e.post(i,{queue:"singleChat"===r.conversationType?`${r.conversationId}@easemob.com`:`${r.conversationId}@conference.easemob.com`,start:r.cursor&&r.cursor.length>0?r.cursor:-1,pull_number:r.pageSize??20,is_positive:"down"===r.searchDirection,msgType:(r.messageTypes??[]).join(","),end:-1,startTime:r.startTime??null,endTime:r.endTime??null,userIds:"singleChat"===r.conversationType?null:r.senderIds&&r.senderIds.length>0?r.senderIds:null},{operation:"getHistoryMessages"}),o=ce(s,"getHistoryMessages"),n=Array.isArray(o.msgs)?o.msgs:[],d=[];for(const l of n){if(!se(l)||"string"!=typeof l.msg||0===l.msg.length)continue;const e=a(ie(l.msg));e&&d.push(e)}return{items:d,cursor:de(o.next_key),hasMore:!0!==o.is_last&&d.length>0}})(this.getRestClient(t),t,e,e=>this.getClientOrThrow().decodeServerMessageMeta(e)))}async searchMessages(e){const t=E.validateOrThrow(Ue,e),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>Ee(this.getRestClient(r),r,t))}async downloadAttachment(e){return this.getClientOrThrow().downloadAttachment(e.message)}async downloadAndParseCombineMessage(e){return this.getClientOrThrow().downloadAndParseCombinePayload(this.resolveDownloadCombineMessageParams(e))}async removeHistoryMessages(e){if(this.validateConversationLocator(e),!e.messageIds&&!e.beforeTimestamp)throw this.buildValidationError("messageIds or beforeTimestamp is required","removeHistoryMessages");if(e.messageIds&&0===e.messageIds.length)throw this.buildValidationError("messageIds cannot be empty","messageIds");if(void 0!==e.beforeTimestamp&&(!Number.isInteger(e.beforeTimestamp)||e.beforeTimestamp<=0))throw this.buildValidationError("beforeTimestamp must be a positive integer","beforeTimestamp");const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const a="singleChat"===r.conversationType?"userId":"groupId",i="singleChat"===r.conversationType?"chat":"group",s=encodeURIComponent(t.clientResource),o=r.messageIds?`${ae(t)}/sdk/message/roaming/${i}/user/${t.userId}?${a}=${encodeURIComponent(r.conversationId)}&msgIdList=${encodeURIComponent(r.messageIds.join(","))}&resource=${s}`:`${ae(t)}/sdk/message/roaming/${i}/user/${t.userId}/time?${a}=${encodeURIComponent(r.conversationId)}&delTime=${r.beforeTimestamp}&resource=${s}`;await e.delete(o,{operation:"removeHistoryMessages"})})(this.getRestClient(t),t,e))}async getGroupMessageReadUsers(e){if(this.requireNonEmptyString(e.groupId,"groupId"),this.requireNonEmptyString(e.messageId,"messageId"),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow(),r=await this.executeRestOperation(()=>(async(e,t,r)=>{const a=s.createQueryParams();a.set("limit",String(r.pageSize??10)),r.cursor&&a.set("key",r.cursor);const i=`${ae(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/${encodeURIComponent(r.messageId)}?${a.toString()}`,o=await e.get(i,{operation:"getGroupMessageReadUsers"}),n=ce(o,"getGroupMessageReadUsers"),d=se(n.group_ack)?n.group_ack:n,l=(Array.isArray(d.userlist)?d.userlist:[]).map(e=>se(e)&&"string"==typeof e.username?{userId:e.username,user:le(e.username),ackId:"string"==typeof e.meta_id?e.meta_id:void 0,timestamp:"number"==typeof e.timestamp?e.timestamp:void 0,ackContent:"string"==typeof e.ack_content?e.ack_content:void 0}:null).filter(e=>null!==e);return{groupId:r.groupId,messageId:"string"==typeof n.ackmid?n.ackmid:r.messageId,users:l,count:"number"==typeof d.total?d.total:l.length,cursor:de(d.next_key),hasMore:!0!==d.is_last&&l.length>0}})(this.getRestClient(t),t,e));return await this.hydrateGroupMessageReadUsers(e.groupId,r)}async getGroupMessageReadReceipts(e){this.requireNonEmptyString(e.groupId,"groupId");const t=this.validateMessageIdList(e.messageIds,"messageIds"),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=`${ae(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/batch`,i=await e.post(a,{messageIds:r.messageIds},{operation:"getGroupMessageReadReceipts"});return ge(i,"getGroupMessageReadReceipts").map(e=>se(e)&&"string"==typeof e.ackmid&&"number"==typeof e.total?{messageId:e.ackmid,count:e.total}:null).filter(e=>null!==e)})(this.getRestClient(r),r,{groupId:e.groupId.trim(),messageIds:t}))}async addReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{await e.post(`${ae(t)}/reaction/user/${t.userId}`,{msgId:r.messageId,message:r.reaction},{operation:"addReaction"})})(this.getRestClient(t),t,e))}async removeReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const a=`${ae(t)}/reaction/user/${t.userId}?msgId=${encodeURIComponent(r.messageId)}&message=${encodeURIComponent(r.reaction)}`;await e.delete(a,{operation:"removeReaction"})})(this.getRestClient(t),t,e))}async getReactionList(e){if(!e.messageId||Array.isArray(e.messageId)&&0===e.messageId.length)throw this.buildValidationError("messageId is required","messageId");"groupChat"===e.conversationType&&this.requireNonEmptyString(e.groupId??"","groupId");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=s.createQueryParams(),i="string"==typeof r.messageId?r.messageId:[...r.messageId].join(",");a.set("msgIdList",i),a.set("msgType","groupChat"===r.conversationType?"group":"chat"),r.groupId&&a.set("groupId",r.groupId);const o=await e.get(`${ae(t)}/reaction/user/${t.userId}?${a.toString()}`,{operation:"getReactionList"});return ge(o,"getReactionList").map(e=>{if(!se(e)||"string"!=typeof e.msgId)return null;const t=Array.isArray(e.reactionList)?e.reactionList:[];return{messageId:e.msgId,reactions:t.map(e=>se(e)&&"string"==typeof e.reaction?{reaction:e.reaction,count:"number"==typeof e.count?e.count:0,isAddedBySelf:!0===e.state,userIds:Array.isArray(e.userList)?e.userList.filter(e=>"string"==typeof e):[]}:null).filter(e=>null!==e)}}).filter(e=>null!==e)})(this.getRestClient(t),t,e))}async getReactionDetail(e){if(this.validateReactionParams(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=s.createQueryParams();a.set("msgId",r.messageId),a.set("message",r.reaction),a.set("cursor",r.cursor??""),a.set("limit",String(r.pageSize??20));const i=await e.get(`${ae(t)}/reaction/user/${t.userId}/detail?${a.toString()}`,{operation:"getReactionDetail"}),o=ce(i,"getReactionDetail"),n=Array.isArray(o.reactionUserList)?o.reactionUserList.map(e=>se(e)&&"string"==typeof e.userId?{userId:e.userId,user:le(e.userId),createdAt:"string"==typeof e.createdAt?e.createdAt:void 0}:null).filter(e=>null!==e):[],d=Array.isArray(o.userList)?o.userList.filter(e=>"string"==typeof e).map(e=>({userId:e,user:le(e)})):[],l=n.length>0?n:d;return{reaction:"string"==typeof o.reaction?o.reaction:r.reaction,count:"number"==typeof o.count?o.count:l.length,isAddedBySelf:!0===o.state,reactionUsers:l,cursor:de(o.cursor),hasMore:de(o.cursor).length>0,createdAt:"string"==typeof o.createdAt?o.createdAt:void 0}})(this.getRestClient(t),t,e))}async getSupportedTranslationLanguages(){const e=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t)=>{const r=await oe(()=>e.get(`${ae(t)}/users/${t.userId}/translate/support/language`,{operation:"getSupportedTranslationLanguages"}));return ue(r,"getSupportedTranslationLanguages").map(e=>se(e)&&"string"==typeof e.code?{code:e.code,name:"string"==typeof e.name?e.name:e.code,nativeName:"string"==typeof e.nativeName?e.nativeName:e.code}:null).filter(e=>null!==e)})(this.getRestClient(e),e))}async translateMessage(t){if("text"!==t.message.type)throw new e.ValidationError("only text messages can be translated",{code:e.ERROR_CODES.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"message.type",message:"must be text",rule:"message_type"}]}});const r=t.message.body.content.trim();if(0===r.length)throw new e.ValidationError("message text is required",{code:e.ERROR_CODES.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"message.body.content",message:"is required",rule:"required"}]}});if(!Array.isArray(t.targetLanguages)||0===t.targetLanguages.length)throw new e.ValidationError("targetLanguages is required",{code:e.ERROR_CODES.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"targetLanguages",message:"is required",rule:"required"}]}});if(t.targetLanguages.some(e=>"string"!=typeof e||0===e.trim().length))throw new e.ValidationError("targetLanguages contains invalid language code",{code:e.ERROR_CODES.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"targetLanguages",message:"contains invalid language code",rule:"language_code"}]}});const a=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(t,r,a)=>{const i=await oe(()=>t.post(`${ae(r)}/users/${r.userId}/translate`,{text:a.text,to:[...a.targetLanguages]},{operation:"translateMessage"})),s=ue(i,"translateMessage"),o=se(s[0])?s[0]:null;if(!o)throw e.createRestBusinessError({apiName:"translateMessage",message:"translateMessage response data is invalid",mapped:!1});const n=Array.isArray(o.translations)?o.translations:[],d=se(o.detectedLanguage)?o.detectedLanguage:void 0;return{detectedLanguage:d&&"string"==typeof d.language?{language:d.language,score:"number"==typeof d.score?d.score:Number(d.score??0)}:void 0,translations:n.map(e=>se(e)&&"string"==typeof e.text&&"string"==typeof e.to?{text:e.text,to:e.to}:null).filter(e=>null!==e)}})(this.getRestClient(a),a,{text:r,targetLanguages:t.targetLanguages}))}async voiceMessageToText(e,t){we(e,t);const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>Me(this.getRestClient(r),r,e,t))}async voiceFileToText(t,r){Ae(t,r);const i=this.getRestContextOrThrow(),s=this.getClientOrThrow().getUploadAdapter();if(!s)throw new e.SDKError("Upload capability is missing for current platform",e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING);return this.executeRestOperation(()=>(async(t,r,i,s)=>{const o=Ae(i,s),n=e.normalizeUploadSource({file:o,fallbackName:Re(o)?"voice.amr":void 0,fallbackMimeType:"audio/amr"});try{const a=await t.upload({url:`${r.restBaseUrl}${fe(r)}/speech/recognitions`,headers:{Authorization:`Bearer ${r.token}`,Accept:"application/json",[e.REQUEST_ID_HEADER]:e.createTraceId()},source:n.source,fields:{username:r.userId,...s?.format?{format:s.format}:{},...void 0!==s?.sampleRate?{sampleRate:String(s.sampleRate)}:{},...void 0!==s?.bitsPerSample?{bitsPerSample:String(s.bitsPerSample)}:{},...void 0!==s?.channels?{channels:String(s.channels)}:{}}});let i=a.body;try{i=JSON.parse(a.body)}catch{i=a.body}if(a.status<200||a.status>=300)throw new e.SDKError("Voice-to-text failed",e.ERROR_CODES.VOICE_TO_TEXT_FAILED,{details:{httpStatus:a.status,rawResponse:i}});return{text:Te(i,"voiceFileToText")}}catch(d){if(d instanceof e.SDKError)throw Se(d);throw Se(a.mapUploadAdapterError(d))}})(s,i,t,r))}validateConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType&&"chatRoom"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType")}validateUnreadConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType must be singleChat or groupChat","conversationType")}validateSendMessageReadReceiptsParams(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType");if(e.messageIds.length>50)throw this.buildValidationError("messageIds cannot contain more than 50 items","messageIds");return this.validateMessageIdList(e.messageIds,"messageIds")}validateMessageIdList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError(`${t} cannot be empty`,t);return e.map((e,r)=>{if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t}.${r} is invalid`,`${t}.${r}`);return e.trim()})}resolveDownloadCombineMessageParams(t){if("message"in t){if("combine"!==t.message.type)throw new e.ValidationError("message must be a combine message",{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT});const r=t.message.body;return{url:r.url??"",secret:r.secret,timeoutMs:t.timeoutMs,maxItems:t.maxItems}}return{url:t.url,secret:t.secret,timeoutMs:t.timeoutMs,maxItems:t.maxItems}}validateReactionParams(e){this.requireNonEmptyString(e.messageId,"messageId"),this.requireNonEmptyString(e.reaction,"reaction")}buildActionError(t,r){return t===e.ERROR_CODES.AUTH_NOT_LOGIN||t===e.ERROR_CODES.AUTH_UNAUTHORIZED?new e.AuthenticationError(r??"authentication failed",{code:t}):t===e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR||t===e.ERROR_CODES.CONNECTION_TIMEOUT?new e.ConnectionError(r??"connection unavailable",{code:t}):107===t||110===t||205===t||500===t||t===e.ERROR_CODES.VALIDATION_REQUIRED||t===e.ERROR_CODES.VALIDATION_INVALID_FORMAT?new e.ValidationError(r??"invalid parameter",{code:t}):t===e.ERROR_CODES.MESSAGE_RECALL_TIME_LIMIT?new e.SDKError(r??"message recall time limit reached",t):t===e.ERROR_CODES.MESSAGE_EDIT_FAILED?new e.SDKError(r??"message update failed",t):t===e.ERROR_CODES.OPERATION_UNSUPPORTED?new e.ValidationError(r??"operation unsupported",{code:t}):new e.SDKError(r??"message action failed",t)}requireNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} is required`,t)}buildValidationError(t,r){return new e.ValidationError(t,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:r,message:t,rule:"required"}]}})}getEventContextOrThrow(){if(!this.eventContext)throw new e.ValidationError("ChatManager is not bound to event context",{code:e.ERROR_CODES.VALIDATION_REQUIRED});return this.eventContext}getClientOrThrow(){if(!this.client)throw new e.ValidationError("ChatManager is not bound to client",{code:e.ERROR_CODES.VALIDATION_REQUIRED});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:xe,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}requireConnectedClient(){const t=this.getClientOrThrow();if(t.getConnectionState()!==o.CONNECTED)throw new e.ConnectionError("client is not connected",{code:e.ERROR_CODES.CONNECTION_WEBSOCKET_ERROR});return t}getCurrentUserIdOrThrow(){const t=this.getClientOrThrow().getCurrentUserId();if(!t)throw new e.AuthenticationError("user is not logged in",{code:e.ERROR_CODES.AUTH_NOT_LOGIN});return t}buildMessageSenderOrThrow(){const e=this.getClientOrThrow(),t=this.getCurrentUserIdOrThrow(),r=e.getCacheManager()?.getUserInfoSummaries([t],!1)[0];return{userId:t,nickname:r?.nickname,avatarUrl:r?.avatarUrl}}async hydrateGroupMessageReadUsers(e,t){const r=this.getClientOrThrow();if(!r.isUserInfoSyncEnabled()||0===t.users.length)return t;const i=r.getCacheManager(),s=await a.resolveGroupUserInfoMap({groupId:e,users:t.users.map(e=>e.user),includeNameCard:!0,cacheManager:i,fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoReadCapability(r);return t?await t.getUserInfoByUserId({userIds:e}):[]},hydrateGroupNamecards:async(e,t)=>{const a=this.getGroupNamecardHydrationCapability(r);a&&await a.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))}});return this.dispatchFetchedUserInfoUpdates(r,s.fetchedUserInfos),{...t,users:t.users.map(e=>{const t=s.usersById.get(e.userId)??e.user;return{...e,user:t}})}}getUserInfoReadCapability(e){const t=e.getManagerByCapability("userInfo:read");return t&&"function"==typeof t.getUserInfoByUserId?t:null}getGroupNamecardHydrationCapability(e){const t=e.getManagerByCapability("group:namecard");return t&&"function"==typeof t.hydrateMessageProfileGroupNamecards?t:null}dispatchFetchedUserInfoUpdates(e,t){if(0===t.length)return;const r=e.getCurrentUserId(),a=t.find(e=>e.userId===r),i=t.filter(e=>e.userId!==r);a&&e.dispatchOwnInfoUpdated(a),e.dispatchUserInfoUpdated(i),t.length>0&&e.refreshConversationDisplayFromUserInfos(t.map(e=>({userId:e.userId})),"profile")}async executeRestOperation(e){try{return await e()}catch(t){throw this.mapRestError(t)}}mapRestError(t){return t instanceof e.ValidationError||t instanceof e.AuthenticationError||t instanceof e.ConnectionError||t instanceof e.NetworkError?t:t instanceof e.RestTransportError?new e.NetworkError(t.message,{code:t.code,details:t.details}):t instanceof e.RestBusinessError||t instanceof e.SDKError?t:new e.SDKError(String(t),e.ERROR_CODES.UNKNOWN)}};ze.key="chatManager";let $e=ze;exports.ChatManager=$e,exports.ConnectionEventName={CONNECTING:"onConnecting",CONNECTED:"onConnected",DISCONNECTED:"onDisconnected",RECONNECT_FAILED:"onReconnectFailed",TOKEN_WILL_EXPIRE:"onTokenWillExpire",TOKEN_EXPIRED:"onTokenExpired",OFFLINE_MESSAGE_SYNC_START:"onOfflineMessageSyncStart",OFFLINE_MESSAGE_SYNC_FINISH:"onOfflineMessageSyncFinish"},exports.ConnectionEventReason={LOGIN:"login",RECONNECT:"reconnect",ONLINE:"online",OFFLINE_RECOVER:"offline-recover",HEARTBEAT_FAILED:"heartbeat-failed",SEND_TIMEOUT:"send-timeout",CLOSE:"close",ERROR:"error",TIMEOUT:"timeout",LIMIT:"limit",OFFLINE:"offline",TOKEN_EXPIRED:"token-expired"},exports.ConnectionStatus=o,exports.InternalEventName={SEND_TIMEOUT:"onSendTimeout",GROUP_NOTIFY:"onGroupNotify",CHATROOM_NOTIFY:"onChatRoomNotify",CHAT_THREAD_NOTIFY:"onChatThreadNotify",USER_INFO_NOTIFY:"onUserInfoNotify",MESSAGE_SENT:"__internal:onMessageSent"},exports.MAX_COMBINE_MESSAGE_COUNT=300,exports.Validator=E,exports.attachmentFileStore=d,exports.calculateCombineLevel=v,exports.copyCombineCompatibleTextSidecar=(e,t)=>{const r=n.get(e);r&&n.set(t,r)},exports.createLocalFileUrl=l,exports.ensureCombineItemLimit=h,exports.ensureCombineLevel=I,exports.generateMsgLocalId=c,exports.getCombineCompatibleTextSidecar=e=>n.get(e),exports.validateCombineMessageList=y;
@@ -0,0 +1,2 @@
1
+ import{g as e,V as t,E as r,p as a,d as s,c as i,R as n,a as o,n as d,b as l,e as c,S as g,A as u,U as m,l as p,C as h,f as y,N as v,h as I,m as f,i as b}from"./common-BW2KLpvb.js";import{i as T,s as _}from"./cache-utils-B99glc0H.js";import{h as C,t as E}from"./session-list-query-DtoToipt.js";import{m as L,r as w}from"./group-user-info-resolver-Diqjmjyj.js";import{ZodError as O,z as R}from"zod";import{c as N}from"./query-params-Bu3Xq4b6.js";const M={DISCONNECTED:"disconnected",CONNECTING:"connecting",CONNECTED:"connected",RECONNECTING:"reconnecting",RECONNECT_FAILED:"reconnectFailed"},A={CONNECTING:"onConnecting",CONNECTED:"onConnected",DISCONNECTED:"onDisconnected",RECONNECT_FAILED:"onReconnectFailed",TOKEN_WILL_EXPIRE:"onTokenWillExpire",TOKEN_EXPIRED:"onTokenExpired",OFFLINE_MESSAGE_SYNC_START:"onOfflineMessageSyncStart",OFFLINE_MESSAGE_SYNC_FINISH:"onOfflineMessageSyncFinish"},U={SEND_TIMEOUT:"onSendTimeout",GROUP_NOTIFY:"onGroupNotify",CHATROOM_NOTIFY:"onChatRoomNotify",CHAT_THREAD_NOTIFY:"onChatThreadNotify",USER_INFO_NOTIFY:"onUserInfoNotify",MESSAGE_SENT:"__internal:onMessageSent"},S={LOGIN:"login",RECONNECT:"reconnect",ONLINE:"online",OFFLINE_RECOVER:"offline-recover",HEARTBEAT_FAILED:"heartbeat-failed",SEND_TIMEOUT:"send-timeout",CLOSE:"close",ERROR:"error",TIMEOUT:"timeout",LIMIT:"limit",OFFLINE:"offline",TOKEN_EXPIRED:"token-expired"},x=/* @__PURE__ */new WeakMap,D=e=>x.get(e),$=(e,t)=>{const r=x.get(e);r&&x.set(t,r)};const k=new class{constructor(){this.store=/* @__PURE__ */new Map}set(e,t){e&&this.store.set(e,t)}get(e){if(e)return this.store.get(e)}consume(e){const t=this.get(e);return t&&this.store.delete(e),t}delete(e){e&&this.store.delete(e)}clear(){this.store.clear()}},V=e=>{if((e=>"undefined"!=typeof File&&e instanceof File)(e)){if("undefined"==typeof URL||"function"!=typeof URL.createObjectURL)return;return URL.createObjectURL(e)}return(e=>"object"==typeof e&&null!==e&&"path"in e&&"string"==typeof e.path)(e)?e.path:(e=>"object"==typeof e&&null!==e&&"uri"in e&&"string"==typeof e.uri)(e)?e.uri:void 0},P=()=>{const t=e().crypto;return t&&"function"==typeof t.randomUUID?t.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},q=300,F=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),B=(e,r,a)=>{throw new t(e,{code:a,details:{fields:[{path:r,message:e,rule:"invalid_format"}]}})},G=e=>{if("combine"!==e.type)return 0;const t=e.combineLevel;return"number"==typeof t?t:F(e.body)&&"number"==typeof e.body.combineLevel?e.body.combineLevel:0},z=(e,t)=>{if(e.sender.userId||B(`messageList[${t}] sender.userId is required`,`messageList[${t}].sender.userId`,r.COMBINE_INVALID_INPUT),e.conversationId&&["singleChat","groupChat","chatRoom"].includes(e.conversationType)||B(`messageList[${t}] conversation is invalid`,`messageList[${t}].conversationId`,r.COMBINE_INVALID_INPUT),(!Number.isInteger(e.timestamp)||e.timestamp<=0)&&B(`messageList[${t}] timestamp must be positive integer`,`messageList[${t}].timestamp`,r.COMBINE_INVALID_INPUT),F(e.body)||B(`messageList[${t}] body must be object`,`messageList[${t}].body`,r.COMBINE_INVALID_INPUT),"combine"===e.type){const a=G(e);(!Number.isInteger(a)||a<0)&&B(`messageList[${t}] combineLevel is invalid`,`messageList[${t}].combineLevel`,r.COMBINE_INVALID_INPUT),a>10&&B(`messageList[${t}] combineLevel exceeds limit`,`messageList[${t}].combineLevel`,r.COMBINE_LEVEL_EXCEEDED)}},j=(e,t=300)=>{(!Number.isInteger(e)||e<=0)&&B("messageList must not be empty","messageList",r.COMBINE_INVALID_INPUT),(!Number.isInteger(t)||t<=0||t>300)&&B("max items is invalid","maxItems",r.COMBINE_INVALID_INPUT),e>t&&B(`messageList max length is ${t}`,"messageList",r.COMBINE_ITEM_LIMIT_EXCEEDED)},H=e=>{j(e.length);for(let t=0;t<e.length;t+=1){const a=e[t];void 0!==a?z(a,t):B(`messageList[${t}] is required`,`messageList[${t}]`,r.COMBINE_INVALID_INPUT)}},X=e=>{let t=0;for(const r of e){if("combine"!==r.type)continue;const e=G(r);e>t&&(t=e)}return t+1},K=e=>{(!Number.isInteger(e)||e<=0)&&B("combineLevel must be positive integer","combineLevel",r.COMBINE_INVALID_INPUT),e>10&&B("combineLevel must be <= 10","combineLevel",r.COMBINE_LEVEL_EXCEEDED)};class Q{static validate(e,a){try{return{success:!0,data:e.parse(a)}}catch(s){if(s instanceof O){const e=s.errors.map(e=>({path:e.path.length>0?e.path.join("."):"root",message:e.message,rule:e.code})),a=`Validation failed: ${e.map(e=>`${e.path}: ${e.message}`).join("; ")}`,i=s.errors.some(e=>"invalid_type"===e.code&&"undefined"===e.received)?r.VALIDATION_REQUIRED:r.VALIDATION_INVALID_FORMAT;return{success:!1,error:new t(a,{code:i,details:{fields:e}})}}return{success:!1,error:new t("Unknown validation error",{code:r.VALIDATION_UNKNOWN,details:{fields:[]}})}}}static validateOrThrow(e,a){const s=this.validate(e,a);if(s.success&&void 0!==s.data)return s.data;if(s.error)throw s.error;throw new t("Unknown validation error",{code:r.VALIDATION_UNKNOWN,details:{fields:[]}})}static safeParse(e,t){return this.validate(e,t)}}const W=(e,a)=>new t(a,{code:r.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:a,rule:"invalid_format"}]}}),Y=(e,a)=>{if("string"!=typeof e||0===e.trim().length)throw(e=>new t(`${e} is required`,{code:r.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}))(a);return e.trim()},Z=e=>`mark_${String(e)}`,J=(e,t)=>{if("singleChat"===e||"groupChat"===e||"chatRoom"===e)return e;throw W(t,`${t} must be one of singleChat, groupChat, chatRoom`)},ee=e=>"singleChat"===e?"chat":"groupChat"===e?"groupchat":"chatroom",te=e=>"string"==typeof e&&e.length>0?e:void 0,re=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}},ae=e=>T(e)?e:void 0,se=(e,t)=>{const r=ae(e);if(!r)return;const a=(e=>"string"==typeof e?_(e,{}):ae(e)??{})(r.payload),s=Array.isArray(a.bodies)?a.bodies:[],i=ae(s[0])??ae(a.body),n=(e=>"txt"===e||"text"===e?"text":"custom"===e?"custom":"cmd"===e?"cmd":"image"===e||"file"===e||"voice"===e||"video"===e||"location"===e||"combine"===e?e:null)(i?.type??a.type);if(!i||!n)return;const o=((e,t)=>{if("text"===e)return{content:te(t.msg)??te(t.content)??""};if("custom"===e){const e=ae(t.customExts)??ae(t.params)??{},r={};for(const[t,a]of Object.entries(e))"string"==typeof a&&(r[t]=a);return{event:te(t.customEvent)??te(t.event)??"",params:r}}if("cmd"===e)return{action:te(t.action)??""};if("image"===e){const e=te(t.url)??te(t.remotePath)??"";return{localUrl:"",filename:te(t.filename)??te(t.displayName),filetype:te(t.filetype)??"application/octet-stream",width:re(t.width),height:re(t.height),isGif:!0===t.isGif||1===t.subType,isOriginalImage:!0===t.isOriginalImage,originalImageUrl:e,bigImageUrl:te(t.bigImageUrl),thumbnailUrl:te(t.thumbnailUrl)??te(t.thumbnailRemotePath),secret:te(t.secret)??te(t.secretKey),fileLength:re(t.fileLength)}}return"file"===e?{url:te(t.url)??te(t.remotePath),filename:te(t.filename)??te(t.displayName),filetype:te(t.filetype)??"application/octet-stream",fileSize:re(t.fileSize),fileLength:re(t.fileLength),secret:te(t.secret)??te(t.secretKey)}:"voice"===e?{url:te(t.url)??te(t.remotePath),filename:te(t.filename)??te(t.displayName),filetype:te(t.filetype)??"application/octet-stream",duration:re(t.duration)??0,fileLength:re(t.fileLength),secret:te(t.secret)??te(t.secretKey)}:"video"===e?{url:te(t.url)??te(t.remotePath),filename:te(t.filename)??te(t.displayName),filetype:te(t.filetype)??"application/octet-stream",duration:re(t.duration)??0,width:re(t.width),height:re(t.height),fileLength:re(t.fileLength),secret:te(t.secret)??te(t.secretKey),thumbnailUrl:te(t.thumbnailUrl)??te(t.thumbnailRemotePath)}:"location"===e?{latitude:re(t.latitude)??0,longitude:re(t.longitude)??0,address:te(t.address),buildingName:te(t.buildingName)}:null})(n,i);if(!o)return;const d=te(a.from)??te(r.from)??"",l=te(a.to)??t.conversationId,c=ae(a.sender),g={userId:te(c?.userId)??d,nickname:te(c?.nickname),avatarUrl:te(c?.avatarUrl)},u=ae(a.ext)??{},m=(e=>{const t=ae(e);if(!t)return;const r=te(t.operatorId)??te(t.operator),a=re(t.operationCount)??re(t.count),s=re(t.operationTime)??re(t.edit_time);return r&&void 0!==a&&void 0!==s?{operatorId:r,operationCount:a,operationTime:s}:void 0})(a.modifiedInfo??ae(a.meta)?.edit_msg);return{msgServerId:te(r.id)??t.messageId,msgLocalId:te(r.msgLocalId)??"",from:d,to:l,sender:g,conversationId:t.conversationId,conversationType:t.conversationType,type:n,sendStatus:"sent",ext:u,timestamp:re(r.timestamp)??t.timestamp,body:o,direct:d===t.currentUserId?"SEND":"RECEIVE",...m?{modifiedInfo:m}:{}}},ie=e=>`${e.conversationType}:${e.conversationId}`,ne=e=>{const{orgName:t,appName:r}=a(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},oe=async(e,t,r,a)=>{const s=ne(t),i=(e=>{const t=e,r=t.conversations;if(void 0!==r){if(!Array.isArray(r)||0===r.length)throw W("params.conversations","params.conversations must be a non-empty array");return r.map((e,t)=>{if(!T(e))throw W(`params.conversations.${String(t)}`,`params.conversations.${String(t)} must be an object`);return{conversationId:Y(e.conversationId,`params.conversations.${String(t)}.conversationId`),conversationType:J(e.conversationType,`params.conversations.${String(t)}.conversationType`)}})}return[{conversationId:Y(t.conversationId,"params.conversationId"),conversationType:J(t.conversationType,"params.conversationType")}]})(r),n=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0||e>19)throw W(t,`${t} must be an integer between 0 and 19`);return e})(r.mark,"params.mark"),o=await e.request(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channels/mark?resource=${s.encodedResource}`,{method:a?"POST":"DELETE",body:{mark:Z(n),targets:i.map(e=>({to:e.conversationId,type:ee(e.conversationType)}))},operation:a?"addConversationMark":"removeConversationMark"}),d=(e=>{if(!Array.isArray(e))/* @__PURE__ */
2
+ return new Set;const t=/* @__PURE__ */new Set;return e.forEach(e=>{if(!T(e))return;const r="string"==typeof e.to?e.to.trim():"",a=(e=>"chat"===e||"singleChat"===e?"singleChat":"groupchat"===e||"groupChat"===e?"groupChat":"chatroom"===e||"chatRoom"===e?"chatRoom":null)(e.type);r&&a&&t.add(ie({conversationId:r,conversationType:a}))}),t})((T(o)&&T(o.data)?o.data:{}).ignore),l=[],c=[];for(const g of i){const e={conversationId:g.conversationId,conversationType:g.conversationType};d.has(ie(g))?c.push({...e,reason:"ignored_by_server"}):l.push(e)}return{succeeded:l,failed:c,mark:n,operation:a?"addMark":"removeMark"}},de=async(e,t,r,a)=>{const s=ne(t),i=Y(r.conversationId,"params.conversationId"),n=J(r.conversationType,"params.conversationType"),o=Y(r.messageId,"params.messageId");return await e.request(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/pin?resource=${s.encodedResource}`,{method:a?"POST":"DELETE",body:{to:i,type:ee(n),pin_msg_id:o},operation:a?"pinMessage":"unpinMessage"}),{conversationId:i,conversationType:n,messageId:o,operation:a?"pin":"unpin"}},le=R.enum(["singleChat","groupChat","chatRoom"]),ce=R.record(R.unknown()).refine(e=>(e=>"object"==typeof e&&null!==e&&!Array.isArray(e))(e),"ext must be an object").refine(e=>(e=>{try{return JSON.stringify(e),!0}catch{return!1}})(e),"ext must be JSON serializable"),ge=R.object({path:R.string().min(1,"data.path is required"),size:R.number().optional(),name:R.string().optional(),type:R.string().optional()}),ue=R.object({uri:R.string().min(1,"data.uri is required"),size:R.number().optional(),name:R.string().optional(),type:R.string().optional()}),me="undefined"!=typeof File?R.instanceof(File):R.never(),pe=R.union([me,ge,ue]),he=R.object({conversationId:R.string().min(1,"conversationId is required"),conversationType:le,ext:ce.optional(),timestamp:R.number().int().positive("timestamp must be a positive integer").optional(),receiverList:R.array(R.string().min(1,"receiverList item is required")).nonempty("receiverList must not be empty").optional(),deliverOnlineOnly:R.boolean().optional(),webhookEnv:R.string().optional(),priority:R.enum(["high","normal","low"]).optional(),needReadReceipt:R.boolean().optional(),isChatThread:R.boolean().optional()}),ye=R.object({type:R.string().min(1,"messageList.type is required"),sender:R.object({userId:R.string().min(1,"messageList.sender.userId is required"),nickname:R.string().optional(),avatarUrl:R.string().optional()}),conversationId:R.string().min(1,"messageList.conversationId is required"),conversationType:le,timestamp:R.number().int().positive("messageList.timestamp must be positive"),body:R.record(R.unknown()),combineLevel:R.number().int().min(0).max(10).optional()}).passthrough(),ve=e=>e.superRefine((e,t)=>{e.receiverList&&"singleChat"===e.conversationType&&t.addIssue({code:R.ZodIssueCode.custom,message:"receiverList is only allowed for group or chat room conversation",path:["receiverList"]}),e.isChatThread&&"groupChat"!==e.conversationType&&t.addIssue({code:R.ZodIssueCode.custom,message:"isChatThread is only allowed for group conversation",path:["isChatThread"]}),e.needReadReceipt&&"chatRoom"===e.conversationType&&t.addIssue({code:R.ZodIssueCode.custom,message:"needReadReceipt is not allowed for chatRoom conversation",path:["needReadReceipt"]})}),Ie=ve(he.extend({content:R.string().min(1,"content is required"),targetLanguages:R.array(R.string().min(1)).optional()})),fe=ve(he.extend({originalUrl:R.string().min(1,"originalUrl is required").optional(),filename:R.string().min(1,"filename is required").optional(),filetype:R.string().min(1,"filetype is required").optional(),width:R.number().positive("width must be positive").optional(),height:R.number().positive("height must be positive").optional(),isGif:R.boolean().optional(),isOriginalImage:R.boolean().optional(),fileLength:R.number().positive("fileLength must be positive").optional(),data:pe.optional(),thumbnailUrl:R.string().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),be=ve(he.extend({originalUrl:R.string().min(1,"originalUrl is required").optional(),filename:R.string().min(1,"filename is required").optional(),filetype:R.string().min(1,"filetype is required").optional(),fileSize:R.number().positive("fileSize must be positive").optional(),fileLength:R.number().positive("fileLength must be positive").optional(),data:pe.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),Te=ve(he.extend({originalUrl:R.string().min(1,"originalUrl is required").optional(),filename:R.string().min(1,"filename is required").optional(),filetype:R.string().min(1,"filetype is required").optional(),duration:R.number().positive("duration must be positive"),fileLength:R.number().positive("fileLength must be positive").optional(),data:pe.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),_e=ve(he.extend({originalUrl:R.string().min(1,"originalUrl is required").optional(),filename:R.string().min(1,"filename is required").optional(),filetype:R.string().min(1,"filetype is required").optional(),duration:R.number().positive("duration must be positive"),width:R.number().positive("width must be positive").optional(),height:R.number().positive("height must be positive").optional(),fileLength:R.number().positive("fileLength must be positive").optional(),thumbnailUrl:R.string().min(1).optional(),data:pe.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),Ce=ve(he.extend({latitude:R.number(),longitude:R.number(),address:R.string().min(1).optional(),buildingName:R.string().min(1).optional()})),Ee=ve(he.extend({action:R.string().min(1,"action is required")})),Le=ve(he.extend({event:R.string().min(1,"event is required"),params:R.record(R.string()).optional()})),we=ve(he.extend({title:R.string().min(1,"title is required"),summary:R.string().min(1,"summary is required"),compatibleText:R.string().min(1).optional(),messageList:R.array(ye).min(1,"messageList must not be empty").max(300,"messageList max length is 300")})),Oe=e=>{const a=e?.userId?.trim();if(!a)throw new t("sender.userId is required",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});return{userId:a,nickname:e?.nickname,avatarUrl:e?.avatarUrl}},Re=()=>P(),Ne=(e,a)=>{if(e)return e;if(!a)throw new t("url or data is required",{code:r.VALIDATION_REQUIRED,details:{fields:[{path:"url",message:"url or data is required",rule:"required"}]}});const s=V(a);if(!s)throw new t("Failed to resolve local url",{code:r.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"url",message:"Failed to resolve local url",rule:"invalid_format"}]}});return s},Me=e=>!!e.isGif||(e.isOriginalImage??!1),Ae=(e,t,r,a,s)=>({msgServerId:"",msgLocalId:s??P(),from:t.userId,to:e.conversationId,sender:t,conversationId:e.conversationId,conversationType:e.conversationType,type:r,sendStatus:"sending",ext:e.ext??{},timestamp:e.timestamp??Date.now(),body:a,direct:"SEND",isOnline:!0,receiverList:e.receiverList,deliverOnlineOnly:e.deliverOnlineOnly,webhookEnv:e.webhookEnv,priority:e.priority,needReadReceipt:e.needReadReceipt,isPeerRead:"singleChat"!==e.conversationType&&void 0,isChatThread:e.isChatThread}),Ue=(e,t)=>{const r=Q.validateOrThrow(we,e),a=r.messageList,s=Oe(t);H(a);const i=X(a);K(i);const n={title:r.title,summary:r.summary,messageList:a,filename:"combine",filetype:"application/octet-stream",combineLevel:i},o=Ae(r,s,"combine",n);return((e,t)=>{t&&x.set(e,t)})(o,r.compatibleText),o},Se=e=>{const{orgName:t,appName:r}=a(e.appKey);return`/${t}/${r}`},xe=e=>{if("undefined"!=typeof Buffer)return new Uint8Array(Buffer.from(e,"base64"));const t=atob(e),r=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)r[a]=t.charCodeAt(a);return r},De=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),$e=async e=>{try{return await e()}catch(t){if(!(t instanceof n))throw t;const e=(e=>{const t="string"==typeof e.details?.serverMessage?e.details.serverMessage:void 0;switch(e.code){case r.SERVICE_NOT_ENABLED:case r.TRANSLATE_SERVICE_NOT_ENABLED:return"Translation service is not enabled";case r.TRANSLATE_PARAM_INVALID:return t?.includes("too long")?"Translation text is too long":t?.includes("target language")?"Invalid target language":"Invalid translation request";case r.TRANSLATE_USAGE_LIMIT:return"Translation quota has been reached";case r.TRANSLATE_FAILED:return"Translation service error";default:return}})(t);if(!e)throw t;throw new n(`REST business error: ${e}`,{code:t.code,details:t.details})}},ke=e=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):"",Ve=e=>{if("string"!=typeof e)return"";const t=e.trim();return t&&"undefined"!==t&&"null"!==t?t:""},Pe=e=>({userId:e}),qe=(e,t)=>{if(!De(e)||!De(e.data))throw i({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},Fe=(e,t)=>{if(!De(e)||!Array.isArray(e.data))throw i({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},Be=(e,t)=>Array.isArray(e)?e:Fe(e,t),Ge={txt:"text",img:"image",video:"video",file:"file",loc:"location",custom:"custom",combine:"combine"},ze={text:"txt",image:"img",video:"video",file:"file",location:"loc",custom:"custom",combine:"combine"},je={chat:"singleChat",chatroom:"chatRoom",groupchat:"groupChat",singleChat:"singleChat",chatRoom:"chatRoom",groupChat:"groupChat"},He=(e,t,r)=>{if(!t)return"";if(t.includes("em-redirect"))return t;const{orgName:s,appName:i}=a(e.appKey),n=t.indexOf("/chatfiles/"),d=n>=0?t.slice(n):t,l=`${e.restBaseUrl}/${s}/${i}${d}`;return o(l,r)},Xe=e=>{if(!e||"object"!=typeof e)return;if(Array.isArray(e))return e;const t=Object.values(e),r=[];for(const a of t)Array.isArray(a)&&r.push(...a);return r.length>0?r:void 0},Ke=(e,t,r)=>{const a=ke(r.contentType??r.type),s=ze[a];if(!s)return null;const i=De(r.content)?r.content:{},n=((e,t)=>{const r=ke(t.conversationType);if("groupchat"===r||"chatroom"===r)return ke(t.receiverId);const a=ke(t.senderId);return a===e?ke(t.receiverId):a})(t,r),o=je[ke(r.conversationType)]??"singleChat",d={msgServerId:ke(r.messageId),msgLocalId:ke(r.messageId),from:ke(r.senderId),to:ke(r.receiverId),conversationId:n,conversationType:o,type:s,ext:De(r.ext)?r.ext:{},timestamp:"number"==typeof r.sentTime?r.sentTime:new Date(ke(r.sentTime)).getTime(),sender:{userId:ke(r.senderId)},highlight:Xe(r.highlight),text:"string"==typeof r.text?r.text:void 0};let l;const c=ke(i.remotePath??i.url),g=ke(i.secret??i.secretKey);switch(s){case"txt":l={type:"txt",content:ke(i.message??r.text)};break;case"img":{const t=He(e,c,g);l={type:"img",url:t,thumb:i.thumb?He(e,ke(i.thumb),ke(i.thumb_secret??i.thumbnailSecretKey)):`${t}&thumbnail=true`,secret:g,width:Number(i.width??(De(i.size)?i.size.width:0))||0,height:Number(i.height??(De(i.size)?i.size.height:0))||0,fileLength:Number(i.file_length??i.fileLength??0)};break}case"video":l={type:"video",url:He(e,c,g),thumb:i.thumb||i.thumbnailRemotePath?He(e,ke(i.thumb??i.thumbnailRemotePath),ke(i.thumb_secret??i.thumbnailSecretKey)):"",secret:g,filename:ke(i.filename??i.displayName),duration:Number(i.length??i.duration??0),fileLength:Number(i.file_length??i.fileLength??0)};break;case"file":l={type:"file",url:He(e,c,g),secret:g,filename:ke(i.filename??i.displayName),fileLength:Number(i.file_length??i.fileLength??0)};break;case"loc":l={type:"loc",latitude:Number(i.lat??i.latitude??0),longitude:Number(i.lng??i.longitude??0),address:ke(i.addr??i.address),buildingName:ke(i.buildingName)};break;case"custom":l={type:"custom",customEvent:ke(i.customEvent),customExts:De(i.customExts)?i.customExts:{}};break;default:return null}return{...d,body:l}},Qe=async(e,t,r)=>{const a=`${Se(t)}/users/${t.userId}/messages/search/get`,s=((e,t)=>{const{option:r,pageNum:a=1,pageSize:s=20}=e,i=r.keywordList.map(e=>e.trim()).filter(e=>e.length>0),n={searchMode:"default",highlightEnable:!0,page:a,size:s};return 1===i.length?n.keyword=i[0]:(n.keywords=i,n.keywordMatch="and"===r.keywordListMatchType?"all":"any"),r.conversationId&&("singleChat"===r.conversationType?n.participantPairs=[{userId1:t,userId2:r.conversationId}]:"groupChat"===r.conversationType?n.groupIds=[r.conversationId]:"chatRoom"===r.conversationType&&(n.chatroomIds=[r.conversationId])),r.msgTypes&&r.msgTypes.length>0&&(n.contentType=r.msgTypes.map(e=>Ge[e]??e).join(",")),void 0!==r.startTime&&(n.startTime=r.startTime),void 0!==r.endTime&&(n.endTime=r.endTime),r.searchScope&&(n.searchExt=r.searchScope),r.direction&&(n.sort="up"===r.direction?"sentTime:asc":"sentTime:desc"),{data:n}})(r,t.userId),i=await e.post(a,s,{operation:"searchMessages"}),n=De(i)?i:{},o=De(n.data)?n.data:n,d=De(o.data)?o.data:o,l=Array.isArray(d.items)?d.items:Array.isArray(d.list)?d.list:[],c=De(d.pagination)?d.pagination:d,g=Number(c.pageNum??c.page??r.pageNum??1),u=Number(c.pageSize??c.size??r.pageSize??20),m=Number(c.totalPages??0),p=1===c.isFinished||g>=m,h=[];for(const y of l){if(!De(y))continue;const e=Ke(t,t.userId,y);e&&h.push(e)}return{messages:h,pageNum:g,pageSize:u,totalPages:m,isLast:p}},We=e=>{const{orgName:t,appName:r}=a(e.appKey);return`/api/sdk/v1/${t}/${r}`},Ye=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ze=e=>Ye(e)&&"string"==typeof e.path&&e.path.trim().length>0,Je=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||Ze(e),et=e=>{if(!Ye(e))return;return{data:Ye(e.data)?e.data:void 0,error:Ye(e.error)?e.error:void 0}},tt=(e,t)=>{const a=et(e),s=a?.data?.text;if("string"!=typeof s)throw new g(`${t} response data is invalid`,r.REST_BUSINESS_UNKNOWN,{details:{api:t,response:e}});return s},rt=(e,r,a,s="sdk")=>"auth"===s?new u(e,{code:r,details:a}):"validation"===s?new t(e,{code:r,details:a}):new g(e,r,{details:a}),at=e=>!(void 0===e||Ye(e)&&!Array.isArray(e))||(void 0!==e?.format&&"string"!=typeof e.format||(void 0!==e?.sampleRate&&"number"!=typeof e.sampleRate||(void 0!==e?.bitsPerSample&&"number"!=typeof e.bitsPerSample||void 0!==e?.channels&&"number"!=typeof e.channels))),st=e=>{if(!e)return;const t=(e.split("#")[0]?.split("?")[0]??"").split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0},it=e=>{const{serviceCode:t,serviceMessage:a}=(e=>{const t=e instanceof g&&Ye(e.details)?e.details:void 0,r=et(t?.rawResponse??t?.response??e),a=t?.serverCode??r?.error?.code,s=t?.serverMessage??r?.error?.message;return{serviceCode:"string"==typeof a||"number"==typeof a?String(a):void 0,serviceMessage:"string"==typeof s?s:void 0}})(e);if(e instanceof m)return rt("File upload failed",r.UPLOAD_REQUEST_FAILED,{cause:e.details});if(e instanceof g&&!t)return e;if(t)switch(t){case"4041001":return rt("File not found",r.VOICE_TO_TEXT_FILE_NOT_FOUND,{serviceCode:t,serviceMessage:a});case"4001002":return rt("Invalid file",r.VOICE_TO_TEXT_FILE_INVALID,{serviceCode:t,serviceMessage:a},"validation");case"5021001":return rt("File upload failed",r.UPLOAD_REQUEST_FAILED,{serviceCode:t,serviceMessage:a});case"4001003":return rt("Voice duration exceeds 60 seconds",r.VOICE_TO_TEXT_FILE_DURATION_TOO_LONG,{serviceCode:t,serviceMessage:a},"validation");case"4031001":return rt("Voice-to-text service is not enabled",r.SERVICE_NOT_ENABLED,{serviceCode:t,serviceMessage:a});case"4031002":return rt("Beta service usage limit exceeded",r.SERVICE_LIMIT_EXCEEDED,{serviceCode:t,serviceMessage:a});case"4001001":return"string"==typeof(s=a)&&s.toLowerCase().includes("uploaded file exceeds")?rt("File too large",r.VOICE_TO_TEXT_FILE_TOO_LARGE,{serviceCode:t,serviceMessage:a}):rt(a||"Missing or invalid request parameter",r.VALIDATION_REQUIRED,{serviceCode:t,serviceMessage:a},"validation");case"5021003":case"5001003":return rt("Voice-to-text failed",r.VOICE_TO_TEXT_FAILED,{serviceCode:t,serviceMessage:a});case"4011001":return rt(a||"Unauthorized or invalid token",r.AUTH_UNAUTHORIZED,{serviceCode:t,serviceMessage:a},"auth");default:return rt(a||(e instanceof Error?e.message:"Voice-to-text failed"),r.VOICE_TO_TEXT_FAILED,{serviceCode:t,serviceMessage:a})}var s;return e instanceof g?rt(e.message,e.code,e.details):rt(e instanceof Error?e.message:"Voice-to-text failed",r.VOICE_TO_TEXT_FAILED)},nt=(e,t)=>{if(!Ye(a=e)||"string"!=typeof a.filename||"string"!=typeof a.filetype||"number"!=typeof a.duration||"type"in a&&void 0!==a.type&&"voice"!==a.type)throw rt("Invalid file",r.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody"},"validation");var a;if(at(t))throw rt("Invalid file",r.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!e.url)throw rt("File not found",r.VOICE_TO_TEXT_FILE_NOT_FOUND,{path:"voiceMessageBody.url"});if(!st(e.url))throw rt("Invalid file",r.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody.url"},"validation");return e},ot=(e,t)=>{if(at(t))throw rt("Invalid file",r.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!Je(e))throw rt("Invalid file",r.VOICE_TO_TEXT_FILE_INVALID,{path:"file"},"validation");return e},dt=async(e,a,s,i)=>{const n=nt(s,i),o=st(n.url);if(!o)throw((e,r,a,s="invalid")=>new t(e,{code:r,details:{fields:[{path:a,message:e,rule:s}]}}))("File not found",r.VOICE_TO_TEXT_FILE_NOT_FOUND,"voiceMessageBody.url");try{const t=await e.post(`${We(a)}/speech/transcriptions`,{data:{fileId:o,username:a.userId,...i?{audio:i}:{}}},{operation:"voiceMessageToText"});return{text:tt(t,"voiceMessageToText")}}catch(d){throw it(d)}},lt=R.object({keywordList:R.array(R.string()).min(1,"keywordList must not be empty").max(5,"keywordList must have at most 5 keywords").refine(e=>e.map(e=>e.trim()).filter(e=>e.length>0).length>0,"keywordList must contain at least one non-empty keyword"),keywordListMatchType:R.enum(["or","and"]).optional(),conversationId:R.string().min(1).optional(),conversationType:R.enum(["singleChat","groupChat","chatRoom"]).optional(),msgTypes:R.array(R.enum(["txt","img","video","file","loc","custom","combine"])).optional(),startTime:R.number().optional(),endTime:R.number().optional(),searchScope:R.enum(["none","with","only"]).optional(),direction:R.enum(["up","down"]).optional()}).refine(e=>void 0!==e.conversationId===(void 0!==e.conversationType),{message:"conversationId and conversationType must be provided together"}).refine(e=>void 0!==e.startTime===(void 0!==e.endTime),{message:"startTime and endTime must be provided together"}).refine(e=>void 0===e.startTime||void 0===e.endTime||e.endTime>=e.startTime,{message:"endTime must be >= startTime"}),ct=R.object({option:lt,pageNum:R.number().int().min(1).default(1),pageSize:R.number().int().min(1).max(100).default(20)}),gt=f(b,{common:{},apis:{sendMessage:{range:"1,4,100,108,110,202,210,213-215,219-222,300-301,303,305,402,405-406,500-501,505-510,602-603,606-607,1200,1299",localErrors:{sendMessage:{operation_cancelled:{code:1,retryable:!1},upload_invalid_appkey:{code:100,retryable:!1},validation_invalid:{code:110,retryable:!1},not_connected:{code:300,retryable:!0},request_timeout:{code:301,retryable:!0},send_failed:{code:303,retryable:!1},upload_failed:{code:402,retryable:!0},file_too_large:{code:405,retryable:!1},file_content_improper:{code:406,retryable:!1},encode_failed:{code:500,retryable:!1}}},errors:{SERVICE_LIMIT_EXCEEDED:{code:4,retryable:!1},TOKEN_EXPIRED:{code:108,retryable:!1},AUTH_FAILED:{code:202,retryable:!1},PERMISSION_DENIED:{code:210,retryable:!1},BIND_ANOTHER_DEVICE:{code:213,retryable:!1},TOO_MANY_DEVICES:{code:214,retryable:!1},USER_MUTED:{code:215,retryable:!1},USER_MUTED_BY_ADMIN:{code:219,retryable:!1},USER_DEVICE_CHANGED:{code:220,retryable:!1},USER_NOT_ON_ROSTER:{code:221,retryable:!1},BLOCKED_BY_RECIPIENT:{code:222,retryable:!1,aliases:["blocked"]},SERVER_SERVING_DISABLED:{code:305,retryable:!1},MESSAGE_INCLUDE_ILLEGAL_CONTENT:{code:501,retryable:!1},SERVICE_NOT_ENABLED:{code:505,retryable:!1},MESSAGE_EXPIRED:{code:506,retryable:!1},MESSAGE_ILLEGAL_WHITELIST:{code:507,retryable:!1},MESSAGE_EXTERNAL_LOGIC_BLOCKED:{code:508,retryable:!1},MESSAGE_CURRENT_LIMITING:{code:509,retryable:!0},MESSAGE_SIZE_LIMIT:{code:510,retryable:!1},GROUP_NOT_JOINED:{code:602,retryable:!1},GROUP_PERMISSION_DENIED:{code:603,retryable:!1},GROUP_NOT_EXIST:{code:606,retryable:!1},GROUP_DISABLED:{code:607,retryable:!1},MESSAGE_BLOCKED:{code:1200,retryable:!1},THIRD_DEFAULT_FAILED:{code:1299,retryable:!1}}},getHistoryMessages:{range:"4,110,202,505",localErrors:{getHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},page_size_exceeded:{code:110,aliases:["pull number cannot be greater","limit is to large"],retryable:!1}}},removeHistoryMessages:{range:"110,112,202,505",localErrors:{removeHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},query_param_reaches_limit:{code:112,aliases:["delete msg list limit"],retryable:!1}}},getGroupMessageReadUsers:{range:"4,110,500",localErrors:{getGroupMessageReadUsers:{validation_invalid:{code:110,retryable:!1}}},errors:{message_not_found:{code:500,retryable:!1}}},recallMessage:{range:"110,201,300,504,505",localErrors:{recallMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},recall_time_limit:{code:504,retryable:!1},recall_disabled:{code:505,retryable:!1}}},updateMessage:{range:"110,111,201,210,300,511",localErrors:{modifyMessage:{validation_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1},not_login:{code:201,retryable:!0},permission_denied:{code:210,retryable:!1},not_connected:{code:300,retryable:!0},edit_failed:{code:511,retryable:!0}}},downloadMessageAttachment:{range:"400,401,403,407",localErrors:{downloadAttachment:{validation_invalid:{code:401,retryable:!1}}},errors:{not_found:{code:400,httpStatus:404,retryable:!1},invalid:{code:401,retryable:!1},download_failed:{code:403,retryable:!0},expired:{code:407,httpStatus:404,retryable:!1}}},downloadAndParseCombineMessage:{range:"110,401,403,500",localErrors:{downloadAndParseCombineMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_param:{code:110,retryable:!1},invalid_type:{code:500,retryable:!1},parse_failed:{code:401,retryable:!0},download_failed:{code:403,retryable:!0}}},addReaction:{range:"110,302,505,600,602,1300-1302",localErrors:{addReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{reaction_already_operated:{code:1301,retryable:!1},reaction_reach_limit:{code:1300,retryable:!1},group_not_joined:{code:602,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1},service_not_enabled:{code:505,retryable:!1},server_busy:{code:302,retryable:!0}}},removeReaction:{range:"110,505,1301,1302",localErrors:{removeReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},getReactionList:{range:"110,505,600",localErrors:{getReactionList:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},group_invalid_id:{code:600,retryable:!1}}},getReactionDetail:{range:"110,505,1302",localErrors:{getReactionDetail:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},pinMessage:{range:"4,110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_limit:{code:4,aliases:["91101"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102"],retryable:!1}}},unpinMessage:{range:"110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getPinnedMessageList:{range:"110,111",errors:{operation_unsupported:{code:111,aliases:["15002"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getSupportedTranslationLanguages:{range:"505",errors:{service_not_enabled:{code:505,aliases:["service not open!"],retryable:!1}}},translateMessage:{range:"505,1110-1113",localErrors:{translateMessage:{validation_invalid:{code:1110,retryable:!1}}},errors:{translate_text_too_long:{code:1110,runtimeMessage:"Translation text is too long",retryable:!1},translate_param_invalid:{code:1110,runtimeMessage:"Invalid target language",retryable:!1},service_not_enabled:{code:1111,runtimeMessage:"Translation service is not enabled",aliases:["service not open!"],retryable:!1},translate_usage_limit:{code:1112,runtimeMessage:"Translation quota has been reached",aliases:["The request has reached the maximum limit"],retryable:!1},translate_failed:{code:1113,runtimeMessage:"Translation service error",aliases:["The request failed, please try again later."],retryable:!1}}},voiceMessageToText:{range:"4,110,202,407-411,505",localErrors:{voiceMessageToText:{validation_invalid:{code:407,retryable:!1},file_not_found:{code:410,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},file_not_found:{code:410,retryable:!1,aliases:["4041001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},voiceFileToText:{range:"4,110,202,402,407-411,505",localErrors:{voiceFileToText:{validation_invalid:{code:407,retryable:!1},upload_required:{code:110,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},upload_failed:{code:402,retryable:!0,aliases:["5021001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},getConversationList:{range:"110",localErrors:{getConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPinnedConversationList:{range:"110",localErrors:{getPinnedConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getConversationListByMark:{range:"110",localErrors:{getConversationListByMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},deleteConversation:{range:"110",localErrors:{deleteConversation:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearConversationUnreadMessageCount:{range:"110,201,300,500",localErrors:{clearConversationUnreadMessageCount:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},clearAllConversationUnreadMessageCount:{range:"201,300,500",errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},sendMessageReadReceipts:{range:"110,300",localErrors:{sendMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_direction:{code:110,retryable:!1},not_connected:{code:300,retryable:!0}}},getGroupMessageReadReceipts:{range:"110,202,210,303",localErrors:{getGroupMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},auth_bad_access_token:{code:202,httpStatus:401,retryable:!1},forbidden_op:{code:210,httpStatus:403,retryable:!1},unknown_exception_error:{code:303,httpStatus:500,retryable:!0}}},setConversationPinned:{range:"110",localErrors:{setConversationPinned:{validation_invalid:{code:110,retryable:!1}}},errors:{}},addConversationMark:{range:"110",localErrors:{addConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},removeConversationMark:{range:"110",localErrors:{removeConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearAllMessagesAndConversations:{range:"",errors:{}},searchMessages:{range:"110,202,303,505",localErrors:{searchMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{parameter_error:{code:110,httpStatus:400,retryable:!1,aliases:["4000005","4000006"]},token_invalid:{code:202,httpStatus:401,retryable:!1,aliases:["4010101"]},service_not_enabled:{code:505,httpStatus:403,retryable:!1,aliases:["4030204"]},app_not_found:{code:110,httpStatus:404,retryable:!1,aliases:["4040302"]},server_error:{code:303,httpStatus:500,retryable:!0,aliases:["5000701","5020801"]}}}}}),ut=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}async sendMessage(e,t){return this.getClientOrThrow().sendMessage(e,t)}createTextMessage(e){return((e,t)=>{const r=Q.validateOrThrow(Ie,e),a=Oe(t),s=Re(),i={content:r.content};return r.targetLanguages&&(i.targetLanguages=r.targetLanguages),Ae(r,a,"text",i,s)})(e,this.buildMessageSenderOrThrow())}createImageMessage(e){return((e,t,r)=>{const a=Q.validateOrThrow(fe,e),i=Oe(t),n=Re(),o=a.data?Ne(void 0,a.data):"",d=a.originalUrl?s(a.originalUrl,{deriveVariants:!r?.useCustomAttachmentUpload}):void 0;a.data&&k.set(n,a.data);const l=a.isGif??!1,c={localUrl:o,filename:a.filename,filetype:a.filetype,width:a.width,height:a.height,isGif:l,isOriginalImage:Me({isGif:l,isOriginalImage:a.isOriginalImage})};return d?.originalImageUrl&&(c.originalImageUrl=d.originalImageUrl,c.bigImageUrl=d.bigImageUrl,c.thumbnailUrl=d.thumbnailUrl),void 0!==a.fileLength&&(c.fileLength=a.fileLength),a.thumbnailUrl&&(c.thumbnailUrl=a.thumbnailUrl),Ae(a,i,"image",c,n)})(e,this.buildMessageSenderOrThrow(),this.getClientOrThrow().getMessageCreationOptions())}createFileMessage(e){return((e,t)=>{const r=Q.validateOrThrow(be,e),a=Oe(t),s=Re(),i=Ne(r.originalUrl,r.data);r.data&&k.set(s,r.data);const n={url:i,filename:r.filename,filetype:r.filetype};return void 0!==r.fileSize&&(n.fileSize=r.fileSize),void 0!==r.fileLength&&(n.fileLength=r.fileLength),Ae(r,a,"file",n,s)})(e,this.buildMessageSenderOrThrow())}createVoiceMessage(e){return((e,t)=>{const r=Q.validateOrThrow(Te,e),a=Oe(t),s=Re(),i=Ne(r.originalUrl,r.data);r.data&&k.set(s,r.data);const n={url:i,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.fileLength&&(n.fileLength=r.fileLength),Ae(r,a,"voice",n,s)})(e,this.buildMessageSenderOrThrow())}createVideoMessage(e){return((e,t)=>{const r=Q.validateOrThrow(_e,e),a=Oe(t),s=Re(),i=Ne(r.originalUrl,r.data);r.data&&k.set(s,r.data);const n={url:i,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.width&&(n.width=r.width),void 0!==r.height&&(n.height=r.height),void 0!==r.fileLength&&(n.fileLength=r.fileLength),r.thumbnailUrl&&(n.thumbnailUrl=r.thumbnailUrl),Ae(r,a,"video",n,s)})(e,this.buildMessageSenderOrThrow())}createLocationMessage(e){return((e,t)=>{const r=Q.validateOrThrow(Ce,e),a=Oe(t),s={latitude:r.latitude,longitude:r.longitude};return r.address&&(s.address=r.address),r.buildingName&&(s.buildingName=r.buildingName),Ae(r,a,"location",s)})(e,this.buildMessageSenderOrThrow())}createCmdMessage(e){return((e,t)=>{const r=Q.validateOrThrow(Ee,e),a=Oe(t),s={action:r.action};return void 0!==r.deliverOnlineOnly&&(s.deliverOnlineOnly=r.deliverOnlineOnly),Ae(r,a,"cmd",s)})(e,this.buildMessageSenderOrThrow())}createCustomMessage(e){return((e,t)=>{const r=Q.validateOrThrow(Le,e),a=Oe(t),s={event:r.event};return r.params&&(s.params=r.params),Ae(r,a,"custom",s)})(e,this.buildMessageSenderOrThrow())}createCombineMessage(e){return Ue(e,this.buildMessageSenderOrThrow())}getConversationList(e){if(void 0!==e?.mark&&(!Number.isInteger(e.mark)||e.mark<0||e.mark>19))throw new t("filter.mark must be an integer between 0 and 19",{code:r.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"filter.mark",message:"filter.mark must be an integer between 0 and 19",rule:"invalid_format"}]}});const a=(this.getClientOrThrow().getCacheManager()?.loadSessionList()??[]).filter(t=>null!==t.lastMessage&&((void 0===e?.isPinned||t.isPinned===e.isPinned)&&!(void 0!==e?.mark&&!C(t,e.mark)))).map(E);return this.getClientOrThrow().markConversationAccess(a.map(e=>({conversationId:e.conversationId,type:e.conversationType}))),a}setCurrentConversation(e){this.validateConversationLocator(e),this.getClientOrThrow().getCacheManager()?.setCurrentConversation({conversationId:e.conversationId,type:e.conversationType})}resetCurrentConversation(){this.getClientOrThrow().getCacheManager()?.resetCurrentConversation()}getCurrentConversation(){const e=this.getClientOrThrow().getCacheManager()?.getCurrentConversation()??null;return e?{conversationId:e.conversationId,conversationType:e.type}:null}refreshSessionList(e){return this.getClientOrThrow().refreshSessionList(e)}async deleteConversation(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const a=ne(t),s=Y(r.conversationId,"params.conversationId"),i=J(r.conversationType,"params.conversationType"),n=r.deleteRoamingMessages??!1;if("boolean"!=typeof n)throw W("params.deleteRoamingMessages","params.deleteRoamingMessages must be a boolean");return await e.request(`/${a.orgName}/${a.appName}/user/${a.encodedUserId}/user_channel?resource=${a.encodedResource}`,{method:"DELETE",body:{channel:s,type:"groupChat"===i?"groupChat":ee(i),delete_roam:n},operation:"deleteConversation"}),{conversationId:s,conversationType:i,operation:"delete"}})(this.getRestClient(t),t,e),a=this.getClientOrThrow(),s=a.getCacheManager()?.deleteConversation({conversationId:r.conversationId,type:r.conversationType});return s?.changed&&a.emitConversationListUpdate("local"),r}async setConversationPinned(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const a=ne(t),s=Y(r.conversationId,"params.conversationId"),i=J(r.conversationType,"params.conversationType");if("boolean"!=typeof r.pinned)throw W("params.pinned","params.pinned must be a boolean");const n="groupChat"===i?"groupChat":ee(i),o=r.pinned?await e.post(`/${a.orgName}/${a.appName}/sdk/user/${a.encodedUserId}/user_channel/top?resource=${a.encodedResource}`,{type:n,to:s},{operation:"setConversationPinned"}):await e.delete(`/${a.orgName}/${a.appName}/sdk/user/${a.encodedUserId}/user_channel/top?type=${encodeURIComponent(n)}&to=${encodeURIComponent(s)}&resource=${a.encodedResource}`,{operation:"setConversationPinned"}),d=T(o)&&T(o.data)?o.data:{};return{conversationId:s,conversationType:i,operation:"setPinned",isPinned:"boolean"==typeof d.is_top?d.is_top:r.pinned,pinnedTime:"number"==typeof d.update_top_status_time?d.update_top_status_time:r.pinned?Date.now():0}})(this.getRestClient(t),t,e),a=this.getClientOrThrow().getCacheManager(),s=a?.applyConversationPinnedMutation({conversationId:r.conversationId,type:r.conversationType,isPinned:r.isPinned??e.pinned,pinnedTime:r.pinnedTime});return s?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async addConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>oe(e,t,r,!0))(this.getRestClient(t),t,e),a=this.getClientOrThrow().getCacheManager(),s=a?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return s?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async removeConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>oe(e,t,r,!1))(this.getRestClient(t),t,e),a=this.getClientOrThrow().getCacheManager(),s=a?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return s?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async clearAllMessagesAndConversations(){const e=this.getRestContextOrThrow();await(async(e,t)=>{const r=ne(t);await e.post(`/${r.orgName}/${r.appName}/sdk/message/roaming/user/${r.encodedUserId}/delete/all?resource=${r.encodedResource}`,void 0,{operation:"clearAllMessagesAndConversations"})})(this.getRestClient(e),e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversations();r?.changed&&t.emitConversationListUpdate("local")}async pinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>de(e,t,r,!0))(this.getRestClient(t),t,e))}async unpinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>de(e,t,r,!1))(this.getRestClient(t),t,e))}async getPinnedMessageList(e){const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=ne(t),s=Y(r.conversationId,"params.conversationId"),i=J(r.conversationType,"params.conversationType"),n=await e.get(`/${a.orgName}/${a.appName}/sdk/user/${a.encodedUserId}/user_channel/pin?to=${encodeURIComponent(s)}&type=${encodeURIComponent(ee(i))}&limit=${String(20)}`,{operation:"getPinnedMessageList"}),o=T(n)&&T(n.data)?n.data:{};return{items:(Array.isArray(o.msg_infos)?o.msg_infos:[]).reduce((e,r)=>{if(!T(r))return e;const a="string"==typeof r.pin_msg_id?r.pin_msg_id:T(r.message)&&"string"==typeof r.message.id?r.message.id:"";if(!a)return e;const n="number"==typeof r.pin_opt_at?r.pin_opt_at:0,o=se(r.message,{messageId:a,conversationId:s,conversationType:i,currentUserId:t.userId,timestamp:n});return o?(e.push({messageId:a,conversationId:s,conversationType:i,operatorId:"string"==typeof r.pin_operator?r.pin_operator:void 0,pinnedAt:n,message:o}),e):e},[])}})(this.getRestClient(t),t,e))}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async clearConversationUnreadMessageCount(e){this.validateUnreadConversationLocator(e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversationUnreadMessageCount({conversationId:e.conversationId,type:e.conversationType});r?.changed&&t.emitConversationListUpdate("local");try{await this.requireConnectedClient().sendMessageAction({kind:"clearConversationUnreadMessageCount",conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:!1},(e,t)=>this.buildActionError(e,t))}catch(a){if(!r?.matched)throw a;p.warn("Conversation unread remote sync failed after local clear",{conversationId:e.conversationId,conversationType:e.conversationType,error:a})}}async sendMessageReadReceipts(e){this.validateSendMessageReadReceiptsParams(e),await this.requireConnectedClient().sendMessageAction({kind:"sendMessageReadReceipts",conversationId:e.conversationId,conversationType:e.conversationType,messageIds:e.messageIds},(e,t)=>this.buildActionError(e,t))}async clearAllConversationUnreadMessageCount(){await this.requireConnectedClient().sendMessageAction({kind:"clearAllConversationUnreadMessageCount",conversationId:this.getCurrentUserIdOrThrow(),conversationType:"singleChat",sendToPeer:!1,clearAllUnreadMessageCount:!0},(e,t)=>this.buildActionError(e,t));const e=this.getClientOrThrow(),t=e.getCacheManager()?.clearAllConversationUnreadMessageCount();t?.changed&&e.emitConversationListUpdate("local")}async recallMessage(e){this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId"),await this.requireConnectedClient().sendMessageAction({kind:"recall",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,ext:e.ext},(e,t)=>this.buildActionError(e,t));return{messageId:e.messageId,conversationId:e.conversationId,conversationType:e.conversationType,timestamp:Date.now()}}async modifyMessage(e){if(this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId"),"text"!==e.message.type&&"custom"!==e.message.type)throw new t("only text and custom messages are editable",{code:r.OPERATION_UNSUPPORTED});await this.requireConnectedClient().sendMessageAction({kind:"update",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,body:e.message.body,messageType:e.message.type,ext:e.message.ext},(e,t)=>this.buildActionError(e,t));const a=Date.now(),s=this.getCurrentUserIdOrThrow(),i={operatorId:s,operationCount:1,operationTime:a};return{msgServerId:e.messageId,msgLocalId:"",from:s,to:e.conversationId,sender:{userId:s},conversationId:e.conversationId,conversationType:e.conversationType,type:e.message.type,sendStatus:"sent",ext:e.message.ext,timestamp:a,body:e.message.body,direct:"SEND",modifiedInfo:i}}async getHistoryMessages(e){if(this.validateConversationLocator(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r,a)=>{const s=`${Se(t)}/users/${t.userId}/messageroaming`,i=await e.post(s,{queue:"singleChat"===r.conversationType?`${r.conversationId}@easemob.com`:`${r.conversationId}@conference.easemob.com`,start:r.cursor&&r.cursor.length>0?r.cursor:-1,pull_number:r.pageSize??20,is_positive:"down"===r.searchDirection,msgType:(r.messageTypes??[]).join(","),end:-1,startTime:r.startTime??null,endTime:r.endTime??null,userIds:"singleChat"===r.conversationType?null:r.senderIds&&r.senderIds.length>0?r.senderIds:null},{operation:"getHistoryMessages"}),n=qe(i,"getHistoryMessages"),o=Array.isArray(n.msgs)?n.msgs:[],d=[];for(const l of o){if(!De(l)||"string"!=typeof l.msg||0===l.msg.length)continue;const e=a(xe(l.msg));e&&d.push(e)}return{items:d,cursor:Ve(n.next_key),hasMore:!0!==n.is_last&&d.length>0}})(this.getRestClient(t),t,e,e=>this.getClientOrThrow().decodeServerMessageMeta(e)))}async searchMessages(e){const t=Q.validateOrThrow(ct,e),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>Qe(this.getRestClient(r),r,t))}async downloadAttachment(e){return this.getClientOrThrow().downloadAttachment(e.message)}async downloadAndParseCombineMessage(e){return this.getClientOrThrow().downloadAndParseCombinePayload(this.resolveDownloadCombineMessageParams(e))}async removeHistoryMessages(e){if(this.validateConversationLocator(e),!e.messageIds&&!e.beforeTimestamp)throw this.buildValidationError("messageIds or beforeTimestamp is required","removeHistoryMessages");if(e.messageIds&&0===e.messageIds.length)throw this.buildValidationError("messageIds cannot be empty","messageIds");if(void 0!==e.beforeTimestamp&&(!Number.isInteger(e.beforeTimestamp)||e.beforeTimestamp<=0))throw this.buildValidationError("beforeTimestamp must be a positive integer","beforeTimestamp");const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const a="singleChat"===r.conversationType?"userId":"groupId",s="singleChat"===r.conversationType?"chat":"group",i=encodeURIComponent(t.clientResource),n=r.messageIds?`${Se(t)}/sdk/message/roaming/${s}/user/${t.userId}?${a}=${encodeURIComponent(r.conversationId)}&msgIdList=${encodeURIComponent(r.messageIds.join(","))}&resource=${i}`:`${Se(t)}/sdk/message/roaming/${s}/user/${t.userId}/time?${a}=${encodeURIComponent(r.conversationId)}&delTime=${r.beforeTimestamp}&resource=${i}`;await e.delete(n,{operation:"removeHistoryMessages"})})(this.getRestClient(t),t,e))}async getGroupMessageReadUsers(e){if(this.requireNonEmptyString(e.groupId,"groupId"),this.requireNonEmptyString(e.messageId,"messageId"),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow(),r=await this.executeRestOperation(()=>(async(e,t,r)=>{const a=N();a.set("limit",String(r.pageSize??10)),r.cursor&&a.set("key",r.cursor);const s=`${Se(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/${encodeURIComponent(r.messageId)}?${a.toString()}`,i=await e.get(s,{operation:"getGroupMessageReadUsers"}),n=qe(i,"getGroupMessageReadUsers"),o=De(n.group_ack)?n.group_ack:n,d=(Array.isArray(o.userlist)?o.userlist:[]).map(e=>De(e)&&"string"==typeof e.username?{userId:e.username,user:Pe(e.username),ackId:"string"==typeof e.meta_id?e.meta_id:void 0,timestamp:"number"==typeof e.timestamp?e.timestamp:void 0,ackContent:"string"==typeof e.ack_content?e.ack_content:void 0}:null).filter(e=>null!==e);return{groupId:r.groupId,messageId:"string"==typeof n.ackmid?n.ackmid:r.messageId,users:d,count:"number"==typeof o.total?o.total:d.length,cursor:Ve(o.next_key),hasMore:!0!==o.is_last&&d.length>0}})(this.getRestClient(t),t,e));return await this.hydrateGroupMessageReadUsers(e.groupId,r)}async getGroupMessageReadReceipts(e){this.requireNonEmptyString(e.groupId,"groupId");const t=this.validateMessageIdList(e.messageIds,"messageIds"),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=`${Se(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/batch`,s=await e.post(a,{messageIds:r.messageIds},{operation:"getGroupMessageReadReceipts"});return Fe(s,"getGroupMessageReadReceipts").map(e=>De(e)&&"string"==typeof e.ackmid&&"number"==typeof e.total?{messageId:e.ackmid,count:e.total}:null).filter(e=>null!==e)})(this.getRestClient(r),r,{groupId:e.groupId.trim(),messageIds:t}))}async addReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{await e.post(`${Se(t)}/reaction/user/${t.userId}`,{msgId:r.messageId,message:r.reaction},{operation:"addReaction"})})(this.getRestClient(t),t,e))}async removeReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const a=`${Se(t)}/reaction/user/${t.userId}?msgId=${encodeURIComponent(r.messageId)}&message=${encodeURIComponent(r.reaction)}`;await e.delete(a,{operation:"removeReaction"})})(this.getRestClient(t),t,e))}async getReactionList(e){if(!e.messageId||Array.isArray(e.messageId)&&0===e.messageId.length)throw this.buildValidationError("messageId is required","messageId");"groupChat"===e.conversationType&&this.requireNonEmptyString(e.groupId??"","groupId");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=N(),s="string"==typeof r.messageId?r.messageId:[...r.messageId].join(",");a.set("msgIdList",s),a.set("msgType","groupChat"===r.conversationType?"group":"chat"),r.groupId&&a.set("groupId",r.groupId);const i=await e.get(`${Se(t)}/reaction/user/${t.userId}?${a.toString()}`,{operation:"getReactionList"});return Fe(i,"getReactionList").map(e=>{if(!De(e)||"string"!=typeof e.msgId)return null;const t=Array.isArray(e.reactionList)?e.reactionList:[];return{messageId:e.msgId,reactions:t.map(e=>De(e)&&"string"==typeof e.reaction?{reaction:e.reaction,count:"number"==typeof e.count?e.count:0,isAddedBySelf:!0===e.state,userIds:Array.isArray(e.userList)?e.userList.filter(e=>"string"==typeof e):[]}:null).filter(e=>null!==e)}}).filter(e=>null!==e)})(this.getRestClient(t),t,e))}async getReactionDetail(e){if(this.validateReactionParams(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=N();a.set("msgId",r.messageId),a.set("message",r.reaction),a.set("cursor",r.cursor??""),a.set("limit",String(r.pageSize??20));const s=await e.get(`${Se(t)}/reaction/user/${t.userId}/detail?${a.toString()}`,{operation:"getReactionDetail"}),i=qe(s,"getReactionDetail"),n=Array.isArray(i.reactionUserList)?i.reactionUserList.map(e=>De(e)&&"string"==typeof e.userId?{userId:e.userId,user:Pe(e.userId),createdAt:"string"==typeof e.createdAt?e.createdAt:void 0}:null).filter(e=>null!==e):[],o=Array.isArray(i.userList)?i.userList.filter(e=>"string"==typeof e).map(e=>({userId:e,user:Pe(e)})):[],d=n.length>0?n:o;return{reaction:"string"==typeof i.reaction?i.reaction:r.reaction,count:"number"==typeof i.count?i.count:d.length,isAddedBySelf:!0===i.state,reactionUsers:d,cursor:Ve(i.cursor),hasMore:Ve(i.cursor).length>0,createdAt:"string"==typeof i.createdAt?i.createdAt:void 0}})(this.getRestClient(t),t,e))}async getSupportedTranslationLanguages(){const e=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t)=>{const r=await $e(()=>e.get(`${Se(t)}/users/${t.userId}/translate/support/language`,{operation:"getSupportedTranslationLanguages"}));return Be(r,"getSupportedTranslationLanguages").map(e=>De(e)&&"string"==typeof e.code?{code:e.code,name:"string"==typeof e.name?e.name:e.code,nativeName:"string"==typeof e.nativeName?e.nativeName:e.code}:null).filter(e=>null!==e)})(this.getRestClient(e),e))}async translateMessage(e){if("text"!==e.message.type)throw new t("only text messages can be translated",{code:r.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"message.type",message:"must be text",rule:"message_type"}]}});const a=e.message.body.content.trim();if(0===a.length)throw new t("message text is required",{code:r.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"message.body.content",message:"is required",rule:"required"}]}});if(!Array.isArray(e.targetLanguages)||0===e.targetLanguages.length)throw new t("targetLanguages is required",{code:r.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"targetLanguages",message:"is required",rule:"required"}]}});if(e.targetLanguages.some(e=>"string"!=typeof e||0===e.trim().length))throw new t("targetLanguages contains invalid language code",{code:r.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"targetLanguages",message:"contains invalid language code",rule:"language_code"}]}});const s=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const a=await $e(()=>e.post(`${Se(t)}/users/${t.userId}/translate`,{text:r.text,to:[...r.targetLanguages]},{operation:"translateMessage"})),s=Be(a,"translateMessage"),n=De(s[0])?s[0]:null;if(!n)throw i({apiName:"translateMessage",message:"translateMessage response data is invalid",mapped:!1});const o=Array.isArray(n.translations)?n.translations:[],d=De(n.detectedLanguage)?n.detectedLanguage:void 0;return{detectedLanguage:d&&"string"==typeof d.language?{language:d.language,score:"number"==typeof d.score?d.score:Number(d.score??0)}:void 0,translations:o.map(e=>De(e)&&"string"==typeof e.text&&"string"==typeof e.to?{text:e.text,to:e.to}:null).filter(e=>null!==e)}})(this.getRestClient(s),s,{text:a,targetLanguages:e.targetLanguages}))}async voiceMessageToText(e,t){nt(e,t);const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>dt(this.getRestClient(r),r,e,t))}async voiceFileToText(e,t){ot(e,t);const a=this.getRestContextOrThrow(),s=this.getClientOrThrow().getUploadAdapter();if(!s)throw new g("Upload capability is missing for current platform",r.UPLOAD_REQUIRED_FIELD_MISSING);return this.executeRestOperation(()=>(async(e,t,a,s)=>{const i=ot(a,s),n=d({file:i,fallbackName:Ze(i)?"voice.amr":void 0,fallbackMimeType:"audio/amr"});try{const a=await e.upload({url:`${t.restBaseUrl}${We(t)}/speech/recognitions`,headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json",[l]:c()},source:n.source,fields:{username:t.userId,...s?.format?{format:s.format}:{},...void 0!==s?.sampleRate?{sampleRate:String(s.sampleRate)}:{},...void 0!==s?.bitsPerSample?{bitsPerSample:String(s.bitsPerSample)}:{},...void 0!==s?.channels?{channels:String(s.channels)}:{}}});let i=a.body;try{i=JSON.parse(a.body)}catch{i=a.body}if(a.status<200||a.status>=300)throw new g("Voice-to-text failed",r.VOICE_TO_TEXT_FAILED,{details:{httpStatus:a.status,rawResponse:i}});return{text:tt(i,"voiceFileToText")}}catch(o){if(o instanceof g)throw it(o);throw it(L(o))}})(s,a,e,t))}validateConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType&&"chatRoom"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType")}validateUnreadConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType must be singleChat or groupChat","conversationType")}validateSendMessageReadReceiptsParams(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType");if(e.messageIds.length>50)throw this.buildValidationError("messageIds cannot contain more than 50 items","messageIds");return this.validateMessageIdList(e.messageIds,"messageIds")}validateMessageIdList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError(`${t} cannot be empty`,t);return e.map((e,r)=>{if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t}.${r} is invalid`,`${t}.${r}`);return e.trim()})}resolveDownloadCombineMessageParams(e){if("message"in e){if("combine"!==e.message.type)throw new t("message must be a combine message",{code:r.VALIDATION_INVALID_FORMAT});const a=e.message.body;return{url:a.url??"",secret:a.secret,timeoutMs:e.timeoutMs,maxItems:e.maxItems}}return{url:e.url,secret:e.secret,timeoutMs:e.timeoutMs,maxItems:e.maxItems}}validateReactionParams(e){this.requireNonEmptyString(e.messageId,"messageId"),this.requireNonEmptyString(e.reaction,"reaction")}buildActionError(e,a){return e===r.AUTH_NOT_LOGIN||e===r.AUTH_UNAUTHORIZED?new u(a??"authentication failed",{code:e}):e===r.CONNECTION_WEBSOCKET_ERROR||e===r.CONNECTION_TIMEOUT?new h(a??"connection unavailable",{code:e}):107===e||110===e||205===e||500===e||e===r.VALIDATION_REQUIRED||e===r.VALIDATION_INVALID_FORMAT?new t(a??"invalid parameter",{code:e}):e===r.MESSAGE_RECALL_TIME_LIMIT?new g(a??"message recall time limit reached",e):e===r.MESSAGE_EDIT_FAILED?new g(a??"message update failed",e):e===r.OPERATION_UNSUPPORTED?new t(a??"operation unsupported",{code:e}):new g(a??"message action failed",e)}requireNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} is required`,t)}buildValidationError(e,a){return new t(e,{code:r.VALIDATION_INVALID_FORMAT,details:{fields:[{path:a,message:e,rule:"required"}]}})}getEventContextOrThrow(){if(!this.eventContext)throw new t("ChatManager is not bound to event context",{code:r.VALIDATION_REQUIRED});return this.eventContext}getClientOrThrow(){if(!this.client)throw new t("ChatManager is not bound to client",{code:r.VALIDATION_REQUIRED});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new y(e.restBaseUrl,{errorMap:gt,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireConnectedClient(){const e=this.getClientOrThrow();if(e.getConnectionState()!==M.CONNECTED)throw new h("client is not connected",{code:r.CONNECTION_WEBSOCKET_ERROR});return e}getCurrentUserIdOrThrow(){const e=this.getClientOrThrow().getCurrentUserId();if(!e)throw new u("user is not logged in",{code:r.AUTH_NOT_LOGIN});return e}buildMessageSenderOrThrow(){const e=this.getClientOrThrow(),t=this.getCurrentUserIdOrThrow(),r=e.getCacheManager()?.getUserInfoSummaries([t],!1)[0];return{userId:t,nickname:r?.nickname,avatarUrl:r?.avatarUrl}}async hydrateGroupMessageReadUsers(e,t){const r=this.getClientOrThrow();if(!r.isUserInfoSyncEnabled()||0===t.users.length)return t;const a=r.getCacheManager(),s=await w({groupId:e,users:t.users.map(e=>e.user),includeNameCard:!0,cacheManager:a,fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoReadCapability(r);return t?await t.getUserInfoByUserId({userIds:e}):[]},hydrateGroupNamecards:async(e,t)=>{const a=this.getGroupNamecardHydrationCapability(r);a&&await a.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))}});return this.dispatchFetchedUserInfoUpdates(r,s.fetchedUserInfos),{...t,users:t.users.map(e=>{const t=s.usersById.get(e.userId)??e.user;return{...e,user:t}})}}getUserInfoReadCapability(e){const t=e.getManagerByCapability("userInfo:read");return t&&"function"==typeof t.getUserInfoByUserId?t:null}getGroupNamecardHydrationCapability(e){const t=e.getManagerByCapability("group:namecard");return t&&"function"==typeof t.hydrateMessageProfileGroupNamecards?t:null}dispatchFetchedUserInfoUpdates(e,t){if(0===t.length)return;const r=e.getCurrentUserId(),a=t.find(e=>e.userId===r),s=t.filter(e=>e.userId!==r);a&&e.dispatchOwnInfoUpdated(a),e.dispatchUserInfoUpdated(s),t.length>0&&e.refreshConversationDisplayFromUserInfos(t.map(e=>({userId:e.userId})),"profile")}async executeRestOperation(e){try{return await e()}catch(t){throw this.mapRestError(t)}}mapRestError(e){return e instanceof t||e instanceof u||e instanceof h||e instanceof v?e:e instanceof I?new v(e.message,{code:e.code,details:e.details}):e instanceof n||e instanceof g?e:new g(String(e),r.UNKNOWN)}};ut.key="chatManager";let mt=ut;export{mt as C,U as I,q as M,Q as V,M as a,A as b,S as c,X as d,K as e,V as f,D as g,k as h,$ as i,j,P as k,H as v};
@@ -0,0 +1 @@
1
+ "use strict";const e={VALIDATION_REQUIRED:110,VALIDATION_INVALID_FORMAT:110,VALIDATION_UNKNOWN:110,AUTH_ALREADY_LOGIN:200,AUTH_NOT_LOGIN:201,AUTH_UNAUTHORIZED:202,AUTH_FORBIDDEN:210,AUTH_TOKEN_EXPIRED:108,AUTH_BIND_ANOTHER_DEVICE:213,AUTH_LOGIN_TOO_MANY_DEVICES:214,AUTH_USER_MUTED:215,CONNECTION_TIMEOUT:301,CONNECTION_WEBSOCKET_ERROR:300,CONNECTION_NOT_CREATED:1,CONNECTION_CLOSED_BEFORE_READY:300,CONNECTION_CANCELLED:1,CONNECTION_PROVISION_TIMEOUT:301,CONNECTION_PROVISION_REJECTED:202,CONNECTION_PROVISION_CLOSED:300,CONNECTION_DNSLIST_FAILED:304,STORAGE_OPERATION_FAILED:3,MESSAGE_NOT_CONNECTED:300,MESSAGE_ACK_TIMEOUT:301,MESSAGE_SEND_FAILED:303,MESSAGE_SENDER_DESTROYED:1,MESSAGE_ENCODE_FAILED:500,MESSAGE_DECODE_FAILED:500,MESSAGE_ACK_MISSING:301,MESSAGE_BLOCKED_BY_RECIPIENT:222,OPERATION_UNSUPPORTED:111,SERVER_BUSY:302,ATTACHMENT_NOT_FOUND:400,ATTACHMENT_INVALID:401,ATTACHMENT_EXPIRED:407,MESSAGE_INCLUDE_ILLEGAL_CONTENT:501,MESSAGE_SEND_TRAFFIC_LIMIT:502,MESSAGE_RECALL_TIME_LIMIT:504,SERVICE_NOT_ENABLED:505,MESSAGE_EXPIRED:506,MESSAGE_ILLEGAL_WHITELIST:507,MESSAGE_EXTERNAL_LOGIC_BLOCKED:508,MESSAGE_CURRENT_LIMITING:509,MESSAGE_SIZE_LIMIT:510,MESSAGE_EDIT_FAILED:511,INVALID_CONVERSATION:107,USER_LOGIN_ANOTHER_DEVICE:206,USER_REMOVED:207,USER_KICKED_BY_CHANGE_PASSWORD:216,USER_KICKED_BY_OTHER_DEVICE:217,USER_ALREADY_LOGIN_ANOTHER:218,USER_MUTED_BY_ADMIN:219,USER_DEVICE_CHANGED:220,USER_NOT_ON_ROSTER:221,SERVER_SERVING_DISABLED:305,FILE_DOWNLOAD_FAILED:403,FILE_TOO_LARGE:405,FILE_CONTENT_IMPROPER:406,THIRD_MODERATION_FAILED:1200,THIRD_DEFAULT_FAILED:1299,STREAM_SEND_NOT_SUPPORTED:303,STREAM_CHUNK_INVALID:500,STREAM_TIMEOUT_BY_SERVER:500,STREAM_STATE_CONFLICT:500,COMBINE_INVALID_INPUT:110,COMBINE_LEVEL_EXCEEDED:4,COMBINE_ITEM_LIMIT_EXCEEDED:4,COMBINE_ENCODE_FAILED:500,COMBINE_UPLOAD_FAILED:402,COMBINE_DOWNLOAD_FAILED:2,COMBINE_PARSE_FAILED:500,REST_NETWORK_ERROR:2,REST_TIMEOUT:301,REST_HTTP_ERROR:303,REST_BUSINESS_UNKNOWN:303,PUSH_TOKEN_UPLOAD_FAILED:1500,PUSH_SILENT_MODE_OPERATION_FAILED:1501,PUSH_LANGUAGE_OPERATION_FAILED:1502,USER_INFO_SUBSCRIPTION_LIMIT_EXCEEDED:1600,USER_INFO_SUBSCRIPTION_TARGET_LIMIT_EXCEEDED:1601,USERINFO_USERCOUNT_EXCEED:900,USERINFO_DATALENGTH_EXCEED:901,CONTACT_ADD_USER_NOT_FOUND:204,CONTACT_ADD_ALREADY_FRIEND:1e3,CONTACT_ADD_BLOCKED_BY_USER:210,CONTACT_SET_REMARK_NOT_FRIEND:223,CONTACT_REACH_LIMIT:1001,CONTACT_REACH_LIMIT_PEER:1002,CONTACT_BLOCKLIST_USER_NOT_FOUND:204,GROUP_INVALID_ID:600,GROUP_ALREADY_JOINED:601,GROUP_NOT_JOINED:602,GROUP_PERMISSION_DENIED:603,GROUP_MEMBERS_FULL:604,GROUP_SHARED_FILE_INVALID_ID:605,GROUP_NOT_EXIST:606,GROUP_DISABLED:607,GROUP_NAME_VIOLATION:608,GROUP_MEMBER_ATTRIBUTES_REACH_LIMIT:609,GROUP_MEMBER_ATTRIBUTES_UPDATE_FAILED:610,GROUP_MEMBER_ATTRIBUTES_KEY_REACH_LIMIT:611,GROUP_MEMBER_ATTRIBUTES_VALUE_REACH_LIMIT:612,GROUP_USER_IN_BLOCKLIST:613,CHATROOM_INVALID_ID:700,CHATROOM_NOT_JOINED:702,CHATROOM_PERMISSION_DENIED:703,CHATROOM_MEMBERS_FULL:704,CHATROOM_NOT_EXIST:705,CHATROOM_OWNER_NOT_ALLOW_LEAVE:706,CHATROOM_USER_IN_BLOCKLIST:707,CONTACT_SYNC_METADATA_FAILED:1700,CONTACT_SYNC_SOCKET_FAILED:1701,CONTACT_SYNC_CURSOR_INVALID:1702,CONTACT_SYNC_PROTO_DECODE_FAILED:1703,CONTACT_SYNC_CANCELLED:1704,SESSION_LIST_SOCKET_FAILED:300,SESSION_LIST_PROTO_DECODE_FAILED:500,SESSION_LIST_REQUEST_INVALID:110,SESSION_LIST_FETCH_FAILED:303,SESSION_LIST_SERVICE_DISABLED:305,SESSION_LIST_CANCELLED:1,PRESENCE_PARAM_LENGTH_EXCEED:1100,PRESENCE_CANNOT_SUBSCRIBE_YOURSELF:1101,TRANSLATE_PARAM_INVALID:1110,TRANSLATE_SERVICE_NOT_ENABLED:1111,TRANSLATE_USAGE_LIMIT:1112,TRANSLATE_FAILED:1113,VOICE_TO_TEXT_FILE_INVALID:407,VOICE_TO_TEXT_FILE_DURATION_TOO_LONG:408,VOICE_TO_TEXT_FAILED:409,VOICE_TO_TEXT_FILE_NOT_FOUND:410,VOICE_TO_TEXT_FILE_TOO_LARGE:411,REACTION_REACH_LIMIT:1300,REACTION_ALREADY_OPERATED:1301,REACTION_OPERATION_ILLEGAL:1302,UPLOAD_REQUIRED_FIELD_MISSING:110,UPLOAD_INVALID_APPKEY:100,UPLOAD_SIZE_EXCEEDED:405,UPLOAD_REQUEST_FAILED:402,UPLOAD_TIMEOUT:301,UPLOAD_ABORTED:1,SERVICE_LIMIT_EXCEEDED:4,UNKNOWN:1},t="[REDACTED]",o=e=>{if(!e)return"";const o=e.includes("?"),r=e.includes("#");try{return((e,o,r)=>(e.username&&(e.username=t),e.password&&(e.password=t),e.search=o?`?${t}`:"",e.hash=r?`#${t}`:"",e.toString()))(new URL(e),o,r)}catch{const o=[e.indexOf("?"),e.indexOf("#")].filter(e=>e>=0).sort((e,t)=>e-t)[0];return void 0===o?"[invalid-url]":`${e.slice(0,o)}?${t}`}},r=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>"url"===e.toLowerCase()&&"string"==typeof t?[e,o(t)]:[e,t]));class s extends Error{constructor(t,o=e.UNKNOWN,i){super(t),this.name="SDKError",this.code=o,this.details=i?.details?r(i.details):void 0,Error.captureStackTrace&&Error.captureStackTrace(this,s)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class i extends s{constructor(t,o){super(t,o?.code??e.AUTH_UNAUTHORIZED,o),this.name="AuthenticationError"}}class n extends s{constructor(t,o){super(t,o?.code??e.VALIDATION_UNKNOWN,o),this.name="ValidationError"}}class a extends s{constructor(t,o){super(t,o?.code??e.REST_NETWORK_ERROR,o),this.name="RestTransportError"}}class p extends s{constructor(t,o){super(t,o?.code??e.REST_BUSINESS_UNKNOWN,o),this.name="RestBusinessError"}}class E extends s{constructor(t,o){super(t,o?.code??e.UPLOAD_REQUEST_FAILED,o),this.name="UploadError"}}const c={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",heic:"image/heic",heif:"image/heif",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",mp3:"audio/mpeg",m4a:"audio/mp4",wav:"audio/wav",aac:"audio/aac",amr:"audio/amr",pdf:"application/pdf",txt:"text/plain",json:"application/json"},T=e=>"undefined"!=typeof Blob&&e instanceof Blob,u=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),o=t.length>0?t[t.length-1]:void 0;if(o)return o},_=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const o=e.slice(t+1).toLowerCase();return c[o]},O=(e,t)=>{for(const o of t){const t=e[o];if("string"==typeof t&&t.length>0)return t}},d=e=>{const t=e.file,o=e.sourceMeta,r=t.name||(o?O(o,["name","fileName","filename"]):void 0),s=e.file.type||(o?O(o,["type","mimeType","filetype"]):void 0),i=e.file.size||(o?((e,t)=>{for(const o of t){const t=e[o];if("number"==typeof t&&Number.isFinite(t))return t}})(o,["size","fileSize","fileLength"]):void 0),n=l({fileName:r,fileType:s,fileSize:i,fallbackName:e.fallbackName,fallbackMimeType:e.fallbackMimeType,fallbackSize:e.fallbackSize});return{source:{sourceType:"web-file",file:e.file,name:n.fileName,mimeType:n.fileType,size:n.fileSize},fileName:n.fileName,fileType:n.fileType,fileSize:n.fileSize,webFile:e.file}},l=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),R=e=>{const{file:t,fallbackName:o,fallbackMimeType:r,fallbackSize:s}=e,i=(e=>{if(T(e))return e;if("object"!=typeof e||null===e)return;const t=e;for(const o of["file","originFileObj","raw","blob"]){const e=t[o];if(T(e))return e}})(t);if(i)return d({file:i,fallbackName:o,fallbackMimeType:r,fallbackSize:s,sourceMeta:"object"==typeof t&&null!==t?t:void 0});if((e=>"object"==typeof e&&null!==e&&"path"in e)(t)){const e=u(t.path),i=l({fileName:t.name??e,fileType:t.type??_(t.name??e),fileSize:t.size,fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"miniapp-path",path:t.path,name:i.fileName,mimeType:i.fileType,size:i.fileSize},fileName:i.fileName,fileType:i.fileType,fileSize:i.fileSize}}if((e=>"object"==typeof e&&null!==e&&"uri"in e)(t)){const e=u(t.uri),i=l({fileName:t.name??e,fileType:t.type??_(t.name??e),fileSize:t.size,fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"rn-uri",uri:t.uri,name:i.fileName,mimeType:i.fileType,size:i.fileSize},fileName:i.fileName,fileType:i.fileType,fileSize:i.fileSize}}const n=l({fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"web-file",name:n.fileName,mimeType:n.fileType,size:n.fileSize},fileName:n.fileName,fileType:n.fileType,fileSize:n.fileSize}},m="CHAT",h="GROUP",N="ROOM",A="original",I="large",S=e=>/^https?:\/\//i.test(e),f=t=>{const o=t.split("#");if(2!==o.length||!o[0]||!o[1])throw new E("Invalid appKey for upload",{code:e.UPLOAD_INVALID_APPKEY,details:{appKey:t}});return{orgName:o[0],appName:o[1]}},C=(e,t)=>D(e,{size:t}),y=e=>{try{return decodeURIComponent(e)}catch{return e}},D=(e,t)=>{const[o="",r]=e.split("#",2),[s,i=""]=o.split("?",2),n=i.split("&").filter(Boolean);return Object.entries(t).forEach(([e,t])=>{const o=encodeURIComponent(e),r=n.filter(t=>{const[r=""]=t.split("=",2);return r!==o&&y(r)!==e});n.length=0,n.push(...r),void 0!==t&&n.push(`${o}=${encodeURIComponent(String(t))}`)}),`${s}${n.length>0?`?${n.join("&")}`:""}${r?`#${r}`:""}`},M=(e,t)=>{if(!e)return{};if(!1===t?.deriveVariants)return{originalImageUrl:e};const o=(e=>{const[t="",o]=e.split("#",2),[r,s=""]=t.split("?",2),i=s.split("&").filter(Boolean).filter(e=>{const[t="",o=""]=e.split("=",2),r=y(t),s=y(o);return"size"!==r||!["big","large","thumbnail","small"].includes(s)}).join("&");return`${r}${i?`?${i}`:""}${o?`#${o}`:""}`})(e);return{originalImageUrl:o,bigImageUrl:C(o,"large"),thumbnailUrl:C(o,"small")}},U=e=>new Promise(t=>{setTimeout(t,e)});const g=new class{constructor(e){this.state="disabled",this.timerId=null,this.reporting=!1,this.context={},this.buffer=[],this.bufferBytes=0,this.reportIntervalMs=this.normalizeReportInterval(e?.reportIntervalMs),this.reportTimeoutMs=e?.reportTimeoutMs??15e3,this.chunkDelayMs=e?.chunkDelayMs??3e3,this.maxChunkBytes=e?.maxChunkBytes??2097152,this.maxBufferBytes=e?.maxBufferBytes??3145728}setEnabled(e){this.setState(e?"enabled":"disabled")}setState(e){this.state=e,"enabled"!==e?(this.stop(),this.clearBuffer()):this.start()}updateContext(e){this.context={...this.context,...e}}updateReportInterval(e){this.reportIntervalMs=this.normalizeReportInterval(e),"enabled"===this.state&&this.start()}append(e){if("disabled"===this.state)return;const t=this.formatEntry(e);this.pushBuffer(t)}async reportNow(){await this.reportLogs()}stop(){this.timerId&&(clearInterval(this.timerId),this.timerId=null)}clearBuffer(){this.buffer=[],this.bufferBytes=0}start(){this.stop(),this.timerId=setInterval(()=>{this.reportLogs()},this.reportIntervalMs)}normalizeReportInterval(e){const t=void 0!==e&&Number.isFinite(e)&&e>0?e:3e5;return Math.max(t,6e4)}canReport(){return Boolean(this.context.restBaseUrl&&this.context.appKey&&this.context.userId&&this.context.token&&this.context.requestAdapter)}formatEntry(e){const t=e.args.length>0?e.args.map(e=>(e=>{if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}})(e)).join(" "):"",o=t?`${e.message} ${t}`:e.message;return`${e.timestamp} [${e.level}] ${o}`}pushBuffer(e){const t=e.length;if(!(t>=this.maxBufferBytes)){for(;this.bufferBytes+t>this.maxBufferBytes&&this.buffer.length>0;){const e=this.buffer.shift();e&&(this.bufferBytes-=e.length)}this.buffer.push(e),this.bufferBytes+=t}}consumeBuffer(){if(0===this.buffer.length)return[];const e=`${this.buffer.join("\n")}\n`;this.clearBuffer();const t=[];let o=e;for(;o.length>this.maxChunkBytes;)t.push(o.slice(0,this.maxChunkBytes)),o=o.slice(this.maxChunkBytes);return o.length>0&&t.push(o),t}requeueChunk(e){this.pushBuffer(e)}async reportLogs(){if("enabled"===this.state&&!this.reporting&&0!==this.buffer.length){this.reporting=!0;try{const e=this.consumeBuffer();if(0===e.length)return;if(!this.canReport())return void e.forEach(e=>this.requeueChunk(e));for(const t of e){await this.reportChunk(t)||this.requeueChunk(t),await U(this.chunkDelayMs)}}finally{this.reporting=!1}}}async reportChunk(e){if(!this.canReport())return!1;const{restBaseUrl:t,appKey:o,userId:r,token:s,resource:i,requestAdapter:n}=this.context;if(!(t&&o&&r&&s&&n))return!1;let a="",p="";try{const e=f(o);a=e.orgName,p=e.appName}catch{return!1}const E=`${t}/${a}/${p}/sdk/users/${r}/client/logs`,c={resource:i??"webim",logContent:e};try{const e=await n.request({url:E,method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json"},body:c,responseType:"json",timeoutMs:this.reportTimeoutMs});if(e.status<200||e.status>=300)return!1;const t="string"==typeof e.data?(e=>{try{return JSON.parse(e)}catch{return}})(e.data):e.data;return!t||!t.status||"ok"===t.status}catch{return!1}}},L="[MASKED]",P=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),b=e=>!!e&&P.has((e=>e.toLowerCase())(e)),G=(e,t,o)=>{const r=o??new WeakSet;if("string"==typeof e)return((e,t)=>b(t)?L:e)(e,t);if("number"==typeof e||"boolean"==typeof e||null==e)return e;if("bigint"==typeof e||"symbol"==typeof e)return e.toString();if("function"==typeof e)return`[Function ${e.name||"anonymous"}]`;if(e instanceof Error)return{name:(s=e).name,message:s.message};var s;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>G(e,void 0,r));if("object"==typeof e){if(r.has(e))return"[Circular]";if(r.add(e),(e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Date||e instanceof Error))(e)){const t={};for(const[o,s]of Object.entries(e))b(o)?t[o]=L:t[o]=G(s,o,r);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},H="undefined"!=typeof document,w={DEBUG:0,WARN:1,ERROR:2};class B{constructor(e="WARN"){this.level=e}setLevel(e){this.level=e}shouldLog(e){return w[e]>=w[this.level]}emit(e,t,o){const r=(e=>{const t=new WeakSet;return e.map(e=>G(e,void 0,t))})(o),s=((e,t,o)=>({timestamp:(new Date).toISOString(),level:e,message:t,args:o}))(e,t,r);g.append(s);const i=new Date,n=`[Chat][${e}][${`${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}:${String(i.getSeconds()).padStart(2,"0")}.${String(i.getMilliseconds()).padStart(3,"0")}`}]`;H?console.log(`%c${n}`,"color: rgb(0, 157, 255); font-weight: bold",t,...r):console.log(n,t,...r)}debug(e,...t){this.shouldLog("DEBUG")&&this.emit("DEBUG",e,t)}warn(e,...t){this.shouldLog("WARN")&&this.emit("WARN",e,t)}error(e,...t){this.shouldLog("ERROR")&&this.emit("ERROR",e,t)}}let v=new B;const F={debug:(e,...t)=>v.debug(e,...t),warn:(e,...t)=>v.warn(e,...t),error:(e,...t)=>v.error(e,...t)},x=["__uniConfig","skipWaiting","registration","navigator","process","window","document","localStorage","fetch","WebSocket","XMLHttpRequest","FormData","TextEncoder","TextDecoder","crypto"],k=e=>{if(e)return e;return((e,t)=>{if(!e)return t;if(0===Object.keys(t).length)return e;const o={},r=e;for(const s of x)try{const e=r[s];void 0!==e&&(o[s]=e)}catch{}for(const s of Object.keys(t))o[s]=t[s];return o})("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0,{..."undefined"!=typeof wx?{wx:wx}:{},..."undefined"!=typeof qq?{qq:qq}:{},..."undefined"!=typeof tt?{tt:tt}:{},..."undefined"!=typeof swan?{swan:swan}:{},..."undefined"!=typeof my?{my:my}:{},..."undefined"!=typeof dd?{dd:dd}:{},..."undefined"!=typeof jd?{jd:jd}:{},..."undefined"!=typeof ks?{ks:ks}:{},..."undefined"!=typeof uni?{uni:uni}:{}})},K=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,V="X-Request-Id",q="direct";class ${constructor(e){this.events=[],this.enabled=!1,this.acceptedInWindow=0,this.capacityDiagnosticEmitted=!1,this.rateDiagnosticEmitted=!1,this.sendBatch=e.send,this.capacity=e.capacity??1e3,this.batchSize=e.batchSize??10,this.rateLimit=e.rateLimit??1e3,this.flushIntervalMs=e.flushIntervalMs??1e3,this.now=e.now??Date.now,this.onDrop=e.onDrop,this.windowStartedAt=this.now()}get size(){return this.events.length}enqueue(e){return this.refreshRateWindow(),this.acceptedInWindow>=this.rateLimit?(this.rateDiagnosticEmitted||(this.rateDiagnosticEmitted=!0,this.onDrop?.("rate-limit")),!1):this.events.length>=this.capacity?(this.capacityDiagnosticEmitted||(this.capacityDiagnosticEmitted=!0,this.onDrop?.("capacity")),!1):(this.events.push(e),this.acceptedInWindow+=1,this.schedule(),!0)}enable(){this.enabled=!0,this.schedule()}updateAppKey(e,t){for(let o=0;o<this.events.length;o+=1){const r=this.events[o];r&&r.appKey===e&&(this.events[o]={appKey:t,wire:{...r.wire,body:{...r.wire.body,appkey:t}}})}}pause(){this.enabled=!1,this.clearTimer()}clear(){this.pause(),this.events.splice(0,this.events.length),this.acceptedInWindow=0,this.windowStartedAt=this.now(),this.capacityDiagnosticEmitted=!1,this.rateDiagnosticEmitted=!1}refreshRateWindow(){const e=this.now();e-this.windowStartedAt<6e4||(this.windowStartedAt=e,this.acceptedInWindow=0,this.rateDiagnosticEmitted=!1)}schedule(){this.enabled&&0!==this.events.length&&!this.timer&&(this.timer=setTimeout(()=>{this.timer=void 0,this.consume()},this.flushIntervalMs))}async consume(){if(!this.enabled||0===this.events.length)return;const e=this.events[0];if(!e)return;const t=[];for(let o=0;o<this.events.length&&t.length<this.batchSize;){const r=this.events[o];r?.appKey===e.appKey?(t.push(r.wire),this.events.splice(o,1)):o+=1}this.events.length<this.capacity&&(this.capacityDiagnosticEmitted=!1);try{await this.sendBatch(e.appKey,t)}catch{}finally{this.schedule()}}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=void 0)}}class W{constructor(e){this.requestAdapter=e.requestAdapter,this.debug=e.debug??!1,this.now=e.now??Date.now,this.onFailure=e.onFailure}async send(e,t){if(this.requestAdapter&&0!==t.length)try{const o=await this.requestAdapter.request({url:this.debug?"https://data-reporting.realtimemesh.com/report":"https://data-reporting.rtnsvc.com/report",method:"POST",headers:{"Content-Type":"application/json",token:"32f24ab2ddb74f508aa9286c356cec84",appid:e,sendts:String(Math.floor(this.now()/1e3)),biz:"im",debug:String(this.debug)},body:JSON.stringify(t),responseType:"text",timeoutMs:15e3});(o.status<200||o.status>=300)&&this.onFailure?.({reason:"non-success-response",status:o.status})}catch(o){this.onFailure?.({reason:"transport-error",message:o instanceof Error?o.message:String(o)})}else this.onFailure?.({reason:"request-adapter-unavailable",eventCount:t.length})}}const z={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},j=()=>{const e=k(),t=e.crypto?.randomUUID;return("function"==typeof t?t.call(e.crypto):void 0)??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class Y{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??j;const t=new W({requestAdapter:e.requestAdapter,debug:e.debug,now:this.now,onFailure:t=>{e.onDiagnostic?.("DataReport transport failed",t)}}),o=e.send??((e,o)=>t.send(e,o));this.queue=new $({send:o,now:this.now,onDrop:t=>{e.onDiagnostic?.("DataReport event dropped",{reason:t})}})}get state(){return this.currentState}get queuedEventCount(){return this.queue.size}get serviceId(){return this.session?.serviceId}startSession(e){this.queue.clear(),this.currentState="unknown";const t=this.randomId();return this.session={...e,sessionId:`session_${t}`,serviceId:`sid_${t}`},this.enqueue(9674,{did:e.did??"",os:e.os??e.platform,sdkVersion:e.sdkVersion,deviceId:e.deviceId??""}),this.session.serviceId}updateSession(e){this.session&&(e.appKey&&e.appKey!==this.session.appKey&&this.queue.updateAppKey(this.session.appKey,e.appKey),this.session={...this.session,...e})}updateNetworkType(e){this.networkType=(e=>"number"==typeof e&&Number.isFinite(e)?e:"string"!=typeof e?-1:z[e.trim().toLowerCase()]??-1)(e)}applyDnsSwitch(e){if(this.session){if("true"===e)return this.currentState="enabled",void this.queue.enable();this.currentState="disabled",this.queue.clear()}else this.currentState="disabled"}startOperation(e){const t=this.session?.sessionId;if(!t||"disabled"===this.currentState)return this.createNoopOperation();const o=`opr_${this.randomId()}`,r=this.now();let s=!1,i=!1,n=`req_${this.randomId()}`,a=0,p="";const E=()=>!s&&!i&&this.session?.sessionId===t,c=(t,r,s,i,n)=>{E()&&(a=n.success?0:n.code,p=n.success?"":n.description??"",this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:o,requestid:r,operationName:e.operationName,operationType:e.operationType,requestName:t.requestName??e.operationName,subrequestid:String(s),requestMethod:t.method??"",requestUrl:t.url??"",requestElapse:Math.max(0,this.now()-i),code:n.code,codeDesc:n.description??"",isLastApi:0,isSuccess:n.success?1:0,accessChannel:this.session?.accessChannel??q,msgId:e.msgId,messageType:e.messageType,resultCount:n.resultCount}))},T=(e,t,o,r)=>{const s=this.now();let i=!1;return{retry:()=>(r.next+=1,T(e,t,r.next,r)),finish:r=>{i||(i=!0,c(e,t,o,s,r))}}};return{startRequest:(e={})=>(n=`req_${this.randomId()}`,T(e,n,1,{next:1})),finish:t=>{E()&&(s=!0,this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:o,requestid:n,operationName:e.operationName,operationType:e.operationType,requestName:"",subrequestid:"0",requestMethod:"",requestUrl:"",requestElapse:Math.max(0,this.now()-r),code:t.success?0:t.code??a,codeDesc:t.success?"":t.description??p,isLastApi:1,isSuccess:t.success?1:0,accessChannel:this.session?.accessChannel??q,msgId:e.msgId,messageType:e.messageType,resultCount:t.resultCount}))},discard:()=>{i=!0}}}reset(){this.currentState="disabled",this.session=void 0,this.queue.clear()}enqueue(e,t){const o=this.session;if(!o||"disabled"===this.currentState)return;const r={lts:this.now(),net:this.networkType,appkey:o.appKey,sdkServiceId:o.serviceId,sdkProduct:0,uikitVersion:o.uikitVersion??"",...t},s={eventId:e,body:Object.fromEntries(Object.entries(r).filter(([,e])=>void 0!==e))};this.queue.enqueue({appKey:o.appKey,wire:s})}createNoopOperation(){const e={retry:()=>e,finish:()=>{}};return{startRequest:()=>e,finish:()=>{},discard:()=>{}}}}let X;const J=e=>{if("disabled"!==X?.state)return X?.startOperation(e)},Q=(e,t)=>{if(!e.matchField)return!1;const o=t[e.matchField];return void 0!==e.matchPattern?"string"==typeof o&&o.includes(e.matchPattern):void 0===e.matchValue?void 0!==o:o===e.matchValue||!("string"!=typeof o&&"number"!=typeof o||"string"!=typeof e.matchValue&&"number"!=typeof e.matchValue)&&String(o)===String(e.matchValue)};function Z(t){const o=t.entry?.code??e.REST_BUSINESS_UNKNOWN,r=t.message??function(e){const t=e.apiName?`${e.apiName} failed`:"request failed";if(e.entry?.runtimeMessage)return`REST business error: ${e.entry.runtimeMessage}`;if(e.mapped??Boolean(e.entry)){if(e.reasonKey){const t=e.reasonKey.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split("_").join(" ").split("-").join(" ").toLowerCase();return`REST business error: ${t.charAt(0).toUpperCase()}${t.slice(1)}`}return`REST business error: ${t}`}return e.reasonKey?`REST business error: ${t} (${e.reasonKey})`:`REST business error: ${t}`}({apiName:t.apiName,entry:t.entry,mapped:t.mapped,reasonKey:t.reasonKey});return new p(r,{code:o,details:{api:t.apiName,serverCode:t.serverCode,serverMessage:t.serverMessage,httpStatus:t.httpStatus,mapped:t.mapped??Boolean(t.entry),reasonKey:t.reasonKey,matchedBy:t.matchedBy,retryable:t.entry?.retryable,canonicalCode:t.entry?.canonicalCode??t.entry?.code}})}const ee={getHistoryMessages:{operationName:"REST_GET_HISTORY_MESSAGE",operationType:"REST"},removeHistoryMessages:{operationName:"REST_DELETE_MESSAGES_CONVERSATIONS",operationType:"REST"},searchMessages:{operationName:"REST_SEARCH_MESSAGES",operationType:"REST"},addContact:{operationName:"ROSTER_ADD",operationType:"ROSTER"},deleteContact:{operationName:"ROSTER_REMOVE",operationType:"ROSTER"},acceptContactInvite:{operationName:"ROSTER_ACCEPT",operationType:"ROSTER"},declineContactInvite:{operationName:"ROSTER_DECLINE",operationType:"ROSTER"},addUsersToBlocklist:{operationName:"ROSTER_BAN",operationType:"ROSTER"},removeUserFromBlocklist:{operationName:"ROSTER_ALLOW",operationType:"ROSTER"},getBlocklist:{operationName:"ROSTER_BLACKLIST",operationType:"ROSTER"},getContactList:{operationName:"ROSTER_CONTACTS",operationType:"ROSTER"},setContactRemark:{operationName:"ROSTER_SET_CONTACT_REMARK",operationType:"ROSTER"},updateOwnInfo:{operationName:"USER_UPDATE_USERINFO",operationType:"USER"},getUserInfoByUserId:{operationName:"USER_FETCH_USERINFO",operationType:"USER"},uploadPushToken:{operationName:"USER_UPLOAD_PUSH_TOKEN",operationType:"USER"},createGroup:{operationName:"GROUP_CREATEGROUP",operationType:"GROUP"},destroyGroup:{operationName:"GROUP_DESTOTYGROUP",operationType:"GROUP"},leaveGroup:{operationName:"GROUP_LEAVEGROUP",operationType:"GROUP"},joinGroup:{operationName:"GROUP_JOIN_PUBLICGROUP",operationType:"GROUP"},getGroupMemberList:{operationName:"GROUP_FETCH_MEMEBERS",operationType:"GROUP"},uploadGroupSharedFile:{operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"},downloadGroupSharedFile:{operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"},getChatRoomList:{operationName:"CHATROOM_FETCH_CHATROOMSWITHPAGE",operationType:"CHATROOM"},getChatRoomInfo:{operationName:"CHATROOM_FETCH_SPECIFICATION",operationType:"CHATROOM"},joinChatRoom:{operationName:"CHATROOM_JOINCAHTROOM",operationType:"CHATROOM"},leaveChatRoom:{operationName:"CHATROOM_LEAVECAHTROOM",operationType:"CHATROOM"},getConversationList:{operationName:"REST_GET_SESSION_LIST",operationType:"REST"},deleteConversation:{operationName:"REST_DEL_SESSION",operationType:"REST"},setConversationPinned:{operationName:"REST_PIN_CONVERSATION",operationType:"REST"},getPinnedMessageList:{operationName:"REST_FETCH_PINMESSAGES",operationType:"REST"},clearAllMessagesAndConversations:{operationName:"REST_DELETE_MESSAGES_CONVERSATIONS",operationType:"REST"},setPinned:{operationName:"REST_PIN_MESSAGE",operationType:"REST"},getSelfIdsOnOtherPlatform:{operationName:"USER_LOGGEDIN_OTHER_PLATFORM",operationType:"USER"},getJoinedGroupList:{operationName:"GROUP_FETCH_USERS_GROUP",operationType:"GROUP"},changeGroupOwner:{operationName:"GROUP_CHANGE_OWNER",operationType:"GROUP"},getGroupInfo:{operationName:"GROUP_FETCH_SPECIFICATION",operationType:"GROUP"},getGroupInfoList:{operationName:"GROUP_FETCH_SPECIFICATION",operationType:"GROUP"},updateGroupInfo:{operationName:"GROUP_CHANGE_GROUPATTRIBUTE",operationType:"GROUP"},getGroupAdminList:{operationName:"GROUP_GET_ADMIN",operationType:"GROUP"},addGroupAdmin:{operationName:"GROUP_SET_ADMIN",operationType:"GROUP"},removeGroupAdmin:{operationName:"GROUP_REMOVE_ADMIN",operationType:"GROUP"},inviteUsersToGroup:{operationName:"GROUP_INVITE_TO_GROUP",operationType:"GROUP"},acceptGroupJoinRequest:{operationName:"GROUP_ACCEPT_JOINPUBLICGROUPAPPL",operationType:"GROUP"},rejectGroupJoinRequest:{operationName:"GROUP_DECLINE_JOINPUBLICGROUPAPPL",operationType:"GROUP"},acceptInvitation:{operationName:"GROUP_ACCEPT_INVITATION",operationType:"GROUP"},rejectInvitation:{operationName:"GROUP_DECLINE_INVITATION",operationType:"GROUP"},removeGroupMembers:{operationName:"GROUP_REMOVE_MEMBERS",operationType:"GROUP"},muteGroupMembers:{operationName:"GROUP_MUTE_MEMBERS",operationType:"GROUP"},unmuteGroupMembers:{operationName:"GROUP_UNMUTE_MEMBERS",operationType:"GROUP"},getGroupMuteList:{operationName:"GROUP_FETCH_MUTES",operationType:"GROUP"},blockGroupMembers:{operationName:"GROUP_BLOCK_MEMBERS",operationType:"GROUP"},unblockGroupMembers:{operationName:"GROUP_UNBLOCK_MEMBERS",operationType:"GROUP"},getGroupBlocklist:{operationName:"GROUP_GET_BLOCK_LIST",operationType:"GROUP"},muteAllGroupMembers:{operationName:"GROUP_MUTE_ALLMEMBERS",operationType:"GROUP"},unmuteAllGroupMembers:{operationName:"GROUP_UNMUTE_ALLMEMBERS",operationType:"GROUP"},addUsersToGroupAllowlist:{operationName:"GROUP_ADD_WHITELIST",operationType:"GROUP"},removeUsersFromGroupAllowlist:{operationName:"GROUP_REMOVE_WHITELIST",operationType:"GROUP"},getGroupAllowlist:{operationName:"GROUP_FETCH_WHITELIST",operationType:"GROUP"},checkIfInGroupAllowList:{operationName:"GROUP_IS_IN_WHITELIST",operationType:"GROUP"},getGroupMessageReadUsers:{operationName:"GROUP_GET_READ_USERS",operationType:"GROUP"},getGroupAnnouncement:{operationName:"GROUP_FETCH_ANNOUNCEMENT",operationType:"GROUP"},updateGroupAnnouncement:{operationName:"GROUP_UPDATE_ANNOUNCEMENT",operationType:"GROUP"},deleteGroupSharedFile:{operationName:"GROUP_DELETE_SHAREDFILE",operationType:"GROUP"},getGroupSharedFileList:{operationName:"GROUP_FETCH_SHAREDFILE",operationType:"GROUP"},setGroupMemberAttributes:{operationName:"GROUP_MEMBER_SET_META_DATA",operationType:"GROUP"},getGroupMembersAttributes:{operationName:"GROUP_MEMBER_FETCH_META_DATA",operationType:"GROUP"},destroyChatRoom:{operationName:"CHATROOM_DESTORYCHATROOM",operationType:"CHATROOM"},updateChatRoomInfo:{operationName:"CHATROOM_CHANGE_ATTRIBUTE",operationType:"CHATROOM"},removeChatRoomMembers:{operationName:"CHATROOM_REMOVE_MEMBERS",operationType:"CHATROOM"},addChatRoomMembers:{operationName:"CHATROOM_ADD_MEMBERS",operationType:"CHATROOM"},getChatRoomMemberList:{operationName:"CHATROOM_FETCH_MEMBERS",operationType:"CHATROOM"},getChatRoomAdminList:{operationName:"CHATROOM_GET_ADMIN",operationType:"CHATROOM"},setChatRoomAdmin:{operationName:"CHATROOM_SET_ADMIN",operationType:"CHATROOM"},removeChatRoomAdmin:{operationName:"CHATROOM_REMOVE_ADMIN",operationType:"CHATROOM"},muteChatRoomMembers:{operationName:"CHATROOM_MUTE_USER",operationType:"CHATROOM"},unmuteChatRoomMembers:{operationName:"CHATROOM_UNMUTE_USER",operationType:"CHATROOM"},getChatRoomMuteList:{operationName:"CHATROOM_FETCH_MUTES",operationType:"CHATROOM"},blockChatRoomMembers:{operationName:"CHATROOM_BLOCK_USERS",operationType:"CHATROOM"},unblockChatRoomMembers:{operationName:"CHATROOM_UNBLOCK_USERS",operationType:"CHATROOM"},getChatRoomBlocklist:{operationName:"CHATROOM_FETCH_BANS",operationType:"CHATROOM"},muteAllChatRoomMembers:{operationName:"CHATROOM_MUTE_ALLMEMEBERS",operationType:"CHATROOM"},unmuteAllChatRoomMembers:{operationName:"CHATROOM_UNMUTE_ALLMEMEBERS",operationType:"CHATROOM"},addUsersToChatRoomAllowlist:{operationName:"CHATROOM_ADD_WHITELIST",operationType:"CHATROOM"},removeUsersFromChatRoomAllowlist:{operationName:"CHATROOM_REMOVE_WHITELIST",operationType:"CHATROOM"},getChatRoomAllowlist:{operationName:"CHATROOM_FETCH_WHITELIST",operationType:"CHATROOM"},checkIfInChatRoomAllowList:{operationName:"CHATROOM_FETCH_MEMBERIN_WHITELIST",operationType:"CHATROOM"},getChatRoomAnnouncement:{operationName:"CHATROOM_FETCH_ANNOUNCEMENT",operationType:"CHATROOM"},updateChatRoomAnnouncement:{operationName:"CHATROOM_UPDATE_ANNOUNCEMENT",operationType:"CHATROOM"},deleteChatRoomSharedFile:{operationName:"CHATROOM_REMOVE_SHARE_FILE",operationType:"CHATROOM"},getChatRoomSharedFileList:{operationName:"CHATROOM_GET_SHARE_FILE_LIST",operationType:"CHATROOM"},setChatRoomAttributes:{operationName:"CHATROOM_SET_META_DATA",operationType:"CHATROOM"},removeChatRoomAttributes:{operationName:"CHATROOM_DELETE_META_DATA",operationType:"CHATROOM"},getChatRoomAttributes:{operationName:"CHATROOM_FETCH_META_DATA",operationType:"CHATROOM"}},te=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase(),oe=e=>{if(Array.isArray(e))return e.length;if(!e||"object"!=typeof e)return;const t=e;for(const o of["entities","data","items","messages","conversations","results"]){const e=t[o];if(Array.isArray(e))return e.length}};exports.AuthenticationError=i,exports.COMMON_ERROR_MAP={common:{validation:{range:"100-110",errors:{MISSING_REQUIRED:{code:110},INVALID_FORMAT:{code:110},UNKNOWN:{code:110}}},auth:{range:"108,200-215",errors:{ALREADY_LOGIN:{code:200},NOT_LOGIN:{code:201},UNAUTHORIZED:{code:202},FORBIDDEN:{code:210},TOKEN_EXPIRED:{code:108},BIND_ANOTHER_DEVICE:{code:213},LOGIN_TOO_MANY_DEVICES:{code:214},USER_MUTED:{code:215}}},connection:{range:"1,100,202,300-304",errors:{TIMEOUT:{code:301},WEBSOCKET_ERROR:{code:300},NOT_CREATED:{code:1},CLOSED_BEFORE_READY:{code:300},CANCELLED:{code:1},PROVISION_TIMEOUT:{code:301},PROVISION_REJECTED:{code:202},PROVISION_CLOSED:{code:300},DNSLIST_FAILED:{code:304},SERVER_BUSY:{code:302}}},storage:{range:"3",errors:{OPERATION_FAILED:{code:3}}},message:{range:"1,300-511",errors:{NOT_CONNECTED:{code:300},ACK_TIMEOUT:{code:301},SEND_FAILED:{code:303},SENDER_DESTROYED:{code:1},ENCODE_FAILED:{code:500},DECODE_FAILED:{code:500},ACK_MISSING:{code:301}}},transport:{range:"2,301,303",errors:{NETWORK_ERROR:{code:2},TIMEOUT:{code:301},HTTP_ERROR:{code:303},BUSINESS_UNKNOWN:{code:303}}},upload:{range:"1,100,110,301,402,405",errors:{REQUIRED_FIELD_MISSING:{code:110},INVALID_APPKEY:{code:100},SIZE_EXCEEDED:{code:405},REQUEST_FAILED:{code:402},TIMEOUT:{code:301},ABORTED:{code:1}}},unknown:{range:"1,4",errors:{UNKNOWN:{code:1},SERVICE_LIMIT_EXCEEDED:{code:4}}},push:{range:"1500,1501,1502",errors:{TOKEN_UPLOAD_FAILED:{code:1500},SILENT_MODE_OPERATION_FAILED:{code:1501},PUSH_LANGUAGE_OPERATION_FAILED:{code:1502}}},chatroom:{range:"700-707",errors:{CHATROOM_INVALID_ID:{code:700},CHATROOM_NOT_JOINED:{code:702},CHATROOM_PERMISSION_DENIED:{code:703},CHATROOM_MEMBERS_FULL:{code:704},CHATROOM_NOT_EXIST:{code:705},CHATROOM_OWNER_NOT_ALLOW_LEAVE:{code:706},CHATROOM_USER_IN_BLOCKLIST:{code:707}}}},apis:{}},exports.CONNECT_TIMEOUT=1e4,exports.ConnectionError=class extends s{constructor(t,o){super(t,o?.code??e.CONNECTION_WEBSOCKET_ERROR,o),this.name="ConnectionError"}},exports.DATA_REPORT_CORRELATION_LIMIT=1e3,exports.DEFAULT_PART_SIZE=5242880,exports.ERROR_CODES=e,exports.GROUP_NAMECARD_HYDRATION_BATCH_SIZE=50,exports.GROUP_NAMECARD_HYDRATION_MAX_CONCURRENCY=5,exports.GROUP_NAMECARD_HYDRATION_MIN_WINDOW_MS=1e3,exports.GROUP_NAMECARD_HYDRATION_WINDOW_MS=7e3,exports.GROUP_SHARED_FILE_DOWNLOAD_TIMEOUT=6e4,exports.GROUP_SHARED_FILE_UPLOAD_TIMEOUT=3e5,exports.HEARTBEAT_INTERVAL=3e4,exports.HEARTBEAT_TIMEOUT=6e4,exports.IMAGE_TYPE_ORIGINAL=A,exports.MAX_POOL=4,exports.MESSAGE_TIMEOUT=15e3,exports.MULTIPART_THRESHOLD=5242880,exports.MessageReceiveError=class extends s{constructor(t,o){super(t,o?.code??e.MESSAGE_DECODE_FAILED,o),this.name="MessageReceiveError"}},exports.MessageSendError=class extends s{constructor(t,o){super(t,o?.code??e.MESSAGE_SEND_FAILED,o),this.name="MessageSendError"}},exports.NetworkError=class extends s{constructor(t,o){super(t,o?.code??e.REST_NETWORK_ERROR,o),this.name="NetworkError"}},exports.PROVISION_TIMEOUT=1e4,exports.RECONNECT_BACKOFF_MULTIPLIER=2,exports.RECONNECT_INITIAL_DELAY=1e3,exports.RECONNECT_MAX_DELAY=6e4,exports.REQUEST_ID_HEADER=V,exports.RestBusinessError=p,exports.RestClient=class{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=t?.requestAdapter,this.includeRequestId=t?.includeRequestId??!1,this.defaultHeaders={Accept:"application/json",...t?.headers}}sanitizeUrl(e){try{const t=new URL(e),o=t.searchParams;for(const e of o.keys())o.set(e,"***");const r=o.toString(),s=r?`?${r}`:"";return`${t.origin}${t.pathname}${s}`}catch{return e.split("?")[0]??e}}setAuthToken(e){this.defaultHeaders.Authorization=`Bearer ${e}`}removeAuthToken(){delete this.defaultHeaders.Authorization}buildHttpStatusFallbackError(t,o,r,s){const a={...o.operation?{api:o.operation}:{},url:o.url,method:o.method,httpStatus:t,serverCode:r,serverMessage:s,mapped:!1};if(400===t)return new n("Invalid request parameters",{code:e.VALIDATION_UNKNOWN,details:{...a,canonicalCode:e.VALIDATION_UNKNOWN}});if(401===t){const t=[r,s].some(e=>"string"==typeof e&&/token[ _-]?(?:has[ _-]?)?expired/i.test(e)),o=t?e.AUTH_TOKEN_EXPIRED:e.AUTH_UNAUTHORIZED;return new i(t?"Authentication token expired":"Authentication failed",{code:o,details:{...a,reasonKey:t?"token_expired":"unauthorized",canonicalCode:o}})}return 403===t?new i("Access forbidden",{code:e.AUTH_FORBIDDEN,details:{...a,canonicalCode:e.AUTH_FORBIDDEN}}):429===t?new p("REST rate limit exceeded",{code:e.SERVICE_LIMIT_EXCEEDED,details:{...a,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:e.SERVICE_LIMIT_EXCEEDED}}):t>=500?new p("REST business error: request failed",{code:e.REST_BUSINESS_UNKNOWN,details:{...a,retryable:!0,reasonKey:"server_unknown_error",canonicalCode:e.REST_BUSINESS_UNKNOWN}}):void 0}async request(t,o={}){const r=`${this.baseUrl}${t}`,i=o.method??"GET",n=Date.now(),p=this.sanitizeUrl(r);F.debug("REST request",{method:i,url:p,operation:o.operation});const E=o.operation?(e=>{const t=ee[e];if(t)return t;const o=(e=>{const t=e.toLowerCase();return t.includes("chatroom")||t.includes("chat_room")?"CHATROOM":t.includes("group")?"GROUP":t.includes("contact")||t.includes("blocklist")?"ROSTER":t.includes("userinfo")||t.includes("presence")?"USER":"REST"})(e);return{operationName:`REST_${te(e)}`,operationType:o}})(o.operation):void 0,c=E?J(E):void 0,T=c?.startRequest({requestName:E?.operationName,method:i,url:r});let u=0;const _={...this.defaultHeaders,...o.headers};this.includeRequestId&&(_[V]=K());const O={method:i,headers:_};if(o.body&&"GET"!==i){const e=Object.keys(_).some(e=>"content-type"===e.toLowerCase());"string"==typeof o.body?(e||(_["Content-Type"]="application/x-www-form-urlencoded"),O.body=o.body):(e||(_["Content-Type"]="application/json"),O.body=JSON.stringify(o.body))}else if("GET"===i)for(const e of Object.keys(_))"content-type"===e.toLowerCase()&&delete _[e];try{if(this.requestAdapter){const e=await this.requestAdapter.request({url:r,method:i,headers:_,body:o.body,timeoutMs:o.timeout??this.timeout});u=e.status;const t=((e,t)=>{if("string"!=typeof e)return e;const o=Object.entries(t).find(([e])=>"content-type"===e.toLowerCase()),r=e.trim();if(!(o?.[1].includes("application/json")||r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]")))return e;try{return JSON.parse(r)}catch{return e}})(e.data,e.headers),s=Date.now()-n;(e.status<200||e.status>=300)&&(F.warn("REST response error",{method:i,url:p,status:e.status,duration:s}),this.handleErrorPayload(e.status,"",t,{operation:o.operation,url:r,method:i})),F.debug("REST response",{method:i,url:p,status:e.status,duration:s});const a=oe(t);return T?.finish({code:e.status,success:!0,resultCount:a}),c?.finish({code:0,success:!0,resultCount:a}),t}const e=new AbortController,t=setTimeout(()=>e.abort(),o.timeout??this.timeout),s=await fetch(r,{...O,signal:e.signal});u=s.status,clearTimeout(t);const a=Date.now()-n;s.ok||(F.warn("REST response error",{method:i,url:p,status:s.status,duration:a}),await this.handleErrorResponse(s,{operation:o.operation,url:r,method:i})),F.debug("REST response",{method:i,url:p,status:s.status,duration:a});const E=s.headers.get("content-type");if(E?.includes("application/json")){const e=await s.json(),t=oe(e);return T?.finish({code:s.status,success:!0,resultCount:t}),c?.finish({code:0,success:!0,resultCount:t}),e}const d=await s.text();return T?.finish({code:s.status,success:!0}),c?.finish({code:0,success:!0}),d}catch(d){const t=0!==u?u:d instanceof s?d.code:-1,n=d instanceof Error?d.message:String(d);if(T?.finish({code:t,success:!1,description:n}),c?.finish({code:t,success:!1,description:n}),d instanceof s)throw d;if(d instanceof Error&&"AbortError"===d.name)throw F.warn("REST request timeout",{method:i,url:p,timeout:o.timeout??this.timeout}),new a(`Request timeout: ${r}`,{code:e.REST_TIMEOUT,details:{url:r,method:i,timeout:o.timeout??this.timeout}});throw F.warn("REST request failed",{method:i,url:p}),new a(`Request failed: ${r}`,{code:e.REST_NETWORK_ERROR,details:{url:r,method:i}})}}async handleErrorResponse(e,t){let o;try{o=await e.json()}catch{o=await e.text()}this.handleErrorPayload(e.status,e.statusText,o,t)}handleErrorPayload(t,o,r,s){const i=r&&"object"==typeof r?r:{},n=((e,t)=>{if(!e.error||"object"!=typeof e.error||Array.isArray(e.error))return;const o=e.error,r=o.code;if("number"!=typeof r&&"string"!=typeof r)return;const s=String(r);return/^\d{7}$/.test(s)&&Number(s.slice(0,3))===t?o:void 0})(i,t),p=n?{...i,code:n.code,message:n.message}:r,E=function(e,t,o){if(!e)return;const r=o&&"object"==typeof o?o:{},s="string"==typeof r.error?r.error:void 0,i=(e=>"string"==typeof e.error_code||"number"==typeof e.error_code?e.error_code:"string"==typeof e.errorCode||"number"==typeof e.errorCode?e.errorCode:"string"==typeof e.error||"number"==typeof e.error?e.error:"string"==typeof e.code||"number"==typeof e.code?e.code:void 0)(r),n="string"==typeof r.error_description?r.error_description:"string"==typeof r.message?r.message:void 0,a=(e,t=!1)=>{const o=(e,o,r)=>({reasonKey:e,entry:o,matchedBy:t?"common":r});if(s&&e[s])return o(s,e[s],"key");for(const[s,i]of Object.entries(e))if(Q(i,r))return o(s,i,"field");if(void 0!==i)for(const[r,s]of Object.entries(e)){if(s.code===i||s.canonicalCode===i)return o(r,s,"code");if(Array.isArray(s.aliases)&&s.aliases.includes(String(i)))return o(r,s,"alias")}if(n)for(const[r,s]of Object.entries(e))if(Array.isArray(s.aliases)&&s.aliases.includes(n))return o(r,s,"alias")},p=t?e.apis[t]:void 0,E=p?a(p.errors):void 0;if(E)return E;for(const c of Object.values(e.common)){const e=a(c.errors,!0);if(e)return e}}(this.errorMap,s.operation,p),c="string"==typeof i.error?i.error:void 0,T="number"==typeof i.error_code||"string"==typeof i.error_code?i.error_code:"number"==typeof i.errorCode||"string"==typeof i.errorCode?i.errorCode:"number"==typeof i.code||"string"==typeof i.code?i.code:"string"==typeof i.error?i.error:"number"==typeof n?.code||"string"==typeof n?.code?n.code:void 0,u="string"==typeof i.message?i.message:"string"==typeof i.error_description?i.error_description:"string"==typeof n?.message?n.message:void 0,_=!!(401!==t&&403!==t||void 0!==c&&"unauthorized"!==c&&"auth_failed"!==c&&"forbidden"!==c)&&(void 0!==c||"string"==typeof i.error_description||"string"==typeof i.message);if(s.operation&&E)throw Z({apiName:s.operation,entry:E.entry,serverCode:T,serverMessage:u,httpStatus:t,mapped:!0,reasonKey:E.reasonKey,matchedBy:E.matchedBy});const O=this.buildHttpStatusFallbackError(t,s,T,u);if(O)throw O;if(s.operation&&_)throw Z({apiName:s.operation,serverCode:T,serverMessage:u,httpStatus:t,mapped:!1,reasonKey:c});throw new a(`HTTP ${t}: ${o}`,{code:e.REST_HTTP_ERROR,details:{url:s.url,method:s.method,httpStatus:t}})}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,o){return this.request(e,{...o,method:"POST",body:t})}put(e,t,o){return this.request(e,{...o,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}patch(e,t,o){return this.request(e,{...o,method:"PATCH",body:t})}},exports.RestTransportError=a,exports.SDKError=s,exports.SESSION_LIST_SYNC_OVERLAP_MS=2e4,exports.SYNC_WEBSOCKET_COMPLETE_CLOSE_DELAY=0,exports.SYNC_WEBSOCKET_CONNECT_TIMEOUT=5e3,exports.SYNC_WEBSOCKET_IDLE_TIMEOUT=1e4,exports.SYNC_WEBSOCKET_RETRY_BACKOFF_MULTIPLIER=2,exports.SYNC_WEBSOCKET_RETRY_INITIAL_DELAY=1e3,exports.SYNC_WEBSOCKET_RETRY_MAX_DELAY=5e3,exports.StorageError=class extends s{constructor(t,o){super(t,o?.code??e.STORAGE_OPERATION_FAILED,o),this.name="StorageError"}},exports.UPLOAD_TIMEOUT=3e5,exports.USER_INFO_HYDRATION_BATCH_SIZE=20,exports.USER_INFO_HYDRATION_MAX_CONCURRENCY=3,exports.USER_INFO_HYDRATION_MAX_RETRIES=1,exports.USER_INFO_HYDRATION_WINDOW_MS=7e3,exports.UploadError=E,exports.ValidationError=n,exports.appendAttachUrlParams=(e,t)=>{if(!e)return"";const o={};return e.includes("em-redirect")||(o["em-redirect"]="true"),t&&!e.includes("share-secret=")&&(o["share-secret"]=t),0===Object.keys(o).length?e:D(e,o)},exports.appendUrlQueryParams=D,exports.applyDataReportDnsSwitch=e=>{X?.applyDnsSwitch(e)},exports.buildAttachmentPrecheckDecision=e=>{const t=(o=e.messageType,r=e.imageType,"image"!==o?"attachment":r===A?"image-origin":"image-big");var o,r;const s=(e=>"image-origin"===e?204800:1048576)(t),i=e.fileSize>s;return{shouldPrecheck:i,thresholdType:t,thresholdBytes:s,actualBytes:e.fileSize,reason:i?"threshold-exceeded":"below-threshold"}},exports.buildUploadResult=t=>{const o=t.response.entities?.[0];if(!o?.uuid)throw new E("Upload response missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t.response}});const r=o["share-secret"],s=o["file-metadata"]??{},i="number"==typeof s["content-length"]?s["content-length"]:t.fallbackSize,n="string"==typeof s["content-type"]?s["content-type"]:t.fileType,a=`${t.restBaseUrl}/${t.orgName}/${t.appName}/chatfiles/${o.uuid}`;if("image"===t.messageType){const e=(t.imageType??I)===A;return{...M(a,{deriveVariants:!t.useCustomAttachmentUpload}),isOriginalImage:e,secret:r,fileLength:i,filetype:n,filename:t.fileName,width:t.width,height:t.height}}const p="video"===t.messageType?`${a}?vframe=true`:void 0;return{url:a,secret:r,fileLength:i,filetype:n,filename:t.fileName,thumbnailUrl:p}},exports.createRestBusinessError=Z,exports.createTraceId=K,exports.deriveImageUrls=M,exports.fromProtocolImageType=e=>2===e?I:A,exports.getRuntimeGlobal=k,exports.installDataReporter=e=>(X?.reset(),X=new Y(e),X),exports.isRemoteUrl=S,exports.isSDKError=function(e){if(e instanceof s)return!0;if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&"string"==typeof t.message&&"number"==typeof t.code&&"function"==typeof t.toJSON},exports.logger=F,exports.mergeRuntimeErrorMaps=(...e)=>{const t={},o={};for(const r of e)Object.assign(t,r.common),Object.assign(o,r.apis);return{common:t,apis:o}},exports.normalizeAttachmentFile=(t,o)=>{if(!t)throw new E("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"file missing"}});const r=("number"==typeof o.fileLength?o.fileLength:void 0)??("fileSize"in o&&"number"==typeof o.fileSize?o.fileSize:void 0),s=R({file:t,fallbackName:o.filename,fallbackMimeType:o.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new E("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"web file missing"}});return s},exports.normalizeUploadSource=R,exports.parseAppKey=f,exports.parseAttachmentPrecheckResult=t=>{const o=t.entities?.[0],r=!0===o?.exists,s="string"==typeof o?.uuid&&o.uuid.length>0?o.uuid:void 0,i=o,n=i?.["exists-type"]??i?.existsType,a="origin"===n?A:n===I||n===A?n:void 0,p="string"==typeof o?.["share-secret"]?o["share-secret"]:void 0;if(r&&!s)throw new E("Upload precheck response missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t}});return{uuid:s,exists:r,existsType:a,shareSecret:p,hit:(c={exists:r,uuid:s},c.exists&&"string"==typeof c.uuid&&c.uuid.length>0)};var c},exports.reportLogsNow=async function(){await g.reportNow()},exports.resetDataReporter=()=>{X?.reset(),X=void 0},exports.resolveImageSendPolicy=e=>e.isGif?{resolvedImageType:A,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:A,reason:"explicit-original"}:{resolvedImageType:I,reason:"default-large"},exports.sanitizeErrorDetails=r,exports.sanitizeErrorUrl=o,exports.setLogLevel=function(e){v instanceof B&&v.setLevel(e)},exports.setLogReportInterval=function(e){g.updateReportInterval(e)},exports.setLogReportState=function(e){g.setState(e)},exports.shouldUploadByUrl=(e,t)=>!!t||(!e||!S(e)),exports.startDataReportOperation=J,exports.startDataReportSession=e=>X?.startSession(e),exports.stopLogReporter=function(){g.stop()},exports.toProtocolImageType=e=>e===A?1:2,exports.toUploadChatType=e=>"singleChat"===e?m:"groupChat"===e?h:N,exports.toUploadImageType=e=>e===A?"origin":"large",exports.updateDataReportNetworkType=e=>{X?.updateNetworkType(e)},exports.updateDataReportSession=e=>{X?.updateSession(e)},exports.updateLogReportContext=function(e){g.updateContext(e)};