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.
- package/bundle/im-sdk-web.iife.js +1 -1
- package/cache/cache-manager.d.ts +3 -0
- package/cache/cache-store.d.ts +6 -4
- package/cache/cache-utils.d.ts +1 -1
- package/chunks/cache-utils-B99glc0H.js +1 -0
- package/chunks/cache-utils-gowrxNr8.cjs +1 -0
- package/chunks/chat-manager-5wHx7UeW.cjs +1 -0
- package/chunks/chat-manager-DdAnJpcH.js +2 -0
- package/chunks/common-BIpcR2uQ.cjs +1 -0
- package/chunks/common-BW2KLpvb.js +1 -0
- package/chunks/{group-user-info-resolver-FNRqDg18.js → group-user-info-resolver-Diqjmjyj.js} +1 -1
- package/chunks/{group-user-info-resolver-C5pdiqox.cjs → group-user-info-resolver-Ds35Z1Uf.cjs} +1 -1
- package/chunks/index-BItCF8E7.cjs +1 -0
- package/chunks/{index-uKWbjx-u.js → index-DKksD5YM.js} +1 -1
- package/chunks/{index-BKg4EGcI.cjs → index-DKmdsV1-.cjs} +1 -1
- package/chunks/index-VEUtqiDw.js +1 -0
- package/chunks/query-params-BHyPuD2k.cjs +1 -0
- package/chunks/query-params-Bu3Xq4b6.js +1 -0
- package/chunks/{session-list-query-B6dh-b4Y.cjs → session-list-query-C4OQMvPf.cjs} +1 -1
- package/chunks/{session-list-query-Dnp2HbpW.js → session-list-query-DtoToipt.js} +1 -1
- package/chunks/{user-info-BfRwS4ZA.js → user-info-22jZtcSi.js} +1 -1
- package/chunks/{user-info-icpL0Eaw.cjs → user-info-DsDDTJrw.cjs} +1 -1
- package/index.cjs +1 -1
- package/index.js +2 -2
- package/managers/chat/index.cjs +1 -1
- package/managers/chat/index.js +1 -1
- package/managers/chat-thread/index.cjs +1 -1
- package/managers/chat-thread/index.js +1 -1
- package/managers/chatroom/index.cjs +1 -1
- package/managers/chatroom/index.js +1 -1
- package/managers/contact/index.cjs +1 -1
- package/managers/contact/index.js +1 -1
- package/managers/group/index.cjs +1 -1
- package/managers/group/index.js +1 -1
- package/managers/presence/index.cjs +1 -1
- package/managers/presence/index.js +1 -1
- package/managers/push/index.cjs +1 -1
- package/managers/push/index.js +1 -1
- package/managers/user-info/index.cjs +1 -1
- package/managers/user-info/index.js +1 -1
- package/package.json +1 -1
- package/platform/env.d.ts +1 -0
- package/utils/query-params.d.ts +16 -0
- package/utils/runtime-global.d.ts +13 -0
- package/utils/storage-error.d.ts +8 -0
- package/chunks/cache-utils-BwRPIZ7n.js +0 -1
- package/chunks/cache-utils-CKbcYPlM.cjs +0 -1
- package/chunks/chat-manager-ChdK26ck.cjs +0 -1
- package/chunks/chat-manager-DH8a6Qj9.js +0 -2
- package/chunks/common-CfAlncj9.cjs +0 -1
- package/chunks/common-DN_g4O3n.js +0 -1
- package/chunks/index-CK3GHdGU.cjs +0 -1
- package/chunks/index-CjofwvEQ.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
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 a extends s{constructor(t,o){super(t,o?.code??e.VALIDATION_UNKNOWN,o),this.name="ValidationError"}}class n 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 T={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"},c=e=>"undefined"!=typeof Blob&&e instanceof Blob,_=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),o=t.length>0?t[t.length-1]:void 0;if(o)return o},u=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const o=e.slice(t+1).toLowerCase();return T[o]},O=(e,t)=>{for(const o of t){const t=e[o];if("string"==typeof t&&t.length>0)return t}},R=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),a=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:a.fileName,mimeType:a.fileType,size:a.fileSize},fileName:a.fileName,fileType:a.fileType,fileSize:a.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}),d=e=>{const{file:t,fallbackName:o,fallbackMimeType:r,fallbackSize:s}=e,i=(e=>{if(c(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(c(e))return e}})(t);if(i)return R({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=_(t.path),i=l({fileName:t.name??e,fileType:t.type??u(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=_(t.uri),i=l({fileName:t.name??e,fileType:t.type??u(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 a=l({fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"web-file",name:a.fileName,mimeType:a.fileType,size:a.fileSize},fileName:a.fileName,fileType:a.fileType,fileSize:a.fileSize}},N="CHAT",m="GROUP",h="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),a=i.split("&").filter(Boolean);return Object.entries(t).forEach(([e,t])=>{const o=encodeURIComponent(e),r=a.filter(t=>{const[r=""]=t.split("=",2);return r!==o&&y(r)!==e});a.length=0,a.push(...r),void 0!==t&&a.push(`${o}=${encodeURIComponent(String(t))}`)}),`${s}${a.length>0?`?${a.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:a}=this.context;if(!(t&&o&&r&&s&&a))return!1;let n="",p="";try{const e=f(o);n=e.orgName,p=e.appName}catch{return!1}const E=`${t}/${n}/${p}/sdk/users/${r}/client/logs`,T={resource:i??"webim",logContent:e};try{const e=await a.request({url:E,method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json"},body:T,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"]),G=e=>!!e&&P.has((e=>e.toLowerCase())(e)),b=(e,t,o)=>{const r=o??new WeakSet;if("string"==typeof e)return((e,t)=>G(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=>b(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))G(o)?t[o]=L:t[o]=b(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=>b(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,a=`[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${a}`,"color: rgb(0, 157, 255); font-weight: bold",t,...r):console.log(a,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=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,k="X-Request-Id",K="direct";class V{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 q{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 $={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},W=()=>{const e=globalThis.crypto?.randomUUID?.();return e??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class z{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??W;const t=new q({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 V({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:$[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,a=`req_${this.randomId()}`,n=0,p="";const E=()=>!s&&!i&&this.session?.sessionId===t,T=(t,r,s,i,a)=>{E()&&(n=a.success?0:a.code,p=a.success?"":a.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:a.code,codeDesc:a.description??"",isLastApi:0,isSuccess:a.success?1:0,accessChannel:this.session?.accessChannel??K,msgId:e.msgId,messageType:e.messageType,resultCount:a.resultCount}))},c=(e,t,o,r)=>{const s=this.now();let i=!1;return{retry:()=>(r.next+=1,c(e,t,r.next,r)),finish:r=>{i||(i=!0,T(e,t,o,s,r))}}};return{startRequest:(e={})=>(a=`req_${this.randomId()}`,c(e,a,1,{next:1})),finish:t=>{E()&&(s=!0,this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:o,requestid:a,operationName:e.operationName,operationType:e.operationType,requestName:"",subrequestid:"0",requestMethod:"",requestUrl:"",requestElapse:Math.max(0,this.now()-r),code:t.success?0:t.code??n,codeDesc:t.success?"":t.description??p,isLastApi:1,isSuccess:t.success?1:0,accessChannel:this.session?.accessChannel??K,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 Y;const j=e=>{if("disabled"!==Y?.state)return Y?.startOperation(e)},X=(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 J(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 Q={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"}},Z=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase(),ee=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=k,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 n={...o.operation?{api:o.operation}:{},url:o.url,method:o.method,httpStatus:t,serverCode:r,serverMessage:s,mapped:!1};if(400===t)return new a("Invalid request parameters",{code:e.VALIDATION_UNKNOWN,details:{...n,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:{...n,reasonKey:t?"token_expired":"unauthorized",canonicalCode:o}})}return 403===t?new i("Access forbidden",{code:e.AUTH_FORBIDDEN,details:{...n,canonicalCode:e.AUTH_FORBIDDEN}}):429===t?new p("REST rate limit exceeded",{code:e.SERVICE_LIMIT_EXCEEDED,details:{...n,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:{...n,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",a=Date.now(),p=this.sanitizeUrl(r);F.debug("REST request",{method:i,url:p,operation:o.operation});const E=o.operation?(e=>{const t=Q[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_${Z(e)}`,operationType:o}})(o.operation):void 0,T=E?j(E):void 0,c=T?.startRequest({requestName:E?.operationName,method:i,url:r});let _=0;const u={...this.defaultHeaders,...o.headers};this.includeRequestId&&(u[k]=x());const O={method:i,headers:u};if(o.body&&"GET"!==i){const e=Object.keys(u).some(e=>"content-type"===e.toLowerCase());"string"==typeof o.body?(e||(u["Content-Type"]="application/x-www-form-urlencoded"),O.body=o.body):(e||(u["Content-Type"]="application/json"),O.body=JSON.stringify(o.body))}else if("GET"===i)for(const e of Object.keys(u))"content-type"===e.toLowerCase()&&delete u[e];try{if(this.requestAdapter){const e=await this.requestAdapter.request({url:r,method:i,headers:u,body:o.body,timeoutMs:o.timeout??this.timeout});_=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()-a;(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 n=ee(t);return c?.finish({code:e.status,success:!0,resultCount:n}),T?.finish({code:0,success:!0,resultCount:n}),t}const e=new AbortController,t=setTimeout(()=>e.abort(),o.timeout??this.timeout),s=await fetch(r,{...O,signal:e.signal});_=s.status,clearTimeout(t);const n=Date.now()-a;s.ok||(F.warn("REST response error",{method:i,url:p,status:s.status,duration:n}),await this.handleErrorResponse(s,{operation:o.operation,url:r,method:i})),F.debug("REST response",{method:i,url:p,status:s.status,duration:n});const E=s.headers.get("content-type");if(E?.includes("application/json")){const e=await s.json(),t=ee(e);return c?.finish({code:s.status,success:!0,resultCount:t}),T?.finish({code:0,success:!0,resultCount:t}),e}const R=await s.text();return c?.finish({code:s.status,success:!0}),T?.finish({code:0,success:!0}),R}catch(R){const t=0!==_?_:R instanceof s?R.code:-1,a=R instanceof Error?R.message:String(R);if(c?.finish({code:t,success:!1,description:a}),T?.finish({code:t,success:!1,description:a}),R instanceof s)throw R;if(R instanceof Error&&"AbortError"===R.name)throw F.warn("REST request timeout",{method:i,url:p,timeout:o.timeout??this.timeout}),new n(`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 n(`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:{},a=((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=a?{...i,code:a.code,message:a.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),a="string"==typeof r.error_description?r.error_description:"string"==typeof r.message?r.message:void 0,n=(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(X(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(a)for(const[r,s]of Object.entries(e))if(Array.isArray(s.aliases)&&s.aliases.includes(a))return o(r,s,"alias")},p=t?e.apis[t]:void 0,E=p?n(p.errors):void 0;if(E)return E;for(const T of Object.values(e.common)){const e=n(T.errors,!0);if(e)return e}}(this.errorMap,s.operation,p),T="string"==typeof i.error?i.error:void 0,c="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 a?.code||"string"==typeof a?.code?a.code:void 0,_="string"==typeof i.message?i.message:"string"==typeof i.error_description?i.error_description:"string"==typeof a?.message?a.message:void 0,u=!!(401!==t&&403!==t||void 0!==T&&"unauthorized"!==T&&"auth_failed"!==T&&"forbidden"!==T)&&(void 0!==T||"string"==typeof i.error_description||"string"==typeof i.message);if(s.operation&&E)throw J({apiName:s.operation,entry:E.entry,serverCode:c,serverMessage:_,httpStatus:t,mapped:!0,reasonKey:E.reasonKey,matchedBy:E.matchedBy});const O=this.buildHttpStatusFallbackError(t,s,c,_);if(O)throw O;if(s.operation&&u)throw J({apiName:s.operation,serverCode:c,serverMessage:_,httpStatus:t,mapped:!1,reasonKey:T});throw new n(`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=n,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=a,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=>{Y?.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,a="string"==typeof s["content-type"]?s["content-type"]:t.fileType,n=`${t.restBaseUrl}/${t.orgName}/${t.appName}/chatfiles/${o.uuid}`;if("image"===t.messageType){const e=(t.imageType??I)===A;return{...M(n,{deriveVariants:!t.useCustomAttachmentUpload}),isOriginalImage:e,secret:r,fileLength:i,filetype:a,filename:t.fileName,width:t.width,height:t.height}}const p="video"===t.messageType?`${n}?vframe=true`:void 0;return{url:n,secret:r,fileLength:i,filetype:a,filename:t.fileName,thumbnailUrl:p}},exports.createRestBusinessError=J,exports.createTraceId=x,exports.deriveImageUrls=M,exports.fromProtocolImageType=e=>2===e?I:A,exports.installDataReporter=e=>(Y?.reset(),Y=new z(e),Y),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=d({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=d,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,a=i?.["exists-type"]??i?.existsType,n="origin"===a?A:a===I||a===A?a: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:n,shareSecret:p,hit:(T={exists:r,uuid:s},T.exists&&"string"==typeof T.uuid&&T.uuid.length>0)};var T},exports.reportLogsNow=async function(){await g.reportNow()},exports.resetDataReporter=()=>{Y?.reset(),Y=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=>Y?.startSession(e),exports.stopLogReporter=function(){g.stop()},exports.toProtocolImageType=e=>e===A?1:2,exports.toUploadChatType=e=>"singleChat"===e?N:"groupChat"===e?m:h,exports.toUploadImageType=e=>e===A?"origin":"large",exports.updateDataReportNetworkType=e=>{Y?.updateNetworkType(e)},exports.updateDataReportSession=e=>{Y?.updateSession(e)},exports.updateLogReportContext=function(e){g.updateContext(e)};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
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.REST_NETWORK_ERROR,o),this.name="NetworkError"}}class a extends s{constructor(t,o){super(t,o?.code??e.CONNECTION_WEBSOCKET_ERROR,o),this.name="ConnectionError"}}class n extends s{constructor(t,o){super(t,o?.code??e.AUTH_UNAUTHORIZED,o),this.name="AuthenticationError"}}class E extends s{constructor(t,o){super(t,o?.code??e.VALIDATION_UNKNOWN,o),this.name="ValidationError"}}class p extends s{constructor(t,o){super(t,o?.code??e.MESSAGE_SEND_FAILED,o),this.name="MessageSendError"}}class c extends s{constructor(t,o){super(t,o?.code??e.MESSAGE_DECODE_FAILED,o),this.name="MessageReceiveError"}}class T extends s{constructor(t,o){super(t,o?.code??e.STORAGE_OPERATION_FAILED,o),this.name="StorageError"}}class u extends s{constructor(t,o){super(t,o?.code??e.REST_NETWORK_ERROR,o),this.name="RestTransportError"}}class d extends s{constructor(t,o){super(t,o?.code??e.REST_BUSINESS_UNKNOWN,o),this.name="RestBusinessError"}}class _ extends s{constructor(t,o){super(t,o?.code??e.UPLOAD_REQUEST_FAILED,o),this.name="UploadError"}}function O(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}const l=15e3,R=3e5,h=6e4,m=3e5,N=1e4,S=1e4,A=3e4,I=6e4,f=1e3,C=6e4,y=2,D=5e3,M=1e4,U=1e3,g=5e3,L=2,b=0,G=2e4,P=7e3,H=20,w=3,v=1,B=7e3,F=1e3,k=50,K=5,V={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"},q=e=>"undefined"!=typeof Blob&&e instanceof Blob,$=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),o=t.length>0?t[t.length-1]:void 0;if(o)return o},z=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const o=e.slice(t+1).toLowerCase();return V[o]},x=(e,t)=>{for(const o of t){const t=e[o];if("string"==typeof t&&t.length>0)return t}},W=e=>{const t=e.file,o=e.sourceMeta,r=t.name||(o?x(o,["name","fileName","filename"]):void 0),s=e.file.type||(o?x(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),a=j({fileName:r,fileType:s,fileSize:i,fallbackName:e.fallbackName,fallbackMimeType:e.fallbackMimeType,fallbackSize:e.fallbackSize});return{source:{sourceType:"web-file",file:e.file,name:a.fileName,mimeType:a.fileType,size:a.fileSize},fileName:a.fileName,fileType:a.fileType,fileSize:a.fileSize,webFile:e.file}},j=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),Y=e=>{const{file:t,fallbackName:o,fallbackMimeType:r,fallbackSize:s}=e,i=(e=>{if(q(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(q(e))return e}})(t);if(i)return W({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=$(t.path),i=j({fileName:t.name??e,fileType:t.type??z(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=$(t.uri),i=j({fileName:t.name??e,fileType:t.type??z(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 a=j({fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"web-file",name:a.fileName,mimeType:a.fileType,size:a.fileSize},fileName:a.fileName,fileType:a.fileType,fileSize:a.fileSize}},X=5242880,J=5242880,Q=4,Z="CHAT",ee="GROUP",te="ROOM",oe="original",re="large",se=e=>/^https?:\/\//i.test(e),ie=(e,t)=>!!t||(!e||!se(e)),ae=t=>{const o=t.split("#");if(2!==o.length||!o[0]||!o[1])throw new _("Invalid appKey for upload",{code:e.UPLOAD_INVALID_APPKEY,details:{appKey:t}});return{orgName:o[0],appName:o[1]}},ne=e=>"singleChat"===e?Z:"groupChat"===e?ee:te,Ee=(e,t)=>ce(e,{size:t}),pe=e=>{try{return decodeURIComponent(e)}catch{return e}},ce=(e,t)=>{const[o="",r]=e.split("#",2),[s,i=""]=o.split("?",2),a=i.split("&").filter(Boolean);return Object.entries(t).forEach(([e,t])=>{const o=encodeURIComponent(e),r=a.filter(t=>{const[r=""]=t.split("=",2);return r!==o&&pe(r)!==e});a.length=0,a.push(...r),void 0!==t&&a.push(`${o}=${encodeURIComponent(String(t))}`)}),`${s}${a.length>0?`?${a.join("&")}`:""}${r?`#${r}`:""}`},Te=(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:ce(e,o)},ue=e=>e.isGif?{resolvedImageType:oe,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:oe,reason:"explicit-original"}:{resolvedImageType:re,reason:"default-large"},de=e=>{const t=(o=e.messageType,r=e.imageType,"image"!==o?"attachment":r===oe?"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"}},_e=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,a=i?.["exists-type"]??i?.existsType,n="origin"===a?oe:a===re||a===oe?a:void 0,E="string"==typeof o?.["share-secret"]?o["share-secret"]:void 0;if(r&&!s)throw new _("Upload precheck response missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t}});return{uuid:s,exists:r,existsType:n,shareSecret:E,hit:(p={exists:r,uuid:s},p.exists&&"string"==typeof p.uuid&&p.uuid.length>0)};var p},Oe=(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=pe(t),s=pe(o);return"size"!==r||!["big","large","thumbnail","small"].includes(s)}).join("&");return`${r}${i?`?${i}`:""}${o?`#${o}`:""}`})(e);return{originalImageUrl:o,bigImageUrl:Ee(o,"large"),thumbnailUrl:Ee(o,"small")}},le=e=>e===oe?"origin":"large",Re=e=>e===oe?1:2,he=e=>2===e?re:oe,me=t=>{const o=t.response.entities?.[0];if(!o?.uuid)throw new _("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,a="string"==typeof s["content-type"]?s["content-type"]:t.fileType,n=`${t.restBaseUrl}/${t.orgName}/${t.appName}/chatfiles/${o.uuid}`;if("image"===t.messageType){const e=(t.imageType??re)===oe;return{...Oe(n,{deriveVariants:!t.useCustomAttachmentUpload}),isOriginalImage:e,secret:r,fileLength:i,filetype:a,filename:t.fileName,width:t.width,height:t.height}}const E="video"===t.messageType?`${n}?vframe=true`:void 0;return{url:n,secret:r,fileLength:i,filetype:a,filename:t.fileName,thumbnailUrl:E}},Ne=(t,o)=>{if(!t)throw new _("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=Y({file:t,fallbackName:o.filename,fallbackMimeType:o.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new _("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"web file missing"}});return s},Se=e=>new Promise(t=>{setTimeout(t,e)});const Ae=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 Se(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:a}=this.context;if(!(t&&o&&r&&s&&a))return!1;let n="",E="";try{const e=ae(o);n=e.orgName,E=e.appName}catch{return!1}const p=`${t}/${n}/${E}/sdk/users/${r}/client/logs`,c={resource:i??"webim",logContent:e};try{const e=await a.request({url:p,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}}},Ie="[MASKED]",fe=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),Ce=e=>!!e&&fe.has((e=>e.toLowerCase())(e)),ye=(e,t,o)=>{const r=o??/* @__PURE__ */new WeakSet;if("string"==typeof e)return((e,t)=>Ce(t)?Ie: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=>ye(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))Ce(o)?t[o]=Ie:t[o]=ye(s,o,r);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},De="undefined"!=typeof document,Me={DEBUG:0,WARN:1,ERROR:2};class Ue{constructor(e="WARN"){this.level=e}setLevel(e){this.level=e}shouldLog(e){return Me[e]>=Me[this.level]}emit(e,t,o){const r=(e=>{const t=/* @__PURE__ */new WeakSet;return e.map(e=>ye(e,void 0,t))})(o),s=((e,t,o)=>({timestamp:/* @__PURE__ */(new Date).toISOString(),level:e,message:t,args:o}))(e,t,r);Ae.append(s);const i=/* @__PURE__ */new Date,a=`[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")}`}]`;De?console.log(`%c${a}`,"color: rgb(0, 157, 255); font-weight: bold",t,...r):console.log(a,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 ge=new Ue;function Le(e){ge instanceof Ue&&ge.setLevel(e)}function be(e){Ae.setState(e)}function Ge(e){Ae.updateContext(e)}function Pe(e){Ae.updateReportInterval(e)}async function He(){await Ae.reportNow()}function we(){Ae.stop()}const ve={debug:(e,...t)=>ge.debug(e,...t),warn:(e,...t)=>ge.warn(e,...t),error:(e,...t)=>ge.error(e,...t)},Be=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,Fe="X-Request-Id",ke=1e3,Ke="direct";class Ve{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 qe{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 $e={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},ze=()=>{const e=globalThis.crypto?.randomUUID?.();return e??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class xe{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??ze;const t=new qe({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 Ve({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:$e[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,a=`req_${this.randomId()}`,n=0,E="";const p=()=>!s&&!i&&this.session?.sessionId===t,c=(t,r,s,i,a)=>{p()&&(n=a.success?0:a.code,E=a.success?"":a.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:a.code,codeDesc:a.description??"",isLastApi:0,isSuccess:a.success?1:0,accessChannel:this.session?.accessChannel??Ke,msgId:e.msgId,messageType:e.messageType,resultCount:a.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={})=>(a=`req_${this.randomId()}`,T(e,a,1,{next:1})),finish:t=>{p()&&(s=!0,this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:o,requestid:a,operationName:e.operationName,operationType:e.operationType,requestName:"",subrequestid:"0",requestMethod:"",requestUrl:"",requestElapse:Math.max(0,this.now()-r),code:t.success?0:t.code??n,codeDesc:t.success?"":t.description??E,isLastApi:1,isSuccess:t.success?1:0,accessChannel:this.session?.accessChannel??Ke,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 We;const je=e=>(We?.reset(),We=new xe(e),We),Ye=e=>We?.startSession(e),Xe=e=>{We?.updateSession(e)},Je=e=>{We?.applyDnsSwitch(e)},Qe=e=>{We?.updateNetworkType(e)},Ze=e=>{if("disabled"!==We?.state)return We?.startOperation(e)},et=()=>{We?.reset(),We=void 0},tt=(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 ot(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 d(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 rt={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"}},st=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase(),it=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}};class at{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 i={...o.operation?{api:o.operation}:{},url:o.url,method:o.method,httpStatus:t,serverCode:r,serverMessage:s,mapped:!1};if(400===t)return new E("Invalid request parameters",{code:e.VALIDATION_UNKNOWN,details:{...i,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 n(t?"Authentication token expired":"Authentication failed",{code:o,details:{...i,reasonKey:t?"token_expired":"unauthorized",canonicalCode:o}})}return 403===t?new n("Access forbidden",{code:e.AUTH_FORBIDDEN,details:{...i,canonicalCode:e.AUTH_FORBIDDEN}}):429===t?new d("REST rate limit exceeded",{code:e.SERVICE_LIMIT_EXCEEDED,details:{...i,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:e.SERVICE_LIMIT_EXCEEDED}}):t>=500?new d("REST business error: request failed",{code:e.REST_BUSINESS_UNKNOWN,details:{...i,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",a=Date.now(),n=this.sanitizeUrl(r);ve.debug("REST request",{method:i,url:n,operation:o.operation});const E=o.operation?(e=>{const t=rt[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_${st(e)}`,operationType:o}})(o.operation):void 0,p=E?Ze(E):void 0,c=p?.startRequest({requestName:E?.operationName,method:i,url:r});let T=0;const d={...this.defaultHeaders,...o.headers};this.includeRequestId&&(d[Fe]=Be());const _={method:i,headers:d};if(o.body&&"GET"!==i){const e=Object.keys(d).some(e=>"content-type"===e.toLowerCase());"string"==typeof o.body?(e||(d["Content-Type"]="application/x-www-form-urlencoded"),_.body=o.body):(e||(d["Content-Type"]="application/json"),_.body=JSON.stringify(o.body))}else if("GET"===i)for(const e of Object.keys(d))"content-type"===e.toLowerCase()&&delete d[e];try{if(this.requestAdapter){const e=await this.requestAdapter.request({url:r,method:i,headers:d,body:o.body,timeoutMs:o.timeout??this.timeout});T=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()-a;(e.status<200||e.status>=300)&&(ve.warn("REST response error",{method:i,url:n,status:e.status,duration:s}),this.handleErrorPayload(e.status,"",t,{operation:o.operation,url:r,method:i})),ve.debug("REST response",{method:i,url:n,status:e.status,duration:s});const E=it(t);return c?.finish({code:e.status,success:!0,resultCount:E}),p?.finish({code:0,success:!0,resultCount:E}),t}const e=new AbortController,t=setTimeout(()=>e.abort(),o.timeout??this.timeout),s=await fetch(r,{..._,signal:e.signal});T=s.status,clearTimeout(t);const E=Date.now()-a;s.ok||(ve.warn("REST response error",{method:i,url:n,status:s.status,duration:E}),await this.handleErrorResponse(s,{operation:o.operation,url:r,method:i})),ve.debug("REST response",{method:i,url:n,status:s.status,duration:E});const u=s.headers.get("content-type");if(u?.includes("application/json")){const e=await s.json(),t=it(e);return c?.finish({code:s.status,success:!0,resultCount:t}),p?.finish({code:0,success:!0,resultCount:t}),e}const O=await s.text();return c?.finish({code:s.status,success:!0}),p?.finish({code:0,success:!0}),O}catch(O){const t=0!==T?T:O instanceof s?O.code:-1,a=O instanceof Error?O.message:String(O);if(c?.finish({code:t,success:!1,description:a}),p?.finish({code:t,success:!1,description:a}),O instanceof s)throw O;if(O instanceof Error&&"AbortError"===O.name)throw ve.warn("REST request timeout",{method:i,url:n,timeout:o.timeout??this.timeout}),new u(`Request timeout: ${r}`,{code:e.REST_TIMEOUT,details:{url:r,method:i,timeout:o.timeout??this.timeout}});throw ve.warn("REST request failed",{method:i,url:n}),new u(`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:{},a=((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),n=a?{...i,code:a.code,message:a.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),a="string"==typeof r.error_description?r.error_description:"string"==typeof r.message?r.message:void 0,n=(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(tt(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(a)for(const[r,s]of Object.entries(e))if(Array.isArray(s.aliases)&&s.aliases.includes(a))return o(r,s,"alias")},E=t?e.apis[t]:void 0,p=E?n(E.errors):void 0;if(p)return p;for(const c of Object.values(e.common)){const e=n(c.errors,!0);if(e)return e}}(this.errorMap,s.operation,n),p="string"==typeof i.error?i.error:void 0,c="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 a?.code||"string"==typeof a?.code?a.code:void 0,T="string"==typeof i.message?i.message:"string"==typeof i.error_description?i.error_description:"string"==typeof a?.message?a.message:void 0,d=!!(401!==t&&403!==t||void 0!==p&&"unauthorized"!==p&&"auth_failed"!==p&&"forbidden"!==p)&&(void 0!==p||"string"==typeof i.error_description||"string"==typeof i.message);if(s.operation&&E)throw ot({apiName:s.operation,entry:E.entry,serverCode:c,serverMessage:T,httpStatus:t,mapped:!0,reasonKey:E.reasonKey,matchedBy:E.matchedBy});const _=this.buildHttpStatusFallbackError(t,s,c,T);if(_)throw _;if(s.operation&&d)throw ot({apiName:s.operation,serverCode:c,serverMessage:T,httpStatus:t,mapped:!1,reasonKey:p});throw new u(`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})}}const nt=(...e)=>{const t={},o={};for(const r of e)Object.assign(t,r.common),Object.assign(o,r.apis);return{common:t,apis:o}},Et={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:{}};export{b as $,n as A,le as B,a as C,ke as D,e as E,me as F,R as G,A as H,oe as I,J,ne as K,ie as L,p as M,i as N,se as O,S as P,Ne as Q,d as R,s as S,ue as T,_ as U,E as V,de as W,_e as X,G as Y,T as Z,D as _,Te as a,M as a0,o as a1,g as a2,U as a3,L as a4,v as a5,w as a6,k as a7,F as a8,K as a9,B as aa,H as ab,P as ac,je as ad,Ye as ae,be as af,Je as ag,Ge as ah,Pe as ai,Xe as aj,He as ak,et as al,we as am,Qe as an,O as ao,Le as ap,m as aq,h as ar,Fe as b,ot as c,Oe as d,Be as e,at as f,u as g,Et as h,he as i,N as j,y as k,ve as l,nt as m,Y as n,C as o,ae as p,f as q,I as r,r as s,Re as t,Ze as u,c as v,l as w,X as x,Q as y,ce as z};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const e=require("./cache-utils-CKbcYPlM.cjs"),t=require("./common-CfAlncj9.cjs"),r=require("./profile-version-njNs7R5-.cjs"),o=require("./group-user-info-resolver-C5pdiqox.cjs"),s=require("./event-system-COBJFEIq.cjs"),n=require("./user-info-icpL0Eaw.cjs"),a=require("./reflection-proto-codec-BnQFQdZC.cjs"),i=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],u=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),p=e=>({userId:e}),d=(e,t,r)=>{const o={userId:r};for(const s of i){const r=t?.[s]??e?.[s];void 0!==r&&(o[s]=r)}return o},c=async(e,t)=>{const r=(e=>{const t=[],r=new Set;for(const o of e){const e=o.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),o=new Map;if(0===r.length)return o;const s=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const a of s)o.set(a.userId,u(a));const n=r.filter(e=>!o.has(e));if(n.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:n});for(const t of e)o.set(t.userId,t)}for(const a of r)o.has(a)||o.set(a,p(a));return o},m=t=>e.isRecord(t)?t:null,l=e=>{if("string"==typeof e)return e},h=e=>{const t=l(e)?.trim();return t||void 0},g=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isFinite(t)?t:void 0}},I=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},y=e=>{const t=m(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},f=e=>{const t=m(e);return t?m(t.data)?t.data:t:null},R=(e,t)=>{const r=m(e),o=r&&m(r.params),s=o?.[t];if(Array.isArray(s)&&0!==s.length)return g(s[0])},_=(e,t)=>{const r=(e=>{const t=m(e);return t?g(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},G=e=>h(e.groupId)??h(e.groupid)??h(e.id)??"",v=e=>l(e.name)??l(e.groupname)??l(e.groupName)??"",w=e=>{const t=y(e),r=m(t[0])??f(e)??{},o=(e=>{const t=m(e);if(!t)return null;const r=G(t);return r?{groupId:r,name:v(t),description:l(t.description),memberCount:g(t.memberCount)??g(t.affiliations_count),public:I(t.public),joinApprovalRequired:I(t.joinApprovalRequired)??I(t.approval)??I(t.membersonly)??I(t.members_only),allowInvites:I(t.allowInvites)??I(t.allowinvites)??I(t.allow_user_invites),maxMembers:g(t.maxMembers)??g(t.maxusers),role:h(t.role)??h(t.permission),disabled:I(t.disabled)}:null})(r)??{groupId:G(r),name:v(r)},s=h(r.owner)??h(r.admin)??h(r.member),n=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>m(e)).filter(e=>null!==e).map(e=>g(e.joined_time)).find(e=>void 0!==e);return{...o,owner:s?p(s):void 0,inviteNeedConfirm:I(r.inviteNeedConfirm)??I(r.invite_need_confirm),muteAllMembers:I(r.mute),ext:l(r.ext)??l(r.custom),createdAt:g(r.createdAt)??g(r.created),joinedAt:n,avatarUrl:l(r.avatar),messageBlocked:I(r.messageBlocked)??I(r.isMessageBlocked)??I(r.shieldgroup)}},S=e=>p(e),E=e=>y(e).map(e=>h(e)).filter(e=>Boolean(e)).map(e=>S(e)),b=e=>{const t=m(e);if(!t)return null;const r=h(t.fileId)??h(t.file_id);if(!r)return null;const o=l(t.fileName)??l(t.file_name)??r,s=h(t.fileOwner)??h(t.file_owner);return{fileId:r,fileName:o,fileOwner:s?S(s):void 0,fileSize:g(t.fileSize)??g(t.file_size),createdAt:g(t.createdAt)??g(t.created)}},C=100,A=3e3,U=e=>({...e}),O=e=>"object"==typeof e&&null!==e,D=e=>"DEFAULT"===e||"ALL"===e||"AT"===e||"NONE"===e?e:"mentionOnly"===e?"AT":"mute"===e?"NONE":"default"===e?"DEFAULT":2===e?"AT":3===e?"NONE":0===e?"DEFAULT":1===e?"ALL":void 0;class N{constructor(e,t){this.groupId=e,this.manager=t}getSummary(){return this.manager.getGroupSummaryForHandle(this.groupId)}getDetail(){return this.manager.getGroupDetailForHandle(this.groupId)}refresh(){return this.manager.refreshGroupDetailForHandle(this.groupId)}updateInfo(e){return this.manager.updateGroupInfo({groupId:this.groupId,...e})}updateConfigs(e){return this.manager.updateGroupInfo({groupId:this.groupId,...e})}changeOwner(e){return this.manager.changeGroupOwner({groupId:this.groupId,newOwner:e.newOwner})}destroy(){return this.manager.destroyGroup(this.toTarget())}leave(){return this.manager.leaveGroup(this.toTarget())}getMembers(e={}){return this.manager.getGroupMemberList({groupId:this.groupId,...e})}removeMembers(e){return this.manager.removeGroupMembers(this.toUserBatchParams(e))}getAdmins(){return this.manager.getGroupAdminList(this.toTarget())}addAdmin(e){return this.manager.addGroupAdmin({groupId:this.groupId,userId:e.userId})}removeAdmin(e){return this.manager.removeGroupAdmin({groupId:this.groupId,userId:e.userId})}getMuteList(e){return this.manager.getGroupMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteGroupMembers({groupId:this.groupId,userIds:e.userIds,muteDuration:e.muteDuration})}unmuteMembers(e){return this.manager.unmuteGroupMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllGroupMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllGroupMembers(this.toTarget())}getBlocklist(e){return this.manager.getGroupBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockGroupMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockGroupMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getGroupAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToGroupAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromGroupAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInGroupAllowList({groupId:this.groupId})}checkIfInMuteList(){return this.manager.checkIfInGroupMuteList(this.toTarget())}getAnnouncement(){return this.manager.getGroupAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateGroupAnnouncement({groupId:this.groupId,announcement:e.announcement})}getSharedFileList(e={}){return this.manager.getGroupSharedFileList({groupId:this.groupId,...e})}uploadSharedFile(e){return this.manager.uploadGroupSharedFile({groupId:this.groupId,...e})}deleteSharedFile(e){return this.manager.deleteGroupSharedFile({groupId:this.groupId,fileId:e.fileId})}downloadSharedFile(e){return this.manager.downloadGroupSharedFile({groupId:this.groupId,...e})}setMemberAttributes(e){return this.manager.setGroupMemberAttributes({groupId:this.groupId,userId:e.userId,memberAttributes:e.memberAttributes})}getMembersAttributes(e){return this.manager.getGroupMembersAttributes({groupId:this.groupId,userIds:e.userIds,keys:e.keys})}toTarget(){return{groupId:this.groupId}}toUserBatchParams(e){return{groupId:this.groupId,userIds:e.userIds}}}const T=e=>{const{orgName:r,appName:o}=t.parseAppKey(e.appKey);return{orgName:r,appName:o,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},M=e=>new t.ValidationError(`${e} is required`,{code:t.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),L=(e,r)=>new t.ValidationError(r,{code:t.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:r,rule:"invalid_format"}]}}),F=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw M(t);const r=[],o=new Set;if(e.forEach((e,s)=>{if("string"!=typeof e)throw L(`${t}[${s}]`,`${t}[${s}] must be a string`);const n=e.trim();n&&!o.has(n)&&(o.add(n),r.push(n))}),0===r.length)throw M(t);return r},P=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw M(t);return e.trim()},x=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw L(t,`${t} must be a string`);return e}},$=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw L(t,`${t} must be a boolean`);return e}},j=(e,t)=>`/${e.orgName}/${e.appName}${t}`,k=new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),q=e=>{const t=new URLSearchParams;"number"==typeof e?.pageNum&&t.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize));const r=t.toString();return r?`?${r}`:""},J=async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups?resource=${o.encodedResource}`);return(e=>{const t=y(e),r=m(t[0]),o=f(e)??r;return{groupId:o&&G(o)||r&&G(r)||""}})(await e.post(s,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?F(r.memberIds,"params.memberIds"):[],public:r.public,approval:r.joinApprovalRequired,allowinvites:r.allowInvites,invite_need_confirm:r.inviteNeedConfirm,maxusers:r.maxMembers,custom:r.ext,avatar:r.avatar},{operation:"createGroup"}))},B=async(e,t,r)=>{const o=T(t),s=P(r.groupId,"params.groupId"),n=j(o,`/chatgroups/${encodeURIComponent(s)}?joined_time=true&version=v3`),a=await e.get(n,{operation:"getGroupInfo"});return w(a)},K=async(e,t,r)=>{const o=T(t),s=P(r.groupId,"params.groupId"),n={},a=x(r.name,"params.name"),i=x(r.description,"params.description"),u=x(r.avatar,"params.avatar"),p=x(r.ext,"params.ext"),d=$(r.public,"params.public"),c=$(r.joinApprovalRequired,"params.joinApprovalRequired"),m=$(r.allowInvites,"params.allowInvites"),l=$(r.inviteNeedConfirm,"params.inviteNeedConfirm"),h=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw L(t,`${t} must be a number`);return e}})(r.maxMembers,"params.maxMembers");if(void 0!==a&&(n.groupname=a),void 0!==i&&(n.description=i),void 0!==u&&(n.avatar=u),void 0!==p&&(n.custom=p),void 0!==d&&(n.public=d),void 0!==c&&(n.membersonly=c),void 0!==m&&(n.allowinvites=m),void 0!==l&&(n.invite_need_confirm=l),void 0!==h&&(n.maxusers=h),0===Object.keys(n).length)throw M("params");const g=j(o,`/chatgroups/${encodeURIComponent(s)}?resource=${o.encodedResource}&version=v3`);await e.put(g,n,{operation:"updateGroupInfo"})},V=async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/users${(e=>{const t=new URLSearchParams;return"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor),t.set("version","v3"),`?${t.toString()}`})(r)}`);return(e=>{const t=[];for(const n of y(e)){const e=m(n);if(!e)continue;const r=h(e.owner),o=h(e.admin),s=h(e.member),a=r??o??s;if(!a)continue;const i=g(e.joinedAt)??g(e.joined_time);t.push({user:S(a),role:r?"owner":o?"admin":"member",...void 0===i?{}:{joinedAt:i}})}const r=R(e,"pagenum"),o=R(e,"pagesize"),s=_(e,o);return{items:t,pageNum:r,pageSize:o,...void 0===s?{}:{hasMore:s}}})(await e.get(s,{operation:"getGroupMemberList"}))},H=async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/admin`),n=await e.get(s,{operation:"getGroupAdminList"});return E(n)},z=async(e,t,r)=>{const o=T(t),s=P(r.groupId,"params.groupId"),n=q(r),a=n?"&":"",i=j(o,`/chatgroups/${encodeURIComponent(s)}/mute?version=v3${a}${n.replace("?","")}`);return(e=>{const t=[];for(const r of y(e)){const e=h(r);if(e){t.push({user:S(e)});continue}const o=m(r);if(!o)continue;const s=h(o.user);if(!s)continue;const n=g(o.expire);t.push({user:S(s),...void 0===n?{}:{muteExpire:n}})}return t})(await e.get(i,{operation:"getGroupMuteList"}))},W=async(e,t,r)=>{const o=T(t),s=P(r.groupId,"params.groupId"),n=q(r),a=n?"&":"",i=j(o,`/chatgroups/${encodeURIComponent(s)}/blocks/users?version=v3${a}${n.replace("?","")}`),u=await e.get(i,{operation:"getGroupBlocklist"});return E(u).map(e=>({user:e}))},Q=async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/white/users`),n=await e.get(s,{operation:"getGroupAllowlist"});return E(n).map(e=>({user:e}))},Y=async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=f(e)??{};return{announcement:l(t.announcement)??""}})(await e.get(s,{operation:"getGroupAnnouncement"}))},X=async(e,t,r)=>{const o=T(t),s=new URLSearchParams;s.set("pagenum",String(r.pageNum??1)),s.set("pagesize",String(r.pageSize??20));const n=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/share_files?${s.toString()}`);return(e=>{const t=R(e,"pagenum"),r=R(e,"pagesize"),o=_(e,r);return{items:y(e).map(e=>b(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===o?{}:{hasMore:o}}})(await e.get(n,{operation:"getGroupSharedFileList"}))},Z=(e,t)=>{const r=T(e);return j(r,`/chatgroups/${encodeURIComponent(P(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(P(t.fileId,"params.fileId"))}`)},ee=async(e,t,r)=>{const o=T(t),s=P(r.groupId,"params.groupId"),n=P(r.userId,"params.userId"),a=((e,t,r)=>{if(t!==e.userId)return null;const o=Object.entries(r);if(0===o.length)return null;let s;for(const[n,a]of o){if(!k.has(n)||"string"!=typeof a)return null;if(void 0!==s){if(s!==a)return null}else s=a}return void 0===s?null:{nameCard:s}})(t,n,r.memberAttributes);if(a){const t=j(o,`/sdk/chatgroups/${encodeURIComponent(s)}/nameCard`);return await e.put(t,a,{operation:"setGroupMemberAttributes"})}const i=j(o,`/sdk/metadata/chatgroup/${encodeURIComponent(s)}/user/${encodeURIComponent(n)}?resource=${o.encodedResource}`);return await e.put(i,{metaData:r.memberAttributes},{operation:"setGroupMemberAttributes"})},te=async(e,t,r)=>{const o=T(t),s=j(o,`/sdk/metadata/chatgroup/${encodeURIComponent(P(r.groupId,"params.groupId"))}/get`);return(e=>{const t=f(e)??{},r=m(t.data)??t,o={};for(const[s,n]of Object.entries(r)){const e=m(n);e&&(o[s]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:o}})(await e.post(s,{targets:F(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},re=t=>{const r=e.isRecord(t)?t:{},o=r.data,s=e.isRecord(o)?o.data:void 0,n=Array.isArray(o)?o:Array.isArray(s)?s:null;if(Array.isArray(n))return oe(n);const a=e.isRecord(o)?o:r,i=e.isRecord(a.namecards)?a.namecards:a,u={};for(const[p,d]of Object.entries(i)){if("string"==typeof d){u[p]={namecard:d};continue}if(!e.isRecord(d))continue;const t=d.namecard??d.nameCard??d.groupNamecard??d.group_namecard??d.group_name_card;"string"==typeof t&&(u[p]={namecard:t,namecardUpdateTime:se(d)})}return u},oe=t=>{const r={};return t.forEach(t=>{if(!e.isRecord(t))return;const o=t.username??t.userId??t.userid??t.user_id,s=t.name_card??t.namecard??t.nameCard??t.groupNamecard??t.group_namecard??t.group_name_card;"string"==typeof o&&o.trim()&&"string"==typeof s&&(r[o.trim()]={namecard:s,namecardUpdateTime:se(t)})}),r},se=e=>r.normalizeProfileVersionFromTimestamp("number"==typeof e.update_timestamp?e.update_timestamp:"number"==typeof e.updateTimestamp?e.updateTimestamp:"number"==typeof e.timestamp?e.timestamp:"number"==typeof e.lastModified?e.lastModified:"number"==typeof e.last_modified?e.last_modified:void 0),ne=t=>{if(e.isRecord(t))return r.normalizeProfileVersionFromTimestamp("number"==typeof t.timestamp?t.timestamp:"number"==typeof t.update_timestamp?t.update_timestamp:"number"==typeof t.updateTimestamp?t.updateTimestamp:"number"==typeof t.lastModified?t.lastModified:"number"==typeof t.last_modified?t.last_modified:void 0)};class ae{constructor(e){this.repository=e}applyPatch(e){e.shouldMarkStale&&this.repository.markStale(e.groupId);const t=this.repository.getDetailSnapshot(e.groupId);if(!e.groupPatch)return t;const r=t??{groupId:e.groupId,name:e.groupPatch.name??e.groupName??""};return this.repository.mergeDetail({...r,...e.groupPatch,groupId:e.groupId})}}const ie=e=>({...e}),ue=e=>({...e,owner:e.owner?{...e.owner}:void 0});class pe{constructor(e){this.summarySnapshot=null,this.detailSnapshot=null,this.loadedSummary=!1,this.stale=!1,this.loadedDetail=!1,this.lastPatchedAt=null,this.lastHydratedAt=null,this.groupId=e}mergeSummary(e){e.groupId===this.groupId&&(this.summarySnapshot=ie({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=ue({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=ie(this.toSummaryFromDetail(this.detailSnapshot)),this.loadedSummary=!0,this.loadedDetail=!0,this.stale=!1,this.lastPatchedAt=Date.now(),this.lastHydratedAt=Date.now())}markStale(){this.stale=!0,this.lastPatchedAt=Date.now()}clear(){this.summarySnapshot=null,this.detailSnapshot=null,this.loadedSummary=!1,this.stale=!1,this.loadedDetail=!1,this.lastPatchedAt=null,this.lastHydratedAt=null}getSummarySnapshot(){return this.summarySnapshot?ie(this.summarySnapshot):this.detailSnapshot?ie(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?ue(this.detailSnapshot):null}isStale(){return this.stale}hasLoadedSummary(){return this.loadedSummary}hasLoadedDetail(){return this.loadedDetail}getLastPatchedAt(){return this.lastPatchedAt}getLastHydratedAt(){return this.lastHydratedAt}toSummaryFromDetail(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,public:e.public,joinApprovalRequired:e.joinApprovalRequired,allowInvites:e.allowInvites,maxMembers:e.maxMembers,role:e.role,disabled:e.disabled}}}class de{toSummary(e){const t=e.getSummarySnapshot();return t?(e=>({...e}))(t):null}toDetail(e){const t=e.getDetailSnapshot();return t?(e=>({...e,owner:e.owner?{...e.owner}:void 0}))(t):null}}class ce{constructor(){this.groups=new Map,this.joinedGroupById=new Map,this.removedJoinedGroupIds=new Set,this.snapshotMapper=new de,this.joinedGroupSnapshot=null,this.sessionKey=null}ensureSession(e){return this.sessionKey!==e&&(this.sessionKey=e,this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null,!0)}getSessionKey(){return this.sessionKey}getOrCreate(e){const t=this.groups.get(e);if(t)return t;const r=new pe(e);return this.groups.set(e,r),r}mergeSummary(e){return this.getOrCreate(e.groupId).mergeSummary(e),this.getSummarySnapshot(e.groupId)??{...e}}mergeSummaries(e){return e.map(e=>this.mergeSummary(e))}applyJoinedGroupSnapshot(e){const t=e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId));this.joinedGroupSnapshot={items:t.map(e=>({...e})),meta:{...e.meta}},this.joinedGroupById.clear();for(const r of t){const e={...r};this.joinedGroupById.set(e.groupId,e),this.mergeSummary(this.toGroupSummary(e))}}getJoinedGroupSnapshot(e){return this.joinedGroupSnapshot?{items:this.joinedGroupSnapshot.items.map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}}:e?{items:e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId)).map(e=>({...e})),meta:{...e.meta}}:{items:[],meta:{integrity:"unknown",limited:!1,storageLimit:100,serverLimit:3e3,source:"sync"}}}getJoinedGroupSummarySnapshot(e,t){const r=this.joinedGroupById.get(e);if(r)return{...r};if(this.removedJoinedGroupIds.has(e))return null;const o=t?.items.find(t=>t.groupId===e);return o?{...o}:null}addJoinedGroupIfAbsent(e,t){const r=this.getJoinedGroupSnapshot(t);return r.items.some(t=>t.groupId===e.groupId)?null:(this.removedJoinedGroupIds.delete(e.groupId),this.applyJoinedGroupSnapshot({items:[{...e},...r.items],meta:{...r.meta}}),this.getJoinedGroupSnapshot())}mergeJoinedGroupSummary(e,t){const r=this.joinedGroupById.get(e);if(!r||!this.joinedGroupSnapshot)return null;const o={...r,...t,groupId:e};return this.joinedGroupById.set(e,o),this.mergeSummary(this.toGroupSummary(o)),this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.map(t=>t.groupId===e?{...o}:{...t}),meta:{...this.joinedGroupSnapshot.meta}},this.getJoinedGroupSnapshot()}mergeDetail(e){const t=this.mergeJoinedGroupFieldsIntoDetail(e);return this.getOrCreate(t.groupId).mergeDetail(t),this.getDetailSnapshot(t.groupId)??{...t}}mergeDetails(e){return e.map(e=>this.mergeDetail(e))}getSummarySnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toSummary(t):null}getDetailSnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toDetail(t):null}hasFreshDetail(e){const t=this.groups.get(e);return Boolean(t&&t.hasLoadedDetail()&&!t.isStale())}markStale(e){this.getOrCreate(e).markStale()}delete(e){this.groups.delete(e),this.joinedGroupById.delete(e),this.joinedGroupSnapshot&&(this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.filter(t=>t.groupId!==e).map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}})}markJoinedGroupRemoved(e){this.removedJoinedGroupIds.add(e),this.delete(e)}clear(){this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null}mergeJoinedGroupFieldsIntoDetail(e){const t=this.joinedGroupById.get(e.groupId);return t&&void 0===e.joinedAt&&void 0!==t.joinedAt?{...e,joinedAt:t.joinedAt}:e}toGroupSummary(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,role:e.role,disabled:e.disabled}}}const me=0,le=5,he=12,ge=13,Ie=0,ye=1,fe=2,Re=0,_e=1,Ge=2,ve=3,we=e=>{const t=e.group_id?.trim();return t?{groupId:t,name:e.group_name??"",description:e.description,memberCount:e.members_count,role:(o=e.role,o===Ie?"owner":o===ye?"admin":o===fe?"member":void 0),disabled:e.disabled,ownerId:e.group_owner,avatarUrl:e.group_avatar,muteAllMembers:e.mute_all,muteExpiration:e.mute_expiration,remindType:(r=e.remind_type,r===Re?"DEFAULT":r===_e?"ALL":r===Ge?"AT":r===ve?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,o},Se=e=>e.updatedAt??0,Ee=(e,t)=>{if(!e)return!0;return Se(t)>=Se(e)},be={nested:{easemob:{nested:{joinedgroups:{nested:{GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},request_id:{type:"string",id:3},protocol_version:{type:"int32",id:4}}},GetJoinedGroupsRequest:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},last_sync_time:{type:"int64",id:6},cursor:{type:"string",id:7}}},GroupItem:{fields:{group_id:{type:"string",id:1},group_name:{type:"string",id:2},group_owner:{type:"string",id:3},members_count:{type:"int64",id:4},mute_all:{type:"bool",id:5},disabled:{type:"bool",id:6},description:{type:"string",id:7},group_avatar:{type:"string",id:8},role:{type:"uint32",id:9},mute_expiration:{type:"int64",id:10},remind_type:{type:"int32",id:11},create_at:{type:"uint64",id:12},update_at:{type:"uint64",id:13},joined_timestamp:{type:"int64",id:14}}},GetJoinedGroupsResponse:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},groups:{rule:"repeated",type:"GroupItem",id:3},is_last_batch:{type:"bool",id:4},last_sync_finished_ts:{type:"int64",id:5},cursor:{type:"string",id:6}}},ErrorDetail:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},code:{type:"uint32",id:3},message:{type:"string",id:4}}}}}}}}};let Ce=null,Ae=!1;const Ue=()=>Ce||(Ae||(a.lightExports.util.Long=a.Long,a.lightExports.configure(),Ae=!0),a.installReflectionRuntime(),Ce=a.lightExports.Root.fromJSON(be),a.installReflectionCodecInNamespace(Ce),Ce),Oe=e=>Ue().lookupType(e),De=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}if(a.Long.isLong(e))return e.toNumber();if(e&&"object"==typeof e&&"toString"in e&&"function"==typeof e.toString){const t=Number(e.toString());return Number.isFinite(t)?t:void 0}},Ne=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:De(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:De(t.protocol_version)??De(t.protocolVersion)??0}};class Te{constructor(){this.requestType=Oe("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=Oe("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=Oe("easemob.joinedgroups.ErrorDetail")}encodeRequest(e){const t=this.requestType.create({type:e.type,header:e.header?{resource:e.header.resource,timestamp:e.header.timestamp,request_id:e.header.requestId,protocol_version:e.header.protocolVersion}:void 0,org:e.org,app:e.app,username:e.username,last_sync_time:e.lastSyncTime??0,cursor:e.cursor});return this.requestType.encode(t).finish()}decode(e){const t=this.tryDecodeError(e);if(t)return t;const r=this.tryDecodeResponse(e);if(r)return r;const o=this.tryDecodeRequest(e);return o||{type:me}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=De(t.type);return r!==he?null:{type:r,header:Ne(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:De(t.last_sync_time)??De(t.lastSyncTime)??0,cursor:"string"==typeof t.cursor?t.cursor:void 0}}catch{return null}}tryDecodeResponse(e){try{const t=this.responseType.toObject(this.responseType.decode(e),{longs:String,bytes:Uint8Array}),r=De(t.type);return r!==ge?null:{type:r,header:Ne(t.header),groups:Array.isArray(t.groups)?t.groups.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{group_id:"string"==typeof t.group_id?t.group_id:"string"==typeof t.groupId?t.groupId:void 0,group_name:"string"==typeof t.group_name?t.group_name:"string"==typeof t.groupName?t.groupName:void 0,group_owner:"string"==typeof t.group_owner?t.group_owner:"string"==typeof t.groupOwner?t.groupOwner:void 0,members_count:De(t.members_count)??De(t.membersCount),mute_all:"boolean"==typeof t.mute_all?t.mute_all:"boolean"==typeof t.muteAll?t.muteAll:void 0,disabled:"boolean"==typeof t.disabled?t.disabled:void 0,description:"string"==typeof t.description?t.description:void 0,group_avatar:"string"==typeof t.group_avatar?t.group_avatar:"string"==typeof t.groupAvatar?t.groupAvatar:void 0,role:De(t.role),mute_expiration:De(t.mute_expiration)??De(t.muteExpiration),remind_type:De(t.remind_type)??De(t.remindType),create_at:De(t.create_at)??De(t.createAt),update_at:De(t.update_at)??De(t.updateAt),joined_timestamp:De(t.joined_timestamp)??De(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:De(t.last_sync_finished_ts)??De(t.lastSyncFinishedTs),cursor:"string"==typeof t.cursor?t.cursor:void 0}}catch{return null}}tryDecodeError(e){try{const t=this.errorType.toObject(this.errorType.decode(e),{longs:String,bytes:Uint8Array}),r=De(t.type);return r!==le?null:{type:r,header:Ne(t.header),code:De(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class Me{constructor(e){this.batches=[],this.done=!1,this.requestId=e}getResumeCursor(){return this.latestCursor}push(e){if(e.type!==ge)return{done:!1};const r=e.header?.requestId;if(r!==this.requestId)return{done:!1};if(this.done)throw new t.SDKError("Joined groups response received after completion",t.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:{stage:"response_decode",requestId:this.requestId}});if(this.batches.push(e),e.cursor&&(this.latestCursor=e.cursor),e.isLastBatch){if("number"!=typeof e.lastSyncFinishedTs)throw new t.SDKError("Joined groups final batch missing lastSyncFinishedTs",t.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:{stage:"completion_meta",requestId:this.requestId}});this.done=!0,this.lastSyncFinishedTs=e.lastSyncFinishedTs}return{done:this.done}}buildResult(){return{batches:this.batches.map(e=>({...e,groups:e.groups.map(e=>({...e}))})),lastSyncFinishedTs:this.lastSyncFinishedTs}}}const Le=e=>e.type===ge,Fe=e=>e.type===le;class Pe{constructor(e){this.codec=new Te,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new Me(t);return await this.syncWithSharedSession(e.request,t,r)}cancel(){this.sharedSession.cancel("group-sync-cancelled")}async syncWithSharedSession(e,r,o){return await this.sharedSession.request({dataType:"group",label:"Group sync",requestId:r,encode:()=>this.codec.encodeRequest(this.buildAttemptRequest(e,r,o.getResumeCursor())),decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:Le(t)||Fe(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(Le(e)){if(!o.push(e).done)return;return{done:!0,result:o.buildResult()}}if(Fe(e))throw(e=>{const r=(t,r)=>({stage:t,serverCode:e.code,requestId:e.header?.requestId,retryable:r});switch(e.code){case 1601:return new t.SDKError(e.message,t.ERROR_CODES.VALIDATION_REQUIRED,{details:r("request_send",!1)});case 1602:return new t.SDKError(e.message,t.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:r("batch_merge",!0)});case 1002:return new t.AuthenticationError(e.message,{code:t.ERROR_CODES.AUTH_UNAUTHORIZED,details:r("auth",!1)});case 1003:return new t.SDKError(e.message,t.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,{details:r("server_limit",!0)});default:return new t.SDKError(e.message,t.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:r("response_decode",!0)})}})(e);return}catch(r){throw r instanceof t.SDKError?r:new t.SDKError("Joined groups frame decode failed",t.ERROR_CODES.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:r instanceof Error?r.message:String(r)}})}}})}buildAttemptRequest(e,t,r){return{...e,cursor:r,lastSyncTime:0,header:{resource:e.header?.resource??"",timestamp:Date.now(),requestId:t,protocolVersion:e.header?.protocolVersion??1}}}}class xe{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("group-sync-cancelled")}async runSync(){this.dependencies.onStart();const e=Date.now();try{const o=await this.dependencies.getSyncUrls();if(0===o.length)throw new t.SDKError("Group sync websocket urls are unavailable",t.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",retryable:!0}});const s=this.buildRequest(),n=await new Pe(this.dependencies.getSharedSyncSession()).sync({urls:o,request:s}),a=n.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=we(r);e&&t.push(e)}return t})(e.groups)),i=this.dependencies.getRuntimeSnapshot(),u=(e=>{const t=new Map(e.existingItems.map(e=>[e.groupId,e])),r=new Map;for(const s of e.incomingItems){const e=r.get(s.groupId)??t.get(s.groupId);Ee(e,s)?r.set(s.groupId,{...e??{},...s,groupId:s.groupId}):e&&r.set(s.groupId,{...e})}const o=r.size>=A;return{items:Array.from(o?e.existingItems.map(e=>({...e})):r.values()).sort((e,t)=>{const r=(t.joinedAt??0)-(e.joinedAt??0);return 0!==r?r:e.groupId.localeCompare(t.groupId)}),meta:{integrity:o?"limited":"synced",limited:o,storageLimit:C,serverLimit:A,source:"sync",lastSyncFinishedTs:e.lastSyncFinishedTs,lastSuccessfulAt:Date.now()}}})({existingItems:i?.items??[],incomingItems:a,lastSyncFinishedTs:n.lastSyncFinishedTs}),p=this.dependencies.getCacheManager();this.dependencies.applyRuntimeSnapshot(u);const d=this.dependencies.getRuntimeSnapshot()??u;try{await p.commitJoinedGroupPreviewSnapshot(d);const e=this.dependencies.getRuntimeSnapshot();e&&!this.hasSameMembership(d,e)&&await p.commitJoinedGroupPreviewSnapshot(e)}catch(r){throw i&&this.dependencies.applyRuntimeSnapshot(i),new t.StorageError("Joined-group preview persistence failed",{details:{stage:"preview_persist",cause:r instanceof Error?r.message:String(r)}})}t.logger.warn("Group sync finished",{durationMs:Date.now()-e,itemCount:u.items.length,limited:u.meta.limited}),this.dependencies.onFinish({status:"success"})}catch(r){const o=(e=>{const r=e instanceof t.SDKError?e:new t.SDKError("Group sync failed",t.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:{stage:"socket_connect",cause:e instanceof Error?e.message:String(e)}}),o=r.details??{},s=o.serverCode;return{dataType:"group",code:r.code,stage:(n=o.stage,"config"===n||"socket_connect"===n||"request_send"===n||"response_decode"===n||"batch_merge"===n||"preview_persist"===n||"completion_meta"===n||"auth"===n||"server_limit"===n||"cancelled"===n?n:"socket_connect"),message:r.message,retryable:!0===o.retryable,serverCode:"number"==typeof s||"string"==typeof s?s:void 0};var n})(r);t.logger.warn("Group sync failed",{durationMs:Date.now()-e,stage:o.stage,code:o.code,serverCode:o.serverCode}),this.dependencies.onFinish({status:"failed",error:o})}}hasSameMembership(e,t){if(e.items.length!==t.items.length)return!1;const r=new Set(t.items.map(e=>e.groupId));return e.items.every(e=>r.has(e.groupId))}buildRequest(){const e=this.dependencies.getRestContext(),{orgName:r,appName:o}=t.parseAppKey(e.appKey);return{type:he,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:r,app:o,username:e.userId,lastSyncTime:0}}}const $e=t.mergeRuntimeErrorMaps(t.COMMON_ERROR_MAP,{common:{},apis:{createGroup:{range:"4,110,204,608",errors:{invalid_parameter:{code:110,httpStatus:400,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},exceed_limit:{code:4,httpStatus:403,retryable:!1},group_name_violation:{code:608,httpStatus:403,retryable:!1,aliases:["INVALID_GROUP_NAME"]},resource_not_found:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","username_not_found"]}}},getJoinedGroupList:{range:"",errors:{}},getGroupInfo:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupInfoList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},updateGroupInfo:{range:"110,603,606,607,608",errors:{group_authorization:{code:603,httpStatus:403,retryable:!1},forbidden_op:{code:603,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},exceed_limit:{code:110,httpStatus:403,retryable:!1},group_name_violation:{code:608,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1},group_disabled:{code:607,httpStatus:403,retryable:!1}}},changeGroupOwner:{range:"603,606",errors:{forbidden_op:{code:603,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1}}},destroyGroup:{range:"603,606,607",errors:{group_authorization:{code:603,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1},group_disabled:{code:607,httpStatus:403,retryable:!1}}},leaveGroup:{range:"602,603,606",errors:{not_joined:{code:602,retryable:!1,aliases:["GROUP_NOT_JOINED","group_not_joined"]},owner_cannot_leave:{code:603,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"owner can not quit group"},resource_not_found:{code:606,httpStatus:404,retryable:!1}}},joinGroup:{range:"600-607,613",errors:{group_invalid_id:{code:600,retryable:!1,aliases:["GROUP_INVALID_ID"]},already_joined:{code:601,retryable:!1,aliases:["ALREADY_JOINED","GROUP_ALREADY_JOINED","group_already_joined"]},not_joined:{code:602,retryable:!1,aliases:["GROUP_NOT_JOINED","group_not_joined"]},group_authorization:{code:603,httpStatus:403,retryable:!1,aliases:["NEED_APPROVAL","GROUP_PERMISSION_DENIED"]},group_full:{code:604,httpStatus:403,retryable:!1,aliases:["GROUP_FULL","GROUP_MEMBERS_FULL"],matchField:"error_description",matchPattern:"member list is full"},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["GROUP_NOT_FOUND","service_resource_not_found"]},group_disabled:{code:607,retryable:!1,aliases:["GROUP_DISABLED"]},group_user_in_blocklist:{code:613,httpStatus:403,retryable:!1,aliases:["GROUP_USER_IN_BLOCKLIST"],matchField:"error_description",matchPattern:"is in the blacklist"}}},inviteUsersToGroup:{range:"204,603,606,607",errors:{group_authorization:{code:603,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","username_not_found"]},group_not_found:{code:606,retryable:!1,aliases:["GROUP_NOT_FOUND"]},group_disabled:{code:607,retryable:!1}}},acceptGroupJoinRequest:{range:"",errors:{}},rejectGroupJoinRequest:{range:"",errors:{}},acceptInvitation:{range:"",errors:{}},rejectInvitation:{range:"",errors:{}},removeGroupMembers:{range:"",errors:{}},addGroupAdmin:{range:"",errors:{}},removeGroupAdmin:{range:"",errors:{}},muteGroupMembers:{range:"",errors:{}},unmuteGroupMembers:{range:"",errors:{}},muteAllGroupMembers:{range:"",errors:{}},unmuteAllGroupMembers:{range:"",errors:{}},blockGroupMembers:{range:"",errors:{}},unblockGroupMembers:{range:"",errors:{}},addUsersToGroupAllowlist:{range:"",errors:{}},removeUsersFromGroupAllowlist:{range:"",errors:{}},checkIfInGroupAllowList:{range:"",errors:{}},getGroupMemberList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},getGroupAdminList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupMuteList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},checkIfInGroupMuteList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupBlocklist:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupAllowlist:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupAnnouncement:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},updateGroupAnnouncement:{range:"110",errors:{announcement_length_exceeded:{code:110,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"announce into length exceeds limit"},announcement_info_length_exceeded:{code:110,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"announce info length exceeds limit"}}},getGroupSharedFileList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["RestGroupFeignException"]}}},deleteGroupSharedFile:{range:"603,605,606",errors:{group_authorization:{code:603,retryable:!1},file_not_found:{code:605,retryable:!1,aliases:["GROUP_SHARED_FILE_INVALID_ID"]},resource_not_found:{code:606,retryable:!1}}},setGroupMemberAttributes:{range:"4,210,302,305,602,609-612",errors:{attributes_reach_limit:{code:609,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_REACH_LIMIT"],matchField:"error_code",matchValue:60006},attributes_update_failed:{code:610,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_UPDATE_FAILED"],matchField:"error_code",matchValue:60005},attributes_key_reach_limit:{code:611,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_KEY_REACH_LIMIT"],matchField:"error_code",matchValue:60009},attributes_value_reach_limit:{code:612,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_VALUE_REACH_LIMIT"],matchField:"error_code",matchValue:600010},not_joined:{code:602,httpStatus:404,retryable:!1,matchField:"error_code",matchValue:60003},permission_denied:{code:210,httpStatus:401,retryable:!1,matchField:"error_code",matchValue:60001},permission_denied_403:{code:210,httpStatus:403,retryable:!1,matchField:"error_code",matchValue:60002},exceed_service_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60007},service_disabled:{code:305,httpStatus:403,retryable:!1,matchField:"error_code",matchValue:60004}}},getGroupMembersAttributes:{range:"606",errors:{resource_not_found:{code:606,retryable:!1}}},getGroupNamecards:{range:"",errors:{}}}}),je=class{constructor(){this.capabilities=["rawNotify:group","group:namecard"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.groupRegistry=new Map,this.groupRepository=null,this.groupEventSync=null}bind(e,t){this.client=e,this.eventContext=t??null,this.groupRegistry.clear(),this.groupRepository=new ce,this.groupEventSync=new ae(this.groupRepository),this.ensureRepositorySession()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("group"!==e.type)return;const t=e.payload,r=t.eventName,o=await this.buildIncomingEventPayload(r,t);if(!o)return;if(this.eventContext?.dispatch?.(r,o),r!==s.GroupEventName.GROUP_MEMBER_ATTRIBUTE_CHANGED)return;if(!("attribute"in o)||!("user"in o))return;const n=this.extractGroupNamecard(o.attribute);if(void 0===n||!o.user?.userId)return;const a=this.client?.getCurrentUserId();o.user.userId!==a&&(this.getCacheManager()?.setGroupNamecards([{groupId:o.groupId,userId:o.user.userId,namecard:n,lastAccess:Date.now(),lastUpdate:Date.now()}]),this.eventContext?.dispatch?.(s.GroupEventName.USER_GROUP_NAMECARD_UPDATED,{groupId:o.groupId,userId:o.user.userId,namecard:n}))}async createGroup(e){return this.runOperation("createGroup",async()=>{const t=this.getRestContextOrThrow(),r=await J(this.getRestClient(t),t,e);return this.ensureRepositorySession(),this.addJoinedGroupIfAbsent({groupId:r.groupId,name:e.name,role:"owner",ownerId:t.userId,...void 0===e.description?{}:{description:e.description},...void 0===e.avatar?{}:{avatarUrl:e.avatar}}),r})}getJoinedGroupList(){return this.getJoinedGroupSnapshotForSync().items}getJoinedGroupSnapshotForSync(){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSnapshot(this.loadJoinedGroupPreviewSnapshot())}applyJoinedGroupSnapshot(e){this.ensureRepositorySession(),this.getGroupRepository().applyJoinedGroupSnapshot(e)}getGroupSummaryForHandle(e){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())}getGroup(e){this.requireClient(),this.ensureRepositorySession();const r=e.trim();if(0===r.length)throw new t.ValidationError("groupId is required",{code:t.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"groupId",message:"groupId is required",rule:"required"}]}});const o=this.groupRegistry.get(r);if(o)return o;this.getGroupSummaryForHandle(r),this.getGroupRepository().getOrCreate(r);const s=new N(r,this);return this.groupRegistry.set(r,s),s}async getGroupInfo(e){return this.runOperation("getGroupInfo",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow(),r=await B(this.getRestClient(t),t,e),o=await this.hydrateGroupDetailUsers(r);return this.getGroupRepository().mergeDetail(o)})}async getGroupInfoList(t){return this.runOperation("getGroupInfoList",async()=>{this.ensureRepositorySession();const r=this.getRestContextOrThrow(),o=await(async(t,r,o)=>{const s=T(r),n=F(o.groupIds,"params.groupIds"),a=j(s,`/chatgroups/${n.map(e=>encodeURIComponent(e)).join(",")}?joined_time=true&version=v3`),i=await t.get(a,{operation:"getGroupInfoList"});return(e.isRecord(i)&&Array.isArray(i.data)?i.data:[]).map(e=>w({data:[e]}))})(this.getRestClient(r),r,t),s=await this.hydrateGroupDetailsUsers(o);return this.getGroupRepository().mergeDetails(s)})}async getGroupDetailForHandle(e){this.ensureRepositorySession();const t=this.getGroupRepository();if(t.getOrCreate(e),t.hasFreshDetail(e)){const r=t.getDetailSnapshot(e);if(r)return r}return this.getGroupInfo({groupId:e})}async refreshGroupDetailForHandle(e){return this.ensureRepositorySession(),this.getGroupRepository().getOrCreate(e),this.getGroupInfo({groupId:e})}resetSessionRuntime(){this.groupRegistry.clear(),this.getGroupRepository().ensureSession(null)}async buildIncomingEventPayload(e,t){this.ensureRepositorySession();const r=t.payload,o=e===s.GroupEventName.GROUP_DESTROYED?this.resolveLocalGroupName(r.groupId):void 0,n=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(await this.syncRuntimeForEvent(e,r,n),e){case s.GroupEventName.INVITATION_RECEIVED:return{groupId:r.groupId,groupName:r.groupName,inviter:this.pickEventUser(r.inviterId,n),reason:r.reason};case s.GroupEventName.REQUEST_TO_JOIN_RECEIVED:return{groupId:r.groupId,groupName:r.groupName,applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case s.GroupEventName.REQUEST_TO_JOIN_ACCEPTED:return{groupId:r.groupId,groupName:r.groupName,accepter:this.pickEventUser(r.accepterId,n)};case s.GroupEventName.REQUEST_TO_JOIN_DECLINED:return{groupId:r.groupId,groupName:r.groupName,decliner:this.pickEventUser(r.declinerId,n),applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case s.GroupEventName.INVITATION_ACCEPTED:case s.GroupEventName.INVITATION_DECLINED:return{groupId:r.groupId,invitee:this.pickEventUser(r.inviteeId,n),reason:r.reason};case s.GroupEventName.USER_REMOVED:return{groupId:r.groupId,groupName:r.groupName};case s.GroupEventName.GROUP_DESTROYED:return{groupId:r.groupId,groupName:r.groupName??o};case s.GroupEventName.AUTO_ACCEPT_INVITATION:return{groupId:r.groupId,inviter:this.pickEventUser(r.inviterId,n),inviteMessage:r.reason};case s.GroupEventName.MUTE_LIST_ADDED:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n),muteExpire:r.muteExpire};case s.GroupEventName.MUTE_LIST_REMOVED:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n)};case s.GroupEventName.ALLOW_LIST_ADDED:case s.GroupEventName.ALLOW_LIST_REMOVED:return{groupId:r.groupId,allowlist:this.pickEventUsers(r.userIds,n)};case s.GroupEventName.ALL_MEMBER_MUTE_STATE_CHANGED:return{groupId:r.groupId,isMuted:Boolean(r.isMuted)};case s.GroupEventName.ADMIN_ADDED:case s.GroupEventName.ADMIN_REMOVED:return{groupId:r.groupId,administrator:this.pickEventUser(r.administratorId,n)};case s.GroupEventName.OWNER_CHANGED:return{groupId:r.groupId,newOwner:this.pickEventUser(r.newOwnerId,n),oldOwner:this.pickEventUser(r.oldOwnerId,n)};case s.GroupEventName.MEMBERS_JOINED:return{groupId:r.groupId,groupName:await this.resolveMembersJoinedGroupName(r),members:this.pickEventUsers(r.memberIds,n)};case s.GroupEventName.MEMBERS_EXITED:return{groupId:r.groupId,members:this.pickEventUsers(r.memberIds,n)};case s.GroupEventName.ANNOUNCEMENT_CHANGED:return{groupId:r.groupId,announcement:r.announcement??""};case s.GroupEventName.SHARED_FILE_ADDED:return{groupId:r.groupId,sharedFile:this.hydrateEventSharedFile(r.sharedFile,n)};case s.GroupEventName.SHARED_FILE_DELETED:return{groupId:r.groupId,fileId:r.fileId??""};case s.GroupEventName.GROUP_INFO_CHANGED:return{groupId:r.groupId,groupInfo:await this.resolveGroupDetailForEvent(r)};case s.GroupEventName.GROUP_DISABLED_CHANGED:{const e=await this.resolveGroupDetailForEvent(r),t=void 0===r.isDisabled?Boolean(e.disabled):Boolean(r.isDisabled);return{groupId:r.groupId,groupInfo:e,disabled:t}}case s.GroupEventName.GROUP_MEMBER_ATTRIBUTE_CHANGED:return{groupId:r.groupId,user:this.pickEventUser(r.userId,n),attribute:r.attribute??{},from:r.from,source:r.source};default:return null}}async resolveGroupDetailForEvent(e){this.ensureRepositorySession();const r=void 0===e.isDisabled?e.groupPatch:{...e.groupPatch??{},disabled:e.isDisabled},o=this.getGroupEventSync().applyPatch({groupId:e.groupId,groupName:e.groupName,groupPatch:r,shouldMarkStale:e.shouldFetchGroupDetail});if(e.shouldFetchGroupDetail)try{return await this.getGroupInfo({groupId:e.groupId})}catch(n){t.logger.warn("GroupManager resolveGroupDetailForEvent fallback to snapshot",{groupId:e.groupId,error:n})}if(o)return o;const s=this.getGroupRepository().getDetailSnapshot(e.groupId);return s||{groupId:e.groupId,name:r?.name??e.groupName??"",...r??{}}}async updateGroupInfo(e){return this.runOperation("updateGroupInfo",async()=>{const t=this.getRestContextOrThrow();await K(this.getRestClient(t),t,e)})}async changeGroupOwner(e){return this.runOperation("changeGroupOwner",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}?resource=${o.encodedResource}`);await e.put(s,{newowner:P(r.newOwner,"params.newOwner")},{operation:"changeGroupOwner"})})(this.getRestClient(t),t,e)})}async destroyGroup(e){return this.runOperation("destroyGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}?version=v3&resource=${o.encodedResource}`);await e.delete(s,{operation:"destroyGroup"})})(this.getRestClient(t),t,e),await this.requireClient().handleGroupDestroyedConversation(e.groupId),await this.removeJoinedGroupLocal(e.groupId)})}async leaveGroup(e){return this.runOperation("leaveGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/quit?resource=${o.encodedResource}`);await e.delete(s,{operation:"leaveGroup"})})(this.getRestClient(t),t,e),await this.removeJoinedGroupLocal(e.groupId)})}async joinGroup(e){return this.runOperation("joinGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/apply?resource=${o.encodedResource}`);await e.post(s,{message:r.message??""},{operation:"joinGroup"})})(this.getRestClient(t),t,e)})}async inviteUsersToGroup(e){return this.runOperation("inviteUsersToGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/invite?resource=${o.encodedResource}`);await e.post(s,{usernames:F(r.userIds,"params.userIds")},{operation:"inviteUsersToGroup"})})(this.getRestClient(t),t,e)})}async acceptGroupJoinRequest(e){return this.runOperation("acceptGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/apply_verify?resource=${o.encodedResource}`);await e.post(s,{applicant:P(r.userId,"params.userId"),verifyResult:!0},{operation:"acceptGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async rejectGroupJoinRequest(e){return this.runOperation("rejectGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/apply_verify?resource=${o.encodedResource}`);await e.post(s,{applicant:P(r.userId,"params.userId"),verifyResult:!1,reason:r.reason},{operation:"rejectGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async acceptInvitation(e){return this.runOperation("acceptInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/invite_verify?resource=${o.encodedResource}`);await e.post(s,{invitee:t.userId,verifyResult:!0},{operation:"acceptInvitation"})})(this.getRestClient(t),t,e)})}async rejectInvitation(e){return this.runOperation("rejectInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/invite_verify?resource=${o.encodedResource}`);await e.post(s,{invitee:t.userId,verifyResult:!1},{operation:"rejectInvitation"})})(this.getRestClient(t),t,e)})}async getGroupMemberList(e){return this.runOperation("getGroupMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await V(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(e.groupId,r.items)}})}async removeGroupMembers(e){return this.runOperation("removeGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=F(r.userIds,"params.userIds"),n=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAdminList(e){return this.runOperation("getGroupAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await H(this.getRestClient(t),t,e);return this.hydrateUserInfos(e.groupId,r)})}async addGroupAdmin(e){return this.runOperation("addGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/admin?resource=${o.encodedResource}`);await e.post(s,{newadmin:r.userId},{operation:"addGroupAdmin"})})(this.getRestClient(t),t,e)})}async removeGroupAdmin(e){return this.runOperation("removeGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/admin/${encodeURIComponent(r.userId)}?resource=${o.encodedResource}`);await e.delete(s,{operation:"removeGroupAdmin"})})(this.getRestClient(t),t,e)})}async getGroupMuteList(e){return this.runOperation("getGroupMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await z(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async muteGroupMembers(e){return this.runOperation("muteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/mute?resource=${o.encodedResource}`);await e.post(s,{usernames:F(r.userIds,"params.userIds"),mute_duration:r.muteDuration},{operation:"muteGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteGroupMembers(e){return this.runOperation("unmuteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=F(r.userIds,"params.userIds"),n=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/mute/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unmuteGroupMembers"})})(this.getRestClient(t),t,e)})}async muteAllGroupMembers(e){return this.runOperation("muteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/ban?resource=${o.encodedResource}`);await e.post(s,void 0,{operation:"muteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllGroupMembers(e){return this.runOperation("unmuteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/ban?resource=${o.encodedResource}`);await e.delete(s,{operation:"unmuteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupBlocklist(e){return this.runOperation("getGroupBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await W(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async blockGroupMembers(e){return this.runOperation("blockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/blocks/users?resource=${o.encodedResource}`);await e.post(s,{usernames:F(r.userIds,"params.userIds")},{operation:"blockGroupMembers"})})(this.getRestClient(t),t,e)})}async unblockGroupMembers(e){return this.runOperation("unblockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=F(r.userIds,"params.userIds"),n=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unblockGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAllowlist(e){return this.runOperation("getGroupAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await Q(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async addUsersToGroupAllowlist(e){return this.runOperation("addUsersToGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/white/users?resource=${o.encodedResource}`);await e.post(s,{usernames:F(r.userIds,"params.userIds")},{operation:"addUsersToGroupAllowlist"})})(this.getRestClient(t),t,e)})}async removeUsersFromGroupAllowlist(e){return this.runOperation("removeUsersFromGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=F(r.userIds,"params.userIds"),n=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeUsersFromGroupAllowlist"})})(this.getRestClient(t),t,e)})}async checkIfInGroupAllowList(t){return this.runOperation("checkIfInGroupAllowList",async()=>{const r=this.getRestContextOrThrow();return(async(t,r,o)=>{const s=T(r),n=j(s,`/chatgroups/${encodeURIComponent(P(o.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),a=await t.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof a?a:e.isRecord(a)&&"boolean"==typeof a.data?a.data:Boolean(a)})(this.getRestClient(r),r,t)})}async checkIfInGroupMuteList(t){return this.runOperation("checkIfInGroupMuteList",async()=>{const r=this.getRestContextOrThrow();return(async(t,r,o)=>{const s=T(r),n=j(s,`/sdk/chatgroups/${encodeURIComponent(P(o.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),a=await t.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof a?a:e.isRecord(a)&&"boolean"==typeof a.data?a.data:Boolean(a)})(this.getRestClient(r),r,t)})}async getGroupAnnouncement(e){return this.runOperation("getGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();return Y(this.getRestClient(t),t,e)})}async updateGroupAnnouncement(e){return this.runOperation("updateGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/announcement?resource=${o.encodedResource}`);await e.post(s,{announcement:r.announcement},{operation:"updateGroupAnnouncement"})})(this.getRestClient(t),t,e)})}async getGroupSharedFileList(e){return this.runOperation("getGroupSharedFileList",async()=>{const t=this.getRestContextOrThrow(),r=await X(this.getRestClient(t),t,e),o=await this.resolveGroupContextUserInfoMap(e.groupId,r.items.map(e=>e.fileOwner).filter(e=>void 0!==e));return{...r,items:r.items.map(e=>({...e,fileOwner:e.fileOwner?.userId?o.get(e.fileOwner.userId)??e.fileOwner:e.fileOwner}))}})}async uploadGroupSharedFile(e){return this.runOperation("uploadGroupSharedFile",async()=>{const r=this.getRestContextOrThrow(),s=Z(r,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),n=t.normalizeUploadSource({file:e.file}),a=t.startDataReportOperation({operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"}),i=a?.startRequest({requestName:"GROUP_UPLOAD_SHAREDFILE",method:"POST",url:`${r.restBaseUrl}${s}`});try{const o=await(this.requireClient().getUploadAdapter()?.upload({url:`${r.restBaseUrl}${s}?resource=${encodeURIComponent(r.clientResource)}`,headers:{Authorization:`Bearer ${r.token}`,[t.REQUEST_ID_HEADER]:t.createTraceId()},source:n.source,timeoutMs:t.GROUP_SHARED_FILE_UPLOAD_TIMEOUT,onProgress:e.onFileUploadProgress}));if(!o)throw new Error("platform upload adapter is unavailable");if(o.status<200||o.status>=300)throw new t.SDKError("uploadGroupSharedFile failed",t.ERROR_CODES.REST_HTTP_ERROR,{details:{status:o.status}});i?.finish({code:o.status,success:!0}),a?.finish({code:0,success:!0}),e.onFileUploadComplete?.(o.body)}catch(u){const r=o.mapUploadAdapterError(u);throw i?.finish({code:r.code,success:!1,description:r.message}),a?.finish({code:r.code,success:!1,description:r.message}),r.code===t.ERROR_CODES.UPLOAD_ABORTED&&e.onFileUploadCanceled?.(),e.onFileUploadError?.(r),r}})}async deleteGroupSharedFile(e){return this.runOperation("deleteGroupSharedFile",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=T(t),s=j(o,`/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(P(r.fileId,"params.fileId"))}?resource=${o.encodedResource}`);await e.delete(s,{operation:"deleteGroupSharedFile"})})(this.getRestClient(t),t,e)})}async downloadGroupSharedFile(e){return this.runOperation("downloadGroupSharedFile",async()=>{let r,o;try{const s=this.getRestContextOrThrow(),n=`${s.restBaseUrl}${Z(s,e)}`;r=t.startDataReportOperation({operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"}),o=r?.startRequest({requestName:"GROUP_DOWNLOAD_SHAREDFILE",method:"GET",url:n});const a=this.requireClient().getRequestAdapter();if(!a)throw new t.SDKError("downloadGroupSharedFile request adapter is unavailable",t.ERROR_CODES.REST_NETWORK_ERROR);const i=await a.request({url:n,method:"GET",headers:{Authorization:`Bearer ${s.token}`,...e.secret?{"Share-Secret":e.secret}:{},[t.REQUEST_ID_HEADER]:t.createTraceId()},responseType:"arraybuffer",timeoutMs:t.GROUP_SHARED_FILE_DOWNLOAD_TIMEOUT});if(i.status<200||i.status>=300)throw o?.finish({code:i.status,success:!1,description:"downloadGroupSharedFile failed"}),r?.finish({code:i.status,success:!1,description:"downloadGroupSharedFile failed"}),new t.SDKError("downloadGroupSharedFile failed",t.ERROR_CODES.REST_HTTP_ERROR);o?.finish({code:i.status,success:!0}),r?.finish({code:0,success:!0});const u="undefined"!=typeof Blob?new Blob([i.data]):i.data;e.onFileDownloadComplete?.(u)}catch(s){const n=s instanceof t.SDKError?s.code:t.ERROR_CODES.REST_NETWORK_ERROR,a=s instanceof Error?s.message:String(s);throw o?.finish({code:n,success:!1,description:a}),r?.finish({code:n,success:!1,description:a}),e.onFileDownloadError?.(s),s}})}async setGroupMemberAttributes(e){return this.runOperation("setGroupMemberAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await ee(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return te(this.getRestClient(t),t,e)})}async hydrateMessageProfileGroupNamecards(e,r){0!==r.length&&await this.runOperation("hydrateMessageProfileGroupNamecards",async()=>{const o=this.getRestContextOrThrow(),n=r.map(e=>e.userId),a=await(async(e,t,r)=>{const o=T(t),s=j(o,`/sdk/chatgroups/${encodeURIComponent(P(r.groupId,"params.groupId"))}/nameCard/batch/get`),n=await e.post(s,{members:F(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:re(n),responseTimestamp:ne(n)}})(this.getRestClient(o),o,{groupId:e,userIds:n}),i=new Map(r.map(e=>[e.userId,e.namecardUpdateTime])),u=[],p=new Set;for(const[t,r]of Object.entries(a.items))p.add(t),u.push({groupId:e,userId:t,namecard:r.namecard,namecardUpdateTime:i.get(t)??r.namecardUpdateTime,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()});const d=n.filter(e=>!p.has(e));d.length>0&&"number"==typeof a.responseTimestamp&&u.push(...d.map(t=>({groupId:e,userId:t,namecard:"",namecardUpdateTime:a.responseTimestamp,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}))),this.getCacheManager()?.setGroupNamecards(u);for(const e of u)e.userId!==o.userId&&""!==e.namecard&&this.eventContext?.dispatch?.(s.GroupEventName.USER_GROUP_NAMECARD_UPDATED,{groupId:e.groupId,userId:e.userId,namecard:e.namecard});d.length>0&&"number"!=typeof a.responseTimestamp&&t.logger.warn("Group namecard hydration returned partial result",{groupId:e,requestedUserIds:n,missingUserIds:d})})}async runOperation(e,r){try{return await r()}catch(o){const r=this.normalizeSdkError(e,o);throw t.logger.warn(`GroupManager ${e} failed`,{code:r.code,message:r.message,details:r.details}),r}}normalizeSdkError(e,r){return r instanceof t.SDKError?r:r instanceof Error?new t.SDKError(`GroupManager ${e} failed: ${r.message}`,t.ERROR_CODES.UNKNOWN):new t.SDKError(`GroupManager ${e} failed`,t.ERROR_CODES.UNKNOWN)}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new t.RestClient(e.restBaseUrl,{errorMap:$e,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new t.SDKError("GroupManager is not bound to client",t.ERROR_CODES.VALIDATION_REQUIRED);return this.client}getGroupRepository(){return this.groupRepository||(this.groupRepository=new ce),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new ae(this.getGroupRepository())),this.groupEventSync}ensureRepositorySession(){this.getGroupRepository().ensureSession(this.resolveRepositorySessionKey())&&this.groupRegistry.clear()}resolveRepositorySessionKey(){if(!this.client)return null;const e=this.client.getCurrentUserId();if(!e)return null;try{const e=this.client.getRestContext();return`${e.restBaseUrl}:${e.userId}:${e.token}:${e.clientResource}`}catch{return`pending:${e}`}}getCacheManager(){return this.client?.getCacheManager()??null}loadJoinedGroupPreviewSnapshot(){const e=this.getCacheManager();if(e&&"function"==typeof e.loadJoinedGroupPreviewSnapshot)return e.loadJoinedGroupPreviewSnapshot()}resolveLocalGroupName(e){const t=this.getGroupRepository(),r=t.getSummarySnapshot(e)?.name;if(r)return r;const o=t.getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())?.name;return o||void 0}async resolveMembersJoinedGroupName(e){const r=this.resolveUsableGroupName(this.resolveLocalGroupName(e.groupId),e.groupId);if(r)return r;const o=this.resolveUsableGroupName(e.groupName,e.groupId);if(o)return o;const s=this.getGroupRepository().getSessionKey();try{const t=this.getRestContextOrThrow(),r=await B(this.getRestClient(t),t,{groupId:e.groupId}),o=this.getGroupRepository();if(o.getSessionKey()!==s)return;return o.mergeDetail(r),this.resolveUsableGroupName(r.name,e.groupId)}catch(n){return void t.logger.warn("Members joined group detail enrichment failed",{groupId:e.groupId,error:n})}}resolveUsableGroupName(e,t){const r=e?.trim();return r&&r!==t?r:void 0}writeSelfGroupNamecardCache(e,r,o){if(r.userId!==e)return;const s=this.extractGroupNamecard(r.memberAttributes);if("string"!=typeof s)return;const n=this.resolveGroupMemberAttributesUpdateTime(o,r.userId);"number"!=typeof n&&t.logger.warn("Group member attributes update response missing server update time",{groupId:r.groupId,userId:r.userId}),this.getCacheManager()?.setGroupNamecards([{groupId:r.groupId,userId:r.userId,namecard:s,namecardUpdateTime:n,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}])}resolveGroupMemberAttributesUpdateTime(e,t){const o=[];this.collectUpdateTimeCandidates(e,t,o);for(const s of o){const e=r.normalizeProfileVersionFromTimestamp("number"==typeof s?s:Number(s));if("number"==typeof e)return e}}collectUpdateTimeCandidates(t,r,o){if(!e.isRecord(t))return;o.push(t.lastModified,t.last_modified,t.timestamp,t.updateTime,t.update_time,t.updatedAt,t.updated_at);const s=t.data;if(e.isRecord(s)){this.collectUpdateTimeCandidates(s,r,o);const t=s[r];e.isRecord(t)&&this.collectUpdateTimeCandidates(t,r,o)}const n=t.lastModified??t.last_modified;e.isRecord(n)&&o.push(n[r])}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}async resolveUserInfoMap(e){return c(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const r=this.getUserInfoManager();if(0===e.length)return[];if(!r)return await this.fetchUserInfosFromRest(e);try{return await r.getUserInfoByUserId({userIds:e})}catch(o){return t.logger.warn("GroupManager user info fetch failed",{userIds:e,error:o}),[]}}})}collectEventUserIds(e){const t=e.payload,r=[t.inviterId,t.applicantId,t.accepterId,t.declinerId,t.inviteeId,t.administratorId,t.oldOwnerId,t.newOwnerId,t.userId,t.sharedFile?.fileOwner?.userId,...t.memberIds??[],...t.userIds??[]],o=[],s=new Set;for(const n of r){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),o.push(e))}return o}pickEventUser(e,t){if(e)return d(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>d(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:d(e.fileOwner,t.get(e.fileOwner.userId),e.fileOwner.userId)}:e}async syncRuntimeForEvent(e,t,r){switch(e){case s.GroupEventName.ALL_MEMBER_MUTE_STATE_CHANGED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{muteAllMembers:Boolean(t.isMuted)}});case s.GroupEventName.OWNER_CHANGED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{owner:this.pickEventUser(t.newOwnerId,r)}});case s.GroupEventName.REQUEST_TO_JOIN_ACCEPTED:case s.GroupEventName.AUTO_ACCEPT_INVITATION:return void this.addCurrentUserJoinedGroupFromEvent(t);case s.GroupEventName.MEMBERS_JOINED:{let r=!1;if(t.memberIds?.includes(this.requireClient().getCurrentUserId()??"")&&(r=await this.addCurrentUserJoinedGroupFromEvent(t)),r)return;if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0})}case s.GroupEventName.MEMBERS_EXITED:if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,-this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});case s.GroupEventName.USER_REMOVED:case s.GroupEventName.GROUP_DESTROYED:return void(await this.removeJoinedGroupLocal(t.groupId));case s.GroupEventName.MUTE_LIST_ADDED:case s.GroupEventName.MUTE_LIST_REMOVED:case s.GroupEventName.ALLOW_LIST_ADDED:case s.GroupEventName.ALLOW_LIST_REMOVED:case s.GroupEventName.ADMIN_ADDED:case s.GroupEventName.ADMIN_REMOVED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});default:return}}getMemberEventDeltaCount(e,t){switch(e){case s.GroupEventName.MEMBERS_JOINED:case s.GroupEventName.MEMBERS_EXITED:return t.memberIds?.length??0;default:return 0}}applyMemberCountDeltaPatch(e,t,r){if(0===r)return!1;const o=this.getGroupRepository().getDetailSnapshot(e);return!(!o||"number"!=typeof o.memberCount)&&(this.getGroupEventSync().applyPatch({groupId:e,groupName:t,groupPatch:{memberCount:Math.max(0,o.memberCount+r)}}),!0)}async removeJoinedGroupLocal(e){this.getGroupRepository().markJoinedGroupRemoved(e);const t=this.getCacheManager();t&&"function"==typeof t.removeJoinedGroupPreview&&await t.removeJoinedGroupPreview(e)}async addCurrentUserJoinedGroupFromEvent(e){if(!this.addJoinedGroupIfAbsent({groupId:e.groupId,name:e.groupName??"",role:"member"}))return!1;const r=this.getGroupRepository().getSessionKey();let o;try{o=this.getRestContextOrThrow()}catch(s){return t.logger.warn("Joined group detail enrichment skipped",{groupId:e.groupId,error:s}),!1}try{return await this.enrichJoinedGroupFromDetail(e.groupId,r,o)}catch(s){return t.logger.warn("Joined group detail enrichment failed",{groupId:e.groupId,error:s}),!1}}addJoinedGroupIfAbsent(e){const t=this.getGroupRepository().addJoinedGroupIfAbsent(e,this.loadJoinedGroupPreviewSnapshot());return!!t&&(this.persistJoinedGroupSnapshot(t),!0)}async enrichJoinedGroupFromDetail(e,t,r){const o=await B(this.getRestClient(r),r,{groupId:e}),s=this.getGroupRepository();if(s.getSessionKey()!==t)return!1;s.mergeDetail(o);const n=s.getJoinedGroupSummarySnapshot(e);if(!n)return!1;const a=s.mergeJoinedGroupSummary(e,{...n.name||!o.name?{}:{name:o.name},...void 0!==n.description||void 0===o.description?{}:{description:o.description},...void 0!==n.memberCount||void 0===o.memberCount?{}:{memberCount:o.memberCount},...void 0!==n.role||void 0===o.role?{}:{role:o.role},...void 0!==n.disabled||void 0===o.disabled?{}:{disabled:o.disabled},...n.ownerId||!o.owner?.userId?{}:{ownerId:o.owner.userId},...void 0!==n.avatarUrl||void 0===o.avatarUrl?{}:{avatarUrl:o.avatarUrl},...void 0!==n.muteAllMembers||void 0===o.muteAllMembers?{}:{muteAllMembers:o.muteAllMembers},...void 0!==n.createdAt||void 0===o.createdAt?{}:{createdAt:o.createdAt},...void 0!==n.joinedAt||void 0===o.joinedAt?{}:{joinedAt:o.joinedAt}});if(a){this.persistJoinedGroupSnapshot(a);const t=s.getJoinedGroupSummarySnapshot(e);t&&this.requireClient().refreshConversationDisplayFromJoinedGroups([{...t,name:o.name||t.name,avatarUrl:o.avatarUrl??t.avatarUrl}],"profile",{onlyWhenNameMissing:!0})}return!0}persistJoinedGroupSnapshot(e){const r=this.getCacheManager();if(r&&"function"==typeof r.applyJoinedGroupPreviewSnapshot){try{r.applyJoinedGroupPreviewSnapshot(e)}catch(o){return void t.logger.warn("Joined group preview persistence failed",{error:o})}"function"==typeof r.flushPending&&r.flushPending().catch(e=>{t.logger.warn("Joined group preview flush failed",{error:e})})}}async hydrateUserInfos(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t);return t.map(e=>r.get(e.userId)??e)}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=n.buildFetchUserInfoByUserIdRequest(e),o=await this.getRestClient(t).request(n.buildUserInfoFetchEndpoint(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return n.normalizeFetchedUserInfos(o,r.targets)}async hydrateEntriesWithUsers(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t.map(e=>e.user));return t.map(e=>({...e,user:r.get(e.user.userId)??e.user}))}extractGroupNamecard(e){return e.groupNamecard??e.group_namecard??e.group_name_card??e.namecard}async hydrateGroupDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveGroupContextUserInfoMap(e.groupId,[e.owner]);return{...e,owner:t.get(e.owner.userId)??e.owner}}async hydrateGroupDetailsUsers(e){const t=e.filter(e=>Boolean(e.owner?.userId)).map(e=>({groupId:e.groupId,user:e.owner}));if(0===t.length)return e;const r=await this.resolveGroupUserInfoContexts(t);return e.map(e=>e.owner?.userId?{...e,owner:r.get(o.getGroupUserInfoContextKey(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),s=await o.resolveGroupUserInfoMap({groupId:e,users:t,includeNameCard:r,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return r&&this.dispatchFetchedUserInfoUpdates(s.fetchedUserInfos),s.usersById}async resolveGroupUserInfoContexts(e){const t=this.isGroupNamecardEnhancementEnabled(),r=await o.resolveGroupUserInfoContexts({contexts:e,includeNameCard:t,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return t&&this.dispatchFetchedUserInfoUpdates(r.fetchedUserInfos),r.usersByContextKey}async fetchGroupUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoManager();return t?await t.getUserInfoByUserId({userIds:e}):await this.fetchUserInfosFromRest(e)}isGroupNamecardEnhancementEnabled(){const e=this.requireClient(),t=e.isUserInfoSyncEnabled;return"function"==typeof t&&t.call(e)}dispatchFetchedUserInfoUpdates(e){if(0===e.length)return;const t=this.requireClient(),r=t.getCurrentUserId(),o=e.find(e=>e.userId===r),s=e.filter(e=>e.userId!==r);o&&t.dispatchOwnInfoUpdated?.(o),t.dispatchUserInfoUpdated?.(s),t.refreshConversationDisplayFromUserInfos?.(e.map(e=>({userId:e.userId})),"profile")}createSyncController(e){return new xe(e)}};je.key="groupManager";let ke=je;exports.Group=N,exports.GroupManager=ke,exports.JoinedGroupPreviewCache=class{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:C,serverLimit:A,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:C,serverLimit:A,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return O(t=e)&&"string"==typeof t.groupId&&0!==t.groupId.length?{groupId:t.groupId,name:"string"==typeof t.name?t.name:"",description:"string"==typeof t.description?t.description:void 0,memberCount:"number"==typeof t.memberCount?t.memberCount:void 0,role:"owner"===t.role||"admin"===t.role||"member"===t.role?t.role:void 0,disabled:"boolean"==typeof t.disabled?t.disabled:void 0,ownerId:"string"==typeof t.ownerId?t.ownerId:void 0,avatarUrl:"string"==typeof t.avatarUrl?t.avatarUrl:void 0,muteAllMembers:"boolean"==typeof t.muteAllMembers?t.muteAllMembers:void 0,muteExpiration:"number"==typeof t.muteExpiration?t.muteExpiration:void 0,remindType:D(t.remindType),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,updatedAt:"number"==typeof t.updatedAt?t.updatedAt:void 0,joinedAt:"number"==typeof t.joinedAt?t.joinedAt:void 0}:null;var t}).filter(e=>null!==e):[];this.items=t.slice(0,C),this.meta=(e=>{const t=O(e)?e:{};return{integrity:"synced"===t.integrity||"limited"===t.integrity||"incomplete"===t.integrity||"unknown"===t.integrity?t.integrity:"preview",limited:!0===t.limited,storageLimit:"number"==typeof t.storageLimit?t.storageLimit:C,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:A,source:"localPreview",lastSyncFinishedTs:"number"==typeof t.lastSyncFinishedTs?t.lastSyncFinishedTs:void 0,lastSuccessfulAt:"number"==typeof t.lastSuccessfulAt?t.lastSuccessfulAt:void 0,reason:"string"==typeof t.reason?t.reason:void 0}})(e.meta)}setSnapshot(e){this.items=e.items.map(e=>U(e)).slice(0,C),this.meta={...e.meta,source:"localPreview",storageLimit:C,serverLimit:A,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>U(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>U(e)),meta:{...this.meta,source:"localPreview"}}}},exports.normalizeGroupSharedFile=b;
|