easemob-websdk 5.1.2 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/im-sdk-web.iife.js +1 -1
- package/cache/cache-manager.d.ts +11 -3
- package/cache/cache-types.d.ts +15 -4
- package/chat-client.d.ts +23 -2
- package/chunks/chat-manager-BB7wYWYG.js +2 -0
- package/chunks/chat-manager-auF_3s3R.cjs +1 -0
- package/chunks/common-Cg-lTASK.cjs +1 -0
- package/chunks/common-gbNWJrBc.js +1 -0
- package/chunks/{event-system-B62vbKqG.js → event-system-DguqwFpc.js} +1 -1
- package/chunks/{group-user-info-resolver-B-dyr__b.cjs → group-user-info-resolver-BNwtC7dY.cjs} +1 -1
- package/chunks/{group-user-info-resolver-DMccCqez.js → group-user-info-resolver-rs5Fnr0l.js} +1 -1
- package/chunks/index-BUNbI8gf.cjs +1 -0
- package/chunks/index-BxMCMoWN.js +1 -0
- package/chunks/index-C7fO2X0x.cjs +1 -0
- package/chunks/index-C_EMU0-3.js +1 -0
- package/chunks/index-CsqE2tfH.js +1 -0
- package/chunks/index-DeJuR3uW.cjs +1 -0
- package/chunks/index-Dknccp9Q.js +1 -0
- package/chunks/index-P1vnLSK2.cjs +1 -0
- package/chunks/multibody-content-BHb-Au8Q.js +1 -0
- package/chunks/multibody-content-BmdQukoX.cjs +1 -0
- package/chunks/push-manager-BO3xq-7O.js +1 -0
- package/chunks/push-manager-DMI0G9v9.cjs +1 -0
- package/chunks/reflection-proto-codec-B1apL0ws.js +1 -0
- package/chunks/reflection-proto-codec-CYglS_mx.cjs +1 -0
- package/chunks/session-list-query-DMe2GZ4v.cjs +1 -0
- package/chunks/session-list-query-Inseic9m.js +1 -0
- package/chunks/{user-info-DH3aE1gm.cjs → user-info-B5St7axd.cjs} +1 -1
- package/chunks/{user-info-AlshAvdy.js → user-info-BkqJHgja.js} +1 -1
- package/core/index.d.ts +1 -1
- package/core/message/attachment-downloader.d.ts +4 -1
- package/core/message/message-sender.d.ts +19 -4
- package/core/message/prepare-text-translation.d.ts +7 -0
- package/core/session-list-sync/session-list-message-events.d.ts +9 -0
- package/index.cjs +1 -1
- package/index.d.ts +3 -2
- package/index.js +2 -2
- package/managers/chat/index.cjs +1 -1
- package/managers/chat/index.js +1 -1
- package/managers/chat-manager.d.ts +128 -7
- 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/message/combine-payload-codec.d.ts +2 -2
- package/message/combine-payload-file.d.ts +11 -0
- package/message/create-message.d.ts +16 -4
- package/message/create-multibody-message.d.ts +31 -0
- package/message/message-snapshot.d.ts +9 -0
- package/message/multibody-content.d.ts +35 -0
- package/message/translations.d.ts +7 -0
- package/package.json +1 -1
- package/platform/image/miniapp-image-processor.d.ts +10 -6
- package/protocol/msync/codec.d.ts +4 -21
- package/protocol/msync/message-identity.d.ts +2 -0
- package/protocol/msync/message-payload-decoder.d.ts +39 -0
- package/protocol/session-list/gateway.d.ts +8 -1
- package/protocol/session-list/payload-decoder.d.ts +13 -1
- package/types/chat-manager.d.ts +2 -2
- package/types/conversation.d.ts +28 -21
- package/types/index.d.ts +33 -9
- package/types/message-create.d.ts +130 -2
- package/upload/attachment-uploader.d.ts +8 -0
- package/utils/session-message-recipient.d.ts +11 -0
- package/validators/message-create.d.ts +25 -2
- package/chunks/chat-manager-BFd2Z4oY.cjs +0 -1
- package/chunks/chat-manager-CId_M_e5.js +0 -2
- package/chunks/common-BvlDAw4a.js +0 -1
- package/chunks/common-tHGz9VBk.cjs +0 -1
- package/chunks/index-BBFJYOM8.js +0 -1
- package/chunks/index-DJPAjXAp.cjs +0 -1
- package/chunks/index-DtWkVcfb.cjs +0 -1
- package/chunks/index-l_BUKi77.js +0 -1
- package/chunks/reflection-proto-codec-7r8Sei3y.js +0 -1
- package/chunks/reflection-proto-codec-CwrIKT1L.cjs +0 -1
- package/chunks/session-list-query-Cvr6rlme.js +0 -1
- package/chunks/session-list-query-Dslj2k3t.cjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const e={VALIDATION_REQUIRED:110,VALIDATION_INVALID_FORMAT:110,VALIDATION_UNKNOWN:110,AUTH_ALREADY_LOGIN:200,AUTH_NOT_LOGIN:201,AUTH_UNAUTHORIZED:202,AUTH_FORBIDDEN:210,AUTH_TOKEN_EXPIRED:108,AUTH_BIND_ANOTHER_DEVICE:213,AUTH_LOGIN_TOO_MANY_DEVICES:214,AUTH_USER_MUTED:215,CONNECTION_TIMEOUT:301,CONNECTION_LOGIN_TIMEOUT:301,CONNECTION_WEBSOCKET_ERROR:300,CONNECTION_NOT_CREATED:1,CONNECTION_CLOSED_BEFORE_READY:300,CONNECTION_CANCELLED:1,CONNECTION_PROVISION_TIMEOUT:301,CONNECTION_PROVISION_REJECTED:202,CONNECTION_PROVISION_CLOSED:300,CONNECTION_DNSLIST_FAILED:304,STORAGE_OPERATION_FAILED:3,MESSAGE_NOT_CONNECTED:300,MESSAGE_ACK_TIMEOUT:301,MESSAGE_SEND_FAILED:303,MESSAGE_SENDER_DESTROYED:1,MESSAGE_ENCODE_FAILED:500,MESSAGE_DECODE_FAILED:500,MESSAGE_ACK_MISSING:301,MESSAGE_BLOCKED_BY_RECIPIENT:222,OPERATION_UNSUPPORTED:111,SERVER_BUSY:302,ATTACHMENT_NOT_FOUND:400,ATTACHMENT_INVALID:401,ATTACHMENT_EXPIRED:407,MESSAGE_INCLUDE_ILLEGAL_CONTENT:501,MESSAGE_SEND_TRAFFIC_LIMIT:502,MESSAGE_RECALL_TIME_LIMIT:504,SERVICE_NOT_ENABLED:505,MESSAGE_EXPIRED:506,MESSAGE_ILLEGAL_WHITELIST:507,MESSAGE_EXTERNAL_LOGIC_BLOCKED:508,MESSAGE_CURRENT_LIMITING:509,MESSAGE_SIZE_LIMIT:510,MESSAGE_EDIT_FAILED:511,INVALID_CONVERSATION:107,USER_LOGIN_ANOTHER_DEVICE:206,USER_REMOVED:207,USER_KICKED_BY_CHANGE_PASSWORD:216,USER_KICKED_BY_OTHER_DEVICE:217,USER_ALREADY_LOGIN_ANOTHER:218,USER_MUTED_BY_ADMIN:219,USER_DEVICE_CHANGED:220,USER_NOT_ON_ROSTER:221,SERVER_SERVING_DISABLED:305,FILE_DOWNLOAD_FAILED:403,FILE_TOO_LARGE:405,FILE_CONTENT_IMPROPER:406,THIRD_MODERATION_FAILED:1200,THIRD_DEFAULT_FAILED:1299,STREAM_SEND_NOT_SUPPORTED:303,STREAM_CHUNK_INVALID:500,STREAM_TIMEOUT_BY_SERVER:500,STREAM_STATE_CONFLICT:500,COMBINE_INVALID_INPUT:110,COMBINE_LEVEL_EXCEEDED:4,COMBINE_ITEM_LIMIT_EXCEEDED:4,COMBINE_ENCODE_FAILED:500,COMBINE_UPLOAD_FAILED:402,COMBINE_DOWNLOAD_FAILED:2,COMBINE_PARSE_FAILED:500,REST_NETWORK_ERROR:2,REST_TIMEOUT:301,REST_HTTP_ERROR:303,REST_BUSINESS_UNKNOWN:303,PUSH_TOKEN_UPLOAD_FAILED:1500,PUSH_SILENT_MODE_OPERATION_FAILED:1501,PUSH_LANGUAGE_OPERATION_FAILED:1502,USER_INFO_SUBSCRIPTION_LIMIT_EXCEEDED:1600,USER_INFO_SUBSCRIPTION_TARGET_LIMIT_EXCEEDED:1601,USERINFO_USERCOUNT_EXCEED:900,USERINFO_DATALENGTH_EXCEED:901,CONTACT_ADD_USER_NOT_FOUND:204,CONTACT_ADD_ALREADY_FRIEND:1e3,CONTACT_ADD_BLOCKED_BY_USER:210,CONTACT_SET_REMARK_NOT_FRIEND:223,CONTACT_REACH_LIMIT:1001,CONTACT_REACH_LIMIT_PEER:1002,CONTACT_BLOCKLIST_USER_NOT_FOUND:204,GROUP_INVALID_ID:600,GROUP_ALREADY_JOINED:601,GROUP_NOT_JOINED:602,GROUP_PERMISSION_DENIED:603,GROUP_MEMBERS_FULL:604,GROUP_SHARED_FILE_INVALID_ID:605,GROUP_NOT_EXIST:606,GROUP_DISABLED:607,GROUP_NAME_VIOLATION:608,GROUP_MEMBER_ATTRIBUTES_REACH_LIMIT:609,GROUP_MEMBER_ATTRIBUTES_UPDATE_FAILED:610,GROUP_MEMBER_ATTRIBUTES_KEY_REACH_LIMIT:611,GROUP_MEMBER_ATTRIBUTES_VALUE_REACH_LIMIT:612,GROUP_USER_IN_BLOCKLIST:613,CHATROOM_INVALID_ID:700,CHATROOM_NOT_JOINED:702,CHATROOM_PERMISSION_DENIED:703,CHATROOM_MEMBERS_FULL:704,CHATROOM_NOT_EXIST:705,CHATROOM_OWNER_NOT_ALLOW_LEAVE:706,CHATROOM_USER_IN_BLOCKLIST:707,CONTACT_SYNC_METADATA_FAILED:1700,CONTACT_SYNC_SOCKET_FAILED:1701,CONTACT_SYNC_CURSOR_INVALID:1702,CONTACT_SYNC_PROTO_DECODE_FAILED:1703,CONTACT_SYNC_CANCELLED:1704,SESSION_LIST_SOCKET_FAILED:300,SESSION_LIST_PROTO_DECODE_FAILED:500,SESSION_LIST_REQUEST_INVALID:110,SESSION_LIST_FETCH_FAILED:303,SESSION_LIST_SERVICE_DISABLED:305,SESSION_LIST_CANCELLED:1,PRESENCE_PARAM_LENGTH_EXCEED:1100,PRESENCE_CANNOT_SUBSCRIBE_YOURSELF:1101,TRANSLATE_PARAM_INVALID:1110,TRANSLATE_SERVICE_NOT_ENABLED:1111,TRANSLATE_USAGE_LIMIT:1112,TRANSLATE_FAILED:1113,VOICE_TO_TEXT_FILE_INVALID:407,VOICE_TO_TEXT_FILE_DURATION_TOO_LONG:408,VOICE_TO_TEXT_FAILED:409,VOICE_TO_TEXT_FILE_NOT_FOUND:410,VOICE_TO_TEXT_FILE_TOO_LARGE:411,REACTION_REACH_LIMIT:1300,REACTION_ALREADY_OPERATED:1301,REACTION_OPERATION_ILLEGAL:1302,UPLOAD_REQUIRED_FIELD_MISSING:110,UPLOAD_INVALID_APPKEY:100,UPLOAD_SIZE_EXCEEDED:405,UPLOAD_REQUEST_FAILED:402,UPLOAD_TIMEOUT:301,UPLOAD_ABORTED:1,SERVICE_LIMIT_EXCEEDED:4,UNKNOWN:1},t="[REDACTED]",o=e=>{if(!e)return"";const o=e.includes("?"),r=e.includes("#");try{return((e,o,r)=>(e.username&&(e.username=t),e.password&&(e.password=t),e.search=o?`?${t}`:"",e.hash=r?`#${t}`:"",e.toString()))(new URL(e),o,r)}catch{const o=[e.indexOf("?"),e.indexOf("#")].filter(e=>e>=0).sort((e,t)=>e-t)[0];return void 0===o?"[invalid-url]":`${e.slice(0,o)}?${t}`}},r=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>"url"===e.toLowerCase()&&"string"==typeof t?[e,o(t)]:[e,t]));class s extends Error{constructor(t,o=e.UNKNOWN,i){super(t),this.name="SDKError",this.code=o,this.details=i?.details?r(i.details):void 0,Error.captureStackTrace&&Error.captureStackTrace(this,s)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class i extends s{constructor(t,o){super(t,o?.code??e.AUTH_UNAUTHORIZED,o),this.name="AuthenticationError"}}class n extends s{constructor(t,o){super(t,o?.code??e.VALIDATION_UNKNOWN,o),this.name="ValidationError"}}class a extends s{constructor(t,o){super(t,o?.code??e.REST_NETWORK_ERROR,o),this.name="RestTransportError"}}class p extends s{constructor(t,o){super(t,o?.code??e.REST_BUSINESS_UNKNOWN,o),this.name="RestBusinessError"}}class E extends s{constructor(t,o){super(t,o?.code??e.UPLOAD_REQUEST_FAILED,o),this.name="UploadError"}}const 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}},d=e=>{const t=e.file,o=e.sourceMeta,r=t.name||(o?O(o,["name","fileName","filename"]):void 0),s=e.file.type||(o?O(o,["type","mimeType","filetype"]):void 0),i=e.file.size||(o?((e,t)=>{for(const o of t){const t=e[o];if("number"==typeof t&&Number.isFinite(t))return t}})(o,["size","fileSize","fileLength"]):void 0),n=l({fileName:r,fileType:s,fileSize:i,fallbackName:e.fallbackName,fallbackMimeType:e.fallbackMimeType,fallbackSize:e.fallbackSize});return{source:{sourceType:"web-file",file:e.file,name:n.fileName,mimeType:n.fileType,size:n.fileSize},fileName:n.fileName,fileType:n.fileType,fileSize:n.fileSize,webFile:e.file}},l=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),R=e=>{const{file:t,fallbackName:o,fallbackMimeType:r,fallbackSize:s}=e,i=(e=>{if(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 d({file:i,fallbackName:o,fallbackMimeType:r,fallbackSize:s,sourceMeta:"object"==typeof t&&null!==t?t:void 0});if((e=>"object"==typeof e&&null!==e&&"path"in e)(t)){const e=_(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 n=l({fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"web-file",name:n.fileName,mimeType:n.fileType,size:n.fileSize},fileName:n.fileName,fileType:n.fileType,fileSize:n.fileSize}},I="CHAT",A="GROUP",N="ROOM",m=/^http:\/\/(?:usr|tmp|store)(?:\/|$)/i,S="original",h="large",f=e=>/^https?:\/\//i.test(e)&&!m.test(e),C=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]}},y=(e,t)=>D(e,{size:t}),M=e=>{try{return decodeURIComponent(e)}catch{return e}},D=(e,t)=>{const[o="",r]=e.split("#",2),[s,i=""]=o.split("?",2),n=i.split("&").filter(Boolean);return Object.entries(t).forEach(([e,t])=>{const o=encodeURIComponent(e),r=n.filter(t=>{const[r=""]=t.split("=",2);return r!==o&&M(r)!==e});n.length=0,n.push(...r),void 0!==t&&n.push(`${o}=${encodeURIComponent(String(t))}`)}),`${s}${n.length>0?`?${n.join("&")}`:""}${r?`#${r}`:""}`},U=(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=M(t),s=M(o);return"size"!==r||!["big","large","thumbnail","small"].includes(s)}).join("&");return`${r}${i?`?${i}`:""}${o?`#${o}`:""}`})(e);return{originalImageUrl:o,bigImageUrl:y(o,"large"),thumbnailUrl:y(o,"small")}},L=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 L(this.chunkDelayMs)}}finally{this.reporting=!1}}}async reportChunk(e){if(!this.canReport())return!1;const{restBaseUrl:t,appKey:o,userId:r,token:s,resource:i,requestAdapter:n}=this.context;if(!(t&&o&&r&&s&&n))return!1;let a="",p="";try{const e=C(o);a=e.orgName,p=e.appName}catch{return!1}const E=`${t}/${a}/${p}/sdk/users/${r}/client/logs`,T={resource:i??"webim",logContent:e};try{const e=await n.request({url:E,method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json"},body: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}}},P="[MASKED]",b=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),G=e=>!!e&&b.has((e=>e.toLowerCase())(e)),H=(e,t,o)=>{const r=o??new WeakSet;if("string"==typeof e)return((e,t)=>G(t)?P: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=>H(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]=P:t[o]=H(s,o,r);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},w="undefined"!=typeof document;let x=null,B=!1;const F={DEBUG:0,WARN:1,ERROR:2};class v{constructor(e="WARN"){this.consoleEnabled=!0,this.level=e}setLevel(e){this.level=e}setConsoleEnabled(e){this.consoleEnabled=e}shouldLog(e){return F[e]>=F[this.level]}emit(e,t,o){const r=(e=>{const t=new WeakSet;return e.map(e=>H(e,void 0,t))})(o),s=((e,t,o)=>({timestamp:(new Date).toISOString(),level:e,message:t,args:o}))(e,t,r);if(g.append(s),this.consoleEnabled){const o=new Date,s=`[Chat][${e}][${`${String(o.getHours()).padStart(2,"0")}:${String(o.getMinutes()).padStart(2,"0")}:${String(o.getSeconds()).padStart(2,"0")}.${String(o.getMilliseconds()).padStart(3,"0")}`}]`;w?console.log(`%c${s}`,"color: rgb(0, 157, 255); font-weight: bold",t,...r):console.log(s,t,...r)}const i=x;i&&!B&&Promise.resolve().then(()=>{if(i===x){B=!0;try{i(s)}catch{}finally{B=!1}}})}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 k=new v;const K={debug:(e,...t)=>k.debug(e,...t),warn:(e,...t)=>k.warn(e,...t),error:(e,...t)=>k.error(e,...t)},V={INIT:"init",REQUEST:"request",UPLOAD:"upload",SOCKET:"socket",PROTO:"proto",RUNTIME:"runtime",STORAGE:"storage"},q={INIT_FAILED:"PLATFORM_INIT_FAILED",MISSING_CAPABILITY:"PLATFORM_MISSING_CAPABILITY",REQUEST_FAILED:"PLATFORM_REQUEST_FAILED",UPLOAD_FAILED:"PLATFORM_UPLOAD_FAILED",SOCKET_FAILED:"PLATFORM_SOCKET_FAILED",PROTO_FAILED:"PLATFORM_PROTO_FAILED"},W=(e,t)=>{const o=new Error(e);return o.name="PlatformAdapterError",o.code=t.code,o.stage=t.stage,o.retryable=t.retryable,t.details&&(o.details=r(t.details)),o},$=["__uniConfig","skipWaiting","registration","navigator","process","window","document","localStorage","fetch","WebSocket","XMLHttpRequest","FormData","TextEncoder","TextDecoder","crypto"],Y=e=>{if(e)return e;return((e,t)=>{if(!e)return t;if(0===Object.keys(t).length)return e;const o={},r=e;for(const s of $)try{const e=r[s];void 0!==e&&(o[s]=e)}catch{}for(const s of Object.keys(t))o[s]=t[s];return o})("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0,{..."undefined"!=typeof wx?{wx:wx}:{},..."undefined"!=typeof qq?{qq:qq}:{},..."undefined"!=typeof tt?{tt:tt}:{},..."undefined"!=typeof swan?{swan:swan}:{},..."undefined"!=typeof my?{my:my}:{},..."undefined"!=typeof dd?{dd:dd}:{},..."undefined"!=typeof jd?{jd:jd}:{},..."undefined"!=typeof ks?{ks:ks}:{},..."undefined"!=typeof uni?{uni:uni}:{}})},j=e=>{const t={};if(!e)return t;if("function"==typeof e.forEach)return e.forEach((e,o)=>{t[o]=e}),t;const o=e.get?.("content-type");return o&&(t["content-type"]=o),t},z=async(e,t)=>{const o=e;if("function"!=typeof o.text){if("function"!=typeof o.json)return"";const e=await o.json();return t?e:JSON.stringify(e)}const r=await o.text();if(!t||0===r.length)return r;try{return JSON.parse(r)}catch{return r}},X=e=>{const t=e?.fetchImpl;if("function"==typeof t)return{async request(o){const r=o.method??"GET",s={...o.headers??{}},i=new AbortController,n=o.timeoutMs??e?.timeoutMs??15e3;let a=!1;const p=()=>i.abort(o.signal?.reason);o.signal?.aborted?p():o.signal?.addEventListener("abort",p,{once:!0});const E=setTimeout(()=>{a=!0,i.abort()},n),T=((e,t,o)=>{if(e.body instanceof Uint8Array)return new Uint8Array(e.body).buffer;if("string"==typeof e.body)return e.body;if(e.body&&"GET"!==o)return Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),JSON.stringify(e.body)})(o,s,r);try{const e=await t(o.url,{method:r,headers:s,body:T,signal:i.signal});let n;if("arraybuffer"===o.responseType)n=await e.arrayBuffer();else if("text"===o.responseType)n=await e.text();else if("json"===o.responseType)n=await z(e,!0);else{const t=e.headers.get("content-type")??"";n=await z(e,t.includes("application/json"))}return{status:e.status,statusText:e.statusText,headers:j(e.headers),data:n}}catch(c){const e=((e,t,o)=>t?"timeout":o?.aborted||e instanceof Error&&"AbortError"===e.name?"abort":"network")(c,a,o.signal);throw W("Request adapter execution failed.",{code:q.REQUEST_FAILED,stage:V.REQUEST,retryable:"abort"!==e,details:{url:o.url,method:r,reason:e,cause:c instanceof Error?c.message:String(c)}})}finally{clearTimeout(E),o.signal?.removeEventListener("abort",p)}}}},Q=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,J="X-Request-Id",Z="direct";class ee{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 te{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 oe={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},re=()=>{const e=Y(),t=e.crypto?.randomUUID;return("function"==typeof t?t.call(e.crypto):void 0)??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class se{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??re;const t=new te({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 ee({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:oe[e.trim().toLowerCase()]??-1)(e)}applyDnsSwitch(e){if(this.session){if("true"===e)return this.currentState="enabled",void this.queue.enable();this.currentState="disabled",this.queue.clear()}else this.currentState="disabled"}startOperation(e){const t=this.session?.sessionId;if(!t||"disabled"===this.currentState)return this.createNoopOperation();const o=`opr_${this.randomId()}`,r=this.now();let s=!1,i=!1,n=`req_${this.randomId()}`,a=0,p="";const E=()=>!s&&!i&&this.session?.sessionId===t,T=(t,r,s,i,n)=>{E()&&(a=n.success?0:n.code,p=n.success?"":n.description??"",this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:o,requestid:r,operationName:e.operationName,operationType:e.operationType,requestName:t.requestName??e.operationName,subrequestid:String(s),requestMethod:t.method??"",requestUrl:t.url??"",requestElapse:Math.max(0,this.now()-i),code:n.code,codeDesc:n.description??"",isLastApi:0,isSuccess:n.success?1:0,accessChannel:this.session?.accessChannel??Z,msgId:e.msgId,messageType:e.messageType,resultCount:n.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={})=>(n=`req_${this.randomId()}`,c(e,n,1,{next:1})),finish:t=>{E()&&(s=!0,this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:o,requestid:n,operationName:e.operationName,operationType:e.operationType,requestName:"",subrequestid:"0",requestMethod:"",requestUrl:"",requestElapse:Math.max(0,this.now()-r),code:t.success?0:t.code??a,codeDesc:t.success?"":t.description??p,isLastApi:1,isSuccess:t.success?1:0,accessChannel:this.session?.accessChannel??Z,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 ie;const ne=e=>{if("disabled"!==ie?.state)return ie?.startOperation(e)},ae=()=>{const e=globalThis;return"function"==typeof e.fetch?e.fetch:void 0},pe=()=>X({fetchImpl:ae()})??{request:e=>Promise.reject(W("Request capability is missing for current platform.",{code:q.MISSING_CAPABILITY,stage:V.REQUEST,retryable:!1,details:{capability:"request"}}))},Ee=e=>e??pe(),Te=(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 ce(e,t,o){if(!e)return;const r=o&&"object"==typeof o?o:{},s="string"==typeof r.error?r.error:void 0,i=(e=>"string"==typeof e.error_code||"number"==typeof e.error_code?e.error_code:"string"==typeof e.errorCode||"number"==typeof e.errorCode?e.errorCode:"string"==typeof e.error||"number"==typeof e.error?e.error:"string"==typeof e.code||"number"==typeof e.code?e.code:void 0)(r),n="string"==typeof r.error_description?r.error_description:"string"==typeof r.message?r.message:"string"==typeof r.desc?r.desc:void 0,a=(e,t=!1)=>{const o=(e,o,r)=>({reasonKey:e,entry:o,matchedBy:t?"common":r});if(s&&e[s])return o(s,e[s],"key");for(const[s,i]of Object.entries(e))if(Te(i,r))return o(s,i,"field");if(void 0!==i)for(const[r,s]of Object.entries(e)){if(s.code===i||s.canonicalCode===i)return o(r,s,"code");if(Array.isArray(s.aliases)&&s.aliases.includes(String(i)))return o(r,s,"alias")}if(n)for(const[r,s]of Object.entries(e))if(Array.isArray(s.aliases)&&s.aliases.includes(n))return o(r,s,"alias")},p=t?e.apis[t]:void 0,E=p?a(p.errors):void 0;if(E)return E;for(const T of Object.values(e.common)){const e=a(T.errors,!0);if(e)return e}}function _e(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 ue={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"}},Oe=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase();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},LOGIN_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=S,exports.LOGIN_TIMEOUT_DEFAULT=3e4,exports.LOGIN_TIMEOUT_MAX=12e4,exports.LOGIN_TIMEOUT_MIN=5e3,exports.MANAGER_SESSION_ENDING_TIMEOUT=6e3,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.NATIVE_PUSH_BIND_MAX_RETRIES=2,exports.NATIVE_PUSH_BIND_REQUEST_TIMEOUT=5e3,exports.NATIVE_PUSH_BIND_RETRY_DELAYS=[1e3,2e3],exports.NATIVE_PUSH_REMOVE_MAX_RETRIES=1,exports.NATIVE_PUSH_REMOVE_REQUEST_TIMEOUT=2500,exports.NATIVE_PUSH_REMOVE_RETRY_DELAY=500,exports.NetworkError=class extends s{constructor(t,o){super(t,o?.code??e.REST_NETWORK_ERROR,o),this.name="NetworkError"}},exports.PLATFORM_ERROR_CODE=q,exports.PLATFORM_ERROR_STAGE=V,exports.PROVISION_TIMEOUT=1e4,exports.RECONNECT_BACKOFF_MULTIPLIER=2,exports.RECONNECT_INITIAL_DELAY=1e3,exports.RECONNECT_MAX_DELAY=6e4,exports.REQUEST_ID_HEADER=J,exports.REQUEST_TIMEOUT=15e3,exports.RUNTIME_PLATFORMS={WEB:"web",WECHAT_MINIAPP:"wechat-miniapp",QQ_MINIAPP:"qq-miniapp",TOUTIAO_MINIAPP:"toutiao-miniapp",BAIDU_MINIAPP:"baidu-miniapp",ALIPAY_MINIAPP:"alipay-miniapp",DINGTALK_MINIAPP:"dingtalk-miniapp",LARK_MINIAPP:"lark-miniapp",KUAISHOU_MINIAPP:"kuaishou-miniapp",JD_MINIAPP:"jd-miniapp",MINIAPP_360:"360-miniapp",HARMONY_MINIAPP:"harmony-miniapp",QUICKAPP:"quickapp",UNIAPP:"uniapp",REACT_NATIVE:"react-native",ELECTRON_RENDERER:"electron-renderer",ELECTRON_MAIN:"electron-main",UNKNOWN:"unknown"},exports.RestBusinessError=p,exports.RestClient=class{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=Ee(t?.requestAdapter),this.includeRequestId=t?.includeRequestId??!1,this.defaultHeaders={Accept:"application/json",...t?.headers}}sanitizeUrl(e){try{const t=new URL(e),o=t.searchParams;for(const e of o.keys())o.set(e,"***");const r=o.toString(),s=r?`?${r}`:"";return`${t.origin}${t.pathname}${s}`}catch{return e.split("?")[0]??e}}setAuthToken(e){this.defaultHeaders.Authorization=`Bearer ${e}`}removeAuthToken(){delete this.defaultHeaders.Authorization}buildHttpStatusFallbackError(t,o,r,s){const a={...o.operation?{api:o.operation}:{},url:o.url,method:o.method,httpStatus:t,serverCode:r,serverMessage:s,mapped:!1};if(400===t)return new n("Invalid request parameters",{code:e.VALIDATION_UNKNOWN,details:{...a,canonicalCode:e.VALIDATION_UNKNOWN}});if(401===t){const t=[r,s].some(e=>"string"==typeof e&&/token[ _-]?(?:has[ _-]?)?expired/i.test(e)),o=t?e.AUTH_TOKEN_EXPIRED:e.AUTH_UNAUTHORIZED;return new i(t?"Authentication token expired":"Authentication failed",{code:o,details:{...a,reasonKey:t?"token_expired":"unauthorized",canonicalCode:o}})}return 403===t?new i("Access forbidden",{code:e.AUTH_FORBIDDEN,details:{...a,canonicalCode:e.AUTH_FORBIDDEN}}):429===t?new p("REST rate limit exceeded",{code:e.SERVICE_LIMIT_EXCEEDED,details:{...a,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:e.SERVICE_LIMIT_EXCEEDED}}):t>=500?new p("REST business error: request failed",{code:e.REST_BUSINESS_UNKNOWN,details:{...a,retryable:!0,reasonKey:"server_unknown_error",canonicalCode:e.REST_BUSINESS_UNKNOWN}}):void 0}async request(t,o={}){const r=`${this.baseUrl}${t}`,i=o.method??"GET",n=Date.now(),p=this.sanitizeUrl(r);K.debug("REST request",{method:i,url:p,operation:o.operation});const E=o.operation?(e=>{const t=ue[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_${Oe(e)}`,operationType:o}})(o.operation):void 0,T=E?ne(E):void 0,c=T?.startRequest({requestName:E?.operationName,method:i,url:r});let _=0;const u={...this.defaultHeaders,...o.headers};if(this.includeRequestId&&(u[J]=Q()),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"):e||(u["Content-Type"]="application/json")}else if("GET"===i)for(const e of Object.keys(u))"content-type"===e.toLowerCase()&&delete u[e];try{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()-n;(e.status<200||e.status>=300)&&(K.warn("REST response error",{method:i,url:p,status:e.status,duration:s}),this.handleErrorPayload(e.status,e.statusText??"",t,{operation:o.operation,url:r,method:i})),K.debug("REST response",{method:i,url:p,status:e.status,duration:s});const a=(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}})(t);return c?.finish({code:e.status,success:!0,resultCount:a}),T?.finish({code:0,success:!0,resultCount:a}),t}catch(O){const t=0!==_?_:O instanceof s?O.code:-1,n=O instanceof Error?O.message:String(O);if(c?.finish({code:t,success:!1,description:n}),T?.finish({code:t,success:!1,description:n}),O instanceof s)throw O;const E=(e=>{if(!e||"object"!=typeof e)return;const t=e.details;if(!t||"object"!=typeof t)return;const o=t.reason;return"abort"===o||"network"===o||"timeout"===o?o:void 0})(O);if(O instanceof Error&&"AbortError"===O.name||"timeout"===E)throw K.warn("REST request timeout",{method:i,url:p,timeout:o.timeout??this.timeout}),new a(`Request timeout: ${r}`,{code:e.REST_TIMEOUT,details:{url:r,method:i,timeout:o.timeout??this.timeout}});throw K.warn("REST request failed",{method:i,url:p}),new a(`Request failed: ${r}`,{code:e.REST_NETWORK_ERROR,details:{url:r,method:i,...E?{reason:E}:{}}})}}handleErrorPayload(t,o,r,s){const i=r&&"object"==typeof r?r:{},n=((e,t)=>{if(!e.error||"object"!=typeof e.error||Array.isArray(e.error))return;const o=e.error,r=o.code;if("number"!=typeof r&&"string"!=typeof r)return;const s=String(r);return/^\d{7}$/.test(s)&&Number(s.slice(0,3))===t?o:void 0})(i,t),p=n?{...i,code:n.code,message:n.message}:r,E=ce(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 n?.code||"string"==typeof n?.code?n.code:void 0,_="string"==typeof i.message?i.message:"string"==typeof i.error_description?i.error_description:"string"==typeof i.desc?i.desc:"string"==typeof n?.message?n.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||"string"==typeof i.desc);if(s.operation&&E)throw _e({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 _e({apiName:s.operation,serverCode:c,serverMessage:_,httpStatus:t,mapped:!1,reasonKey:T});throw new a(`HTTP ${t}: ${o}`,{code:e.REST_HTTP_ERROR,details:{url:s.url,method:s.method,httpStatus:t}})}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,o){return this.request(e,{...o,method:"POST",body:t})}put(e,t,o){return this.request(e,{...o,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}patch(e,t,o){return this.request(e,{...o,method:"PATCH",body:t})}},exports.RestTransportError=a,exports.SDKError=s,exports.SEND_CONNECTION_RECOVERY_TIMEOUT=1e4,exports.SESSION_LIST_SYNC_OVERLAP_MS=2e4,exports.SOCKET_READY_STATE={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},exports.SYNC_WEBSOCKET_COMPLETE_CLOSE_DELAY=0,exports.SYNC_WEBSOCKET_CONNECT_TIMEOUT=5e3,exports.SYNC_WEBSOCKET_IDLE_TIMEOUT=1e4,exports.SYNC_WEBSOCKET_RETRY_BACKOFF_MULTIPLIER=2,exports.SYNC_WEBSOCKET_RETRY_INITIAL_DELAY=1e3,exports.SYNC_WEBSOCKET_RETRY_MAX_DELAY=5e3,exports.StorageError=class extends s{constructor(t,o){super(t,o?.code??e.STORAGE_OPERATION_FAILED,o),this.name="StorageError"}},exports.UPLOAD_TIMEOUT=3e5,exports.USER_INFO_HYDRATION_BATCH_SIZE=20,exports.USER_INFO_HYDRATION_MAX_CONCURRENCY=3,exports.USER_INFO_HYDRATION_MAX_RETRIES=1,exports.USER_INFO_HYDRATION_WINDOW_MS=7e3,exports.UploadError=E,exports.ValidationError=n,exports.appendAttachUrlParams=(e,t)=>{if(!e)return"";const o={};return e.includes("em-redirect")||(o["em-redirect"]="true"),t&&!e.includes("share-secret=")&&(o["share-secret"]=t),0===Object.keys(o).length?e:D(e,o)},exports.appendUrlQueryParams=D,exports.applyDataReportDnsSwitch=e=>{ie?.applyDnsSwitch(e)},exports.buildAttachmentPrecheckDecision=e=>{const t=(o=e.messageType,r=e.imageType,"image"!==o?"attachment":r===S?"image-origin":"image-big");var o,r;const s=(e=>"image-origin"===e?204800:1048576)(t),i=e.fileSize>s;return{shouldPrecheck:i,thresholdType:t,thresholdBytes:s,actualBytes:e.fileSize,reason:i?"threshold-exceeded":"below-threshold"}},exports.buildUploadResult=t=>{const o=t.response.entities?.[0];if(!o?.uuid)throw new E("Upload response missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t.response}});const r=o["share-secret"],s=o["file-metadata"]??{},i="number"==typeof s["content-length"]?s["content-length"]:t.fallbackSize,n="string"==typeof s["content-type"]?s["content-type"]:t.fileType,a=`${t.restBaseUrl}/${t.orgName}/${t.appName}/chatfiles/${o.uuid}`;if("image"===t.messageType){const e=(t.imageType??h)===S;return{...U(a,{deriveVariants:!t.useCustomAttachmentUpload}),isOriginalImage:e,secret:r,fileLength:i,filetype:n,filename:t.fileName,width:t.width,height:t.height}}const p="video"===t.messageType?`${a}?vframe=true`:void 0;return{url:a,secret:r,fileLength:i,filetype:n,filename:t.fileName,thumbnailUrl:p}},exports.createPlatformError=W,exports.createRestBusinessError=_e,exports.createTraceId=Q,exports.createWebRequestAdapter=X,exports.deriveImageUrls=U,exports.fromProtocolImageType=e=>2===e?h:S,exports.getRuntimeGlobal=Y,exports.installDataReporter=e=>(ie?.reset(),ie=new se(e),ie),exports.isRemoteUrl=f,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=K,exports.mergeRuntimeErrorMaps=(...e)=>{const t={},o={};for(const r of e)Object.assign(t,r.common),Object.assign(o,r.apis);return{common:t,apis:o}},exports.normalizeAttachmentFile=(t,o)=>{if(!t)throw new E("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"file missing"}});const r=("number"==typeof o.fileLength?o.fileLength:void 0)??("fileSize"in o&&"number"==typeof o.fileSize?o.fileSize:void 0),s=R({file:t,fallbackName:o.filename,fallbackMimeType:o.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new E("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"web file missing"}});return s},exports.normalizeUploadSource=R,exports.parseAppKey=C,exports.parseAttachmentPrecheckResult=t=>{const o=t.entities?.[0],r=!0===o?.exists,s="string"==typeof o?.uuid&&o.uuid.length>0?o.uuid:void 0,i=o,n=i?.["exists-type"]??i?.existsType,a="origin"===n?S:n===h||n===S?n:void 0,p="string"==typeof o?.["share-secret"]?o["share-secret"]:void 0;if(r&&!s)throw new E("Upload precheck response missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t}});return{uuid:s,exists:r,existsType:a,shareSecret:p,hit:(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=()=>{ie?.reset(),ie=void 0},exports.resolveApiBusinessError=ce,exports.resolveImageSendPolicy=e=>e.isGif?{resolvedImageType:S,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:S,reason:"explicit-original"}:{resolvedImageType:h,reason:"default-large"},exports.resolveRequestAdapter=Ee,exports.sanitizeErrorUrl=o,exports.setConsoleLogEnabled=function(e){k instanceof v&&k.setConsoleEnabled(e)},exports.setLogEntrySink=function(e){x=e},exports.setLogLevel=function(e){k instanceof v&&k.setLevel(e)},exports.setLogReportInterval=function(e){g.updateReportInterval(e)},exports.setLogReportState=function(e){g.setState(e)},exports.shouldUploadByUrl=(e,t)=>!!t||(!e||!f(e)),exports.startDataReportOperation=ne,exports.startDataReportSession=e=>ie?.startSession(e),exports.stopLogReporter=function(){g.stop()},exports.toProtocolImageType=e=>e===S?1:2,exports.toUploadChatType=e=>"singleChat"===e?I:"groupChat"===e?A:N,exports.toUploadImageType=e=>e===S?"origin":"large",exports.updateDataReportNetworkType=e=>{ie?.updateNetworkType(e)},exports.updateDataReportSession=e=>{ie?.updateSession(e)},exports.updateLogReportContext=function(e){g.updateContext(e)};
|
|
@@ -0,0 +1 @@
|
|
|
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_LOGIN_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 p extends s{constructor(t,o){super(t,o?.code??e.VALIDATION_UNKNOWN,o),this.name="ValidationError"}}class E 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 l 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 _=15e3,R=1e4,m=15e3,h=3e5,N=6e4,I=3e5,A=1e4,f=1e4,S=3e4,y=5e3,C=12e4,M=3e4,g=6e4,D=1e3,U=6e4,L=2,b=5e3,P=1e4,G=1e3,H=5e3,w=2,v=0,F=2e4,B=7e3,k=20,K=3,q=1,V=7e3,$=1e3,x=50,j=5,z=5e3,W=2,Y=[1e3,2e3],X=2500,J=1,Q=500,Z=6e3,ee={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"},te=e=>"undefined"!=typeof Blob&&e instanceof Blob,oe=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),o=t.length>0?t[t.length-1]:void 0;if(o)return o},re=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const o=e.slice(t+1).toLowerCase();return ee[o]},se=(e,t)=>{for(const o of t){const t=e[o];if("string"==typeof t&&t.length>0)return t}},ie=e=>{const t=e.file,o=e.sourceMeta,r=t.name||(o?se(o,["name","fileName","filename"]):void 0),s=e.file.type||(o?se(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=ae({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}},ae=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),ne=e=>{const{file:t,fallbackName:o,fallbackMimeType:r,fallbackSize:s}=e,i=(e=>{if(te(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(te(e))return e}})(t);if(i)return ie({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=oe(t.path),i=ae({fileName:t.name??e,fileType:t.type??re(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=oe(t.uri),i=ae({fileName:t.name??e,fileType:t.type??re(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=ae({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}},pe=5242880,Ee=5242880,ce=4,Te="CHAT",ue="GROUP",de="ROOM",le=/^http:\/\/(?:usr|tmp|store)(?:\/|$)/i,Oe="original",_e="large",Re=e=>/^https?:\/\//i.test(e)&&!le.test(e),me=(e,t)=>!!t||(!e||!Re(e)),he=t=>{const o=t.split("#");if(2!==o.length||!o[0]||!o[1])throw new l("Invalid appKey for upload",{code:e.UPLOAD_INVALID_APPKEY,details:{appKey:t}});return{orgName:o[0],appName:o[1]}},Ne=e=>"singleChat"===e?Te:"groupChat"===e?ue:de,Ie=(e,t)=>fe(e,{size:t}),Ae=e=>{try{return decodeURIComponent(e)}catch{return e}},fe=(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&&Ae(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}`:""}`},Se=(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:fe(e,o)},ye=e=>e.isGif?{resolvedImageType:Oe,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:Oe,reason:"explicit-original"}:{resolvedImageType:_e,reason:"default-large"},Ce=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"}},Me=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===_e||a===Oe?a:void 0,p="string"==typeof o?.["share-secret"]?o["share-secret"]:void 0;if(r&&!s)throw new l("Upload precheck response missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t}});return{uuid:s,exists:r,existsType:n,shareSecret:p,hit:(E={exists:r,uuid:s},E.exists&&"string"==typeof E.uuid&&E.uuid.length>0)};var E},ge=(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=Ae(t),s=Ae(o);return"size"!==r||!["big","large","thumbnail","small"].includes(s)}).join("&");return`${r}${i?`?${i}`:""}${o?`#${o}`:""}`})(e);return{originalImageUrl:o,bigImageUrl:Ie(o,"large"),thumbnailUrl:Ie(o,"small")}},De=e=>e===Oe?"origin":"large",Ue=e=>e===Oe?1:2,Le=e=>2===e?_e:Oe,be=t=>{const o=t.response.entities?.[0];if(!o?.uuid)throw new l("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??_e)===Oe;return{...ge(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}},Pe=(t,o)=>{if(!t)throw new l("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=ne({file:t,fallbackName:o.filename,fallbackMimeType:o.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new l("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"web file missing"}});return s},Ge=e=>new Promise(t=>{setTimeout(t,e)});const He=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 Ge(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=he(o);n=e.orgName,p=e.appName}catch{return!1}const E=`${t}/${n}/${p}/sdk/users/${r}/client/logs`,c={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: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}}},we="[MASKED]",ve=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),Fe=e=>!!e&&ve.has((e=>e.toLowerCase())(e)),Be=(e,t,o)=>{const r=o??/* @__PURE__ */new WeakSet;if("string"==typeof e)return((e,t)=>Fe(t)?we: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=>Be(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))Fe(o)?t[o]=we:t[o]=Be(s,o,r);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},ke="undefined"!=typeof document;let Ke=null,qe=!1;const Ve={DEBUG:0,WARN:1,ERROR:2};class $e{constructor(e="WARN"){this.consoleEnabled=!0,this.level=e}setLevel(e){this.level=e}setConsoleEnabled(e){this.consoleEnabled=e}shouldLog(e){return Ve[e]>=Ve[this.level]}emit(e,t,o){const r=(e=>{const t=/* @__PURE__ */new WeakSet;return e.map(e=>Be(e,void 0,t))})(o),s=((e,t,o)=>({timestamp:/* @__PURE__ */(new Date).toISOString(),level:e,message:t,args:o}))(e,t,r);if(He.append(s),this.consoleEnabled){const o=/* @__PURE__ */new Date,s=`[Chat][${e}][${`${String(o.getHours()).padStart(2,"0")}:${String(o.getMinutes()).padStart(2,"0")}:${String(o.getSeconds()).padStart(2,"0")}.${String(o.getMilliseconds()).padStart(3,"0")}`}]`;ke?console.log(`%c${s}`,"color: rgb(0, 157, 255); font-weight: bold",t,...r):console.log(s,t,...r)}const i=Ke;i&&!qe&&Promise.resolve().then(()=>{if(i===Ke){qe=!0;try{i(s)}catch{}finally{qe=!1}}})}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 xe=new $e;function je(e){xe instanceof $e&&xe.setLevel(e)}function ze(e){xe instanceof $e&&xe.setConsoleEnabled(e)}function We(e){Ke=e}function Ye(e){He.setState(e)}function Xe(e){He.updateContext(e)}function Je(e){He.updateReportInterval(e)}async function Qe(){await He.reportNow()}function Ze(){He.stop()}const et={debug:(e,...t)=>xe.debug(e,...t),warn:(e,...t)=>xe.warn(e,...t),error:(e,...t)=>xe.error(e,...t)},ot={WEB:"web",WECHAT_MINIAPP:"wechat-miniapp",QQ_MINIAPP:"qq-miniapp",TOUTIAO_MINIAPP:"toutiao-miniapp",BAIDU_MINIAPP:"baidu-miniapp",ALIPAY_MINIAPP:"alipay-miniapp",DINGTALK_MINIAPP:"dingtalk-miniapp",LARK_MINIAPP:"lark-miniapp",KUAISHOU_MINIAPP:"kuaishou-miniapp",JD_MINIAPP:"jd-miniapp",MINIAPP_360:"360-miniapp",HARMONY_MINIAPP:"harmony-miniapp",QUICKAPP:"quickapp",UNIAPP:"uniapp",REACT_NATIVE:"react-native",ELECTRON_RENDERER:"electron-renderer",ELECTRON_MAIN:"electron-main",UNKNOWN:"unknown"},rt={INIT:"init",REQUEST:"request",UPLOAD:"upload",SOCKET:"socket",PROTO:"proto",RUNTIME:"runtime",STORAGE:"storage"},st={INIT_FAILED:"PLATFORM_INIT_FAILED",MISSING_CAPABILITY:"PLATFORM_MISSING_CAPABILITY",REQUEST_FAILED:"PLATFORM_REQUEST_FAILED",UPLOAD_FAILED:"PLATFORM_UPLOAD_FAILED",SOCKET_FAILED:"PLATFORM_SOCKET_FAILED",PROTO_FAILED:"PLATFORM_PROTO_FAILED"},it=(e,t)=>{const o=new Error(e);return o.name="PlatformAdapterError",o.code=t.code,o.stage=t.stage,o.retryable=t.retryable,t.details&&(o.details=r(t.details)),o},at={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},nt=["__uniConfig","skipWaiting","registration","navigator","process","window","document","localStorage","fetch","WebSocket","XMLHttpRequest","FormData","TextEncoder","TextDecoder","crypto"],pt=e=>{if(e)return e;return((e,t)=>{if(!e)return t;if(0===Object.keys(t).length)return e;const o={},r=e;for(const s of nt)try{const e=r[s];void 0!==e&&(o[s]=e)}catch{}for(const s of Object.keys(t))o[s]=t[s];return o})("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0,{..."undefined"!=typeof wx?{wx:wx}:{},..."undefined"!=typeof qq?{qq:qq}:{},..."undefined"!=typeof tt?{tt:tt}:{},..."undefined"!=typeof swan?{swan:swan}:{},..."undefined"!=typeof my?{my:my}:{},..."undefined"!=typeof dd?{dd:dd}:{},..."undefined"!=typeof jd?{jd:jd}:{},..."undefined"!=typeof ks?{ks:ks}:{},..."undefined"!=typeof uni?{uni:uni}:{}})},Et=e=>{const t={};if(!e)return t;if("function"==typeof e.forEach)return e.forEach((e,o)=>{t[o]=e}),t;const o=e.get?.("content-type");return o&&(t["content-type"]=o),t},ct=async(e,t)=>{const o=e;if("function"!=typeof o.text){if("function"!=typeof o.json)return"";const e=await o.json();return t?e:JSON.stringify(e)}const r=await o.text();if(!t||0===r.length)return r;try{return JSON.parse(r)}catch{return r}},Tt=e=>{const t=e?.fetchImpl;if("function"==typeof t)return{async request(o){const r=o.method??"GET",s={...o.headers??{}},i=new AbortController,a=o.timeoutMs??e?.timeoutMs??15e3;let n=!1;const p=()=>i.abort(o.signal?.reason);o.signal?.aborted?p():o.signal?.addEventListener("abort",p,{once:!0});const E=setTimeout(()=>{n=!0,i.abort()},a),c=((e,t,o)=>{if(e.body instanceof Uint8Array)return new Uint8Array(e.body).buffer;if("string"==typeof e.body)return e.body;if(e.body&&"GET"!==o)return Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),JSON.stringify(e.body)})(o,s,r);try{const e=await t(o.url,{method:r,headers:s,body:c,signal:i.signal});let a;if("arraybuffer"===o.responseType)a=await e.arrayBuffer();else if("text"===o.responseType)a=await e.text();else if("json"===o.responseType)a=await ct(e,!0);else{const t=e.headers.get("content-type")??"";a=await ct(e,t.includes("application/json"))}return{status:e.status,statusText:e.statusText,headers:Et(e.headers),data:a}}catch(T){const e=((e,t,o)=>t?"timeout":o?.aborted||e instanceof Error&&"AbortError"===e.name?"abort":"network")(T,n,o.signal);throw it("Request adapter execution failed.",{code:st.REQUEST_FAILED,stage:rt.REQUEST,retryable:"abort"!==e,details:{url:o.url,method:r,reason:e,cause:T instanceof Error?T.message:String(T)}})}finally{clearTimeout(E),o.signal?.removeEventListener("abort",p)}}}},ut=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,dt="X-Request-Id",lt=1e3,Ot="direct";class _t{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 Rt{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 mt={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},ht=()=>{const e=pt(),t=e.crypto?.randomUUID;return("function"==typeof t?t.call(e.crypto):void 0)??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class Nt{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??ht;const t=new Rt({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 _t({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:mt[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,c=(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??Ot,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=>{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??Ot,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 It;const At=e=>(It?.reset(),It=new Nt(e),It),ft=e=>It?.startSession(e),St=e=>{It?.updateSession(e)},yt=e=>{It?.applyDnsSwitch(e)},Ct=e=>{It?.updateNetworkType(e)},Mt=e=>{if("disabled"!==It?.state)return It?.startOperation(e)},gt=()=>{It?.reset(),It=void 0},Dt=()=>{const e=globalThis;return"function"==typeof e.fetch?e.fetch:void 0},Ut=()=>Tt({fetchImpl:Dt()})??{request:e=>Promise.reject(it("Request capability is missing for current platform.",{code:st.MISSING_CAPABILITY,stage:rt.REQUEST,retryable:!1,details:{capability:"request"}}))},Lt=e=>e??Ut(),bt=(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 Pt(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:"string"==typeof r.desc?r.desc: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(bt(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 c of Object.values(e.common)){const e=n(c.errors,!0);if(e)return e}}function Gt(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 Ht={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"}},wt=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase();class vt{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=Lt(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 p("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);et.debug("REST request",{method:i,url:n,operation:o.operation});const p=o.operation?(e=>{const t=Ht[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_${wt(e)}`,operationType:o}})(o.operation):void 0,E=p?Mt(p):void 0,c=E?.startRequest({requestName:p?.operationName,method:i,url:r});let T=0;const d={...this.defaultHeaders,...o.headers};if(this.includeRequestId&&(d[dt]=ut()),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"):e||(d["Content-Type"]="application/json")}else if("GET"===i)for(const e of Object.keys(d))"content-type"===e.toLowerCase()&&delete d[e];try{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)&&(et.warn("REST response error",{method:i,url:n,status:e.status,duration:s}),this.handleErrorPayload(e.status,e.statusText??"",t,{operation:o.operation,url:r,method:i})),et.debug("REST response",{method:i,url:n,status:e.status,duration:s});const p=(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}})(t);return c?.finish({code:e.status,success:!0,resultCount:p}),E?.finish({code:0,success:!0,resultCount:p}),t}catch(l){const t=0!==T?T:l instanceof s?l.code:-1,a=l instanceof Error?l.message:String(l);if(c?.finish({code:t,success:!1,description:a}),E?.finish({code:t,success:!1,description:a}),l instanceof s)throw l;const p=(e=>{if(!e||"object"!=typeof e)return;const t=e.details;if(!t||"object"!=typeof t)return;const o=t.reason;return"abort"===o||"network"===o||"timeout"===o?o:void 0})(l);if(l instanceof Error&&"AbortError"===l.name||"timeout"===p)throw et.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 et.warn("REST request failed",{method:i,url:n}),new u(`Request failed: ${r}`,{code:e.REST_NETWORK_ERROR,details:{url:r,method:i,...p?{reason:p}:{}}})}}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,p=Pt(this.errorMap,s.operation,n),E="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 i.desc?i.desc:"string"==typeof a?.message?a.message:void 0,d=!!(401!==t&&403!==t||void 0!==E&&"unauthorized"!==E&&"auth_failed"!==E&&"forbidden"!==E)&&(void 0!==E||"string"==typeof i.error_description||"string"==typeof i.message||"string"==typeof i.desc);if(s.operation&&p)throw Gt({apiName:s.operation,entry:p.entry,serverCode:c,serverMessage:T,httpStatus:t,mapped:!0,reasonKey:p.reasonKey,matchedBy:p.matchedBy});const l=this.buildHttpStatusFallbackError(t,s,c,T);if(l)throw l;if(s.operation&&d)throw Gt({apiName:s.operation,serverCode:c,serverMessage:T,httpStatus:t,mapped:!1,reasonKey:E});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 Ft=(...e)=>{const t={},o={};for(const r of e)Object.assign(t,r.common),Object.assign(o,r.apis);return{common:t,apis:o}},Bt={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},LOGIN_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{De as $,n as A,A as B,Bt as C,L as D,e as E,U as F,D as G,M as H,g as I,f as J,Mt as K,c as L,E as M,W as N,Le as O,st as P,Oe as Q,vt as R,s as S,_ as T,l as U,p as V,lt as W,Lt as X,pe as Y,ce as Z,fe as _,rt as a,be as a0,Ee as a1,Ne as a2,me as a3,Re as a4,Pe as a5,ye as a6,Ce as a7,Me as a8,F as a9,gt as aA,Xe as aB,Je as aC,Qe as aD,Ze as aE,R as aF,Z as aG,We as aH,ze as aI,je as aJ,O as aK,Pt as aL,I as aM,N as aN,T as aa,b as ab,v as ac,P as ad,o as ae,H as af,G as ag,w as ah,y as ai,C as aj,m as ak,q as al,K as am,x as an,$ as ao,j as ap,V as aq,k as ar,B as as,S as at,At as au,ft as av,Ct as aw,Ye as ax,St as ay,yt as az,z as b,Y as c,J as d,X as e,Q as f,pt as g,Gt as h,d as i,Se as j,ge as k,et as l,Ft as m,ne as n,dt as o,he as p,ut as q,a as r,i as s,u as t,ot as u,it as v,at as w,h as x,Tt as y,Ue as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e={MESSAGE:"onMessage",STREAM_MESSAGE:"onStreamMessage",CONVERSATION_LIST_UPDATE:"onConversationListUpdate",MESSAGE_READ_RECEIPTS:"onMessageReadReceipts",MESSAGE_DELIVERED:"onMessageDelivered",MESSAGE_RECALLED:"onMessageRecalled",MESSAGE_UPDATED:"onMessageUpdated",REACTION_CHANGED:"onReactionChanged",PINNED_MESSAGE_CHANGED:"onPinnedMessageChanged",MULTI_DEVICE_CONTACT:"onMultiDeviceContact",MULTI_DEVICE_CONVERSATION:"onMultiDeviceConversation",SYNC_DATA_START:"onSyncDataStart",SYNC_DATA_FINISHED:"onSyncDataFinished"},E={LOG:"onLog"},o={STATUS_CHANGE:"onPresenceStatusChange"},n={INVITED:"onContactInvited",DELETED:"onContactDeleted",ADDED:"onContactAdded",REFUSE:"onContactRefuse",AGREED:"onContactAgreed",CONTACT_INFO_UPDATED:"onContactInfoUpdated"},_={INVITATION_RECEIVED:"onInvitationReceived",REQUEST_TO_JOIN_RECEIVED:"onRequestToJoinReceived",REQUEST_TO_JOIN_ACCEPTED:"onRequestToJoinAccepted",REQUEST_TO_JOIN_DECLINED:"onRequestToJoinDeclined",INVITATION_ACCEPTED:"onInvitationAccepted",INVITATION_DECLINED:"onInvitationDeclined",USER_REMOVED:"onUserRemoved",GROUP_DESTROYED:"onGroupDestroyed",AUTO_ACCEPT_INVITATION:"onAutoAcceptInvitationFromGroup",MUTE_LIST_ADDED:"onMuteListAdded",MUTE_LIST_REMOVED:"onMuteListRemoved",ALLOW_LIST_ADDED:"onAllowListAdded",ALLOW_LIST_REMOVED:"onAllowListRemoved",ALL_MEMBER_MUTE_STATE_CHANGED:"onAllMemberMuteStateChanged",ADMIN_ADDED:"onAdminAdded",ADMIN_REMOVED:"onAdminRemoved",OWNER_CHANGED:"onOwnerChanged",MEMBERS_JOINED:"onMembersJoined",MEMBERS_EXITED:"onMembersExited",ANNOUNCEMENT_CHANGED:"onAnnouncementChanged",SHARED_FILE_ADDED:"onSharedFileAdded",SHARED_FILE_DELETED:"onSharedFileDeleted",GROUP_INFO_CHANGED:"onGroupInfoChanged",GROUP_DISABLED_CHANGED:"onGroupDisabledChanged",GROUP_MEMBER_ATTRIBUTE_CHANGED:"onGroupMemberAttributeChanged",USER_GROUP_NAMECARD_UPDATED:"onUserGroupNamecardUpdated"},A={CHAT_ROOM_DESTROYED:"__chatroom:onChatRoomDestroyed",MEMBERS_JOINED:"__chatroom:onMembersJoined",MEMBERS_EXITED:"__chatroom:onMembersExited",REMOVED_FROM_CHAT_ROOM:"__chatroom:onRemovedFromChatRoom",MUTE_LIST_ADDED:"__chatroom:onMuteListAdded",MUTE_LIST_REMOVED:"__chatroom:onMuteListRemoved",ALLOW_LIST_ADDED:"__chatroom:onAllowListAdded",ALLOW_LIST_REMOVED:"__chatroom:onAllowListRemoved",ALL_MEMBER_MUTE_STATE_CHANGED:"__chatroom:onAllMemberMuteStateChanged",ADMIN_ADDED:"__chatroom:onAdminAdded",ADMIN_REMOVED:"__chatroom:onAdminRemoved",OWNER_CHANGED:"__chatroom:onOwnerChanged",ANNOUNCEMENT_CHANGED:"__chatroom:onAnnouncementChanged",CHAT_ROOM_INFO_CHANGED:"__chatroom:onChatRoomInfoChanged",ATTRIBUTES_UPDATE:"__chatroom:onAttributesUpdate",ATTRIBUTES_REMOVED:"__chatroom:onAttributesRemoved"},D={TOKEN_BOUND:"onPushTokenBound",TOKEN_BIND_FAILED:"onPushTokenBindFailed",TOKEN_REMOVE_FAILED:"onPushTokenRemoveFailed"};export{e as C,_ as G,E as L,
|
|
1
|
+
const e={MESSAGE:"onMessage",STREAM_MESSAGE:"onStreamMessage",CONVERSATION_LIST_UPDATE:"onConversationListUpdate",MESSAGE_READ_RECEIPTS:"onMessageReadReceipts",MESSAGE_DELIVERED:"onMessageDelivered",MESSAGE_RECALLED:"onMessageRecalled",MESSAGE_UPDATED:"onMessageUpdated",REACTION_CHANGED:"onReactionChanged",PINNED_MESSAGE_CHANGED:"onPinnedMessageChanged",MULTI_DEVICE_CONTACT:"onMultiDeviceContact",MULTI_DEVICE_CONVERSATION:"onMultiDeviceConversation",SYNC_DATA_START:"onSyncDataStart",SYNC_DATA_FINISHED:"onSyncDataFinished"},E={LOG:"onLog"},o={STATUS_CHANGE:"onPresenceStatusChange"},n={INVITED:"onContactInvited",DELETED:"onContactDeleted",ADDED:"onContactAdded",REFUSE:"onContactRefuse",AGREED:"onContactAgreed",CONTACT_INFO_UPDATED:"onContactInfoUpdated"},_={INVITATION_RECEIVED:"onInvitationReceived",REQUEST_TO_JOIN_RECEIVED:"onRequestToJoinReceived",REQUEST_TO_JOIN_ACCEPTED:"onRequestToJoinAccepted",REQUEST_TO_JOIN_DECLINED:"onRequestToJoinDeclined",INVITATION_ACCEPTED:"onInvitationAccepted",INVITATION_DECLINED:"onInvitationDeclined",USER_REMOVED:"onUserRemoved",GROUP_DESTROYED:"onGroupDestroyed",AUTO_ACCEPT_INVITATION:"onAutoAcceptInvitationFromGroup",MUTE_LIST_ADDED:"onMuteListAdded",MUTE_LIST_REMOVED:"onMuteListRemoved",ALLOW_LIST_ADDED:"onAllowListAdded",ALLOW_LIST_REMOVED:"onAllowListRemoved",ALL_MEMBER_MUTE_STATE_CHANGED:"onAllMemberMuteStateChanged",ADMIN_ADDED:"onAdminAdded",ADMIN_REMOVED:"onAdminRemoved",OWNER_CHANGED:"onOwnerChanged",MEMBERS_JOINED:"onMembersJoined",MEMBERS_EXITED:"onMembersExited",ANNOUNCEMENT_CHANGED:"onAnnouncementChanged",SHARED_FILE_ADDED:"onSharedFileAdded",SHARED_FILE_DELETED:"onSharedFileDeleted",GROUP_INFO_CHANGED:"onGroupInfoChanged",GROUP_DISABLED_CHANGED:"onGroupDisabledChanged",GROUP_MEMBER_ATTRIBUTE_CHANGED:"onGroupMemberAttributeChanged",USER_GROUP_NAMECARD_UPDATED:"onUserGroupNamecardUpdated"},A={CHAT_ROOM_DESTROYED:"__chatroom:onChatRoomDestroyed",MEMBERS_JOINED:"__chatroom:onMembersJoined",MEMBERS_EXITED:"__chatroom:onMembersExited",REMOVED_FROM_CHAT_ROOM:"__chatroom:onRemovedFromChatRoom",MUTE_LIST_ADDED:"__chatroom:onMuteListAdded",MUTE_LIST_REMOVED:"__chatroom:onMuteListRemoved",ALLOW_LIST_ADDED:"__chatroom:onAllowListAdded",ALLOW_LIST_REMOVED:"__chatroom:onAllowListRemoved",ALL_MEMBER_MUTE_STATE_CHANGED:"__chatroom:onAllMemberMuteStateChanged",ADMIN_ADDED:"__chatroom:onAdminAdded",ADMIN_REMOVED:"__chatroom:onAdminRemoved",OWNER_CHANGED:"__chatroom:onOwnerChanged",ANNOUNCEMENT_CHANGED:"__chatroom:onAnnouncementChanged",CHAT_ROOM_INFO_CHANGED:"__chatroom:onChatRoomInfoChanged",ATTRIBUTES_UPDATE:"__chatroom:onAttributesUpdate",ATTRIBUTES_REMOVED:"__chatroom:onAttributesRemoved"},D={TOKEN_BOUND:"onPushTokenBound",TOKEN_BIND_FAILED:"onPushTokenBindFailed",TOKEN_REMOVE_FAILED:"onPushTokenRemoveFailed"};export{e as C,_ as G,E as L,D as P,n as a,o as b,A as c};
|
package/chunks/{group-user-info-resolver-B-dyr__b.cjs → group-user-info-resolver-BNwtC7dY.cjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const e=require("./common-
|
|
1
|
+
"use strict";const e=require("./common-Cg-lTASK.cjs"),r=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],s=(e,r)=>`${e}\0${r}`,o=(e,s,o)=>{const t={userId:e};for(const n of r){const e=o?.[n]??s?.[n];void 0!==e&&(t[n]=e)}return t},t=e=>o(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),n=(e,r,o)=>{const t=new Map;if(!e?.getGroupNamecard||!o)return t;for(const n of r){const r=e.getGroupNamecard(n.groupId,n.user.userId,!1);r&&t.set(s(n.groupId,n.user.userId),r.namecard)}return t},a=async(r,s)=>{if(0===r.length||!s)return[];try{return await s({userIds:r})}catch(o){return e.logger.warn("Group user info hydration failed",{userIds:r,error:o}),[]}},d=async(r,s)=>{s&&0!==r.size&&await Promise.all([...r.entries()].map(async([r,o])=>{try{await s(r,o)}catch(t){e.logger.warn("Group namecard hydration failed",{groupId:r,userIds:o,error:t})}}))},u=async e=>{const r=(e=>{const r=[],o=new Set;for(const t of e){const e=t.groupId.trim(),n=t.user.userId.trim();if(!e||!n)continue;const a=s(e,n);o.has(a)||(o.add(a),r.push({groupId:e,user:{...t.user,userId:n}}))}return r})(e.contexts),u=(e=>{const r=[],s=new Set;for(const o of e)s.has(o.user.userId)||(s.add(o.user.userId),r.push(o.user.userId));return r})(r),c=((e,r)=>{const s=new Map;if(!e)return s;for(const t of r){const r=e.getRuntimeUserInfo?.(t,!1)??null;r&&s.set(t,r)}const o=r.filter(e=>!s.has(e));for(const n of e.getUserInfoSummaries?.(o,!1)??[])s.set(n.userId,t(n));return s})(e.cacheManager,u),i=u.filter(e=>!c.has(e)),p=new Set(i),f=n(e.cacheManager,r,e.includeNameCard),l=e.includeNameCard?((e,r,o)=>{const t=new Map;for(const n of e){const e=n.user.userId,a=s(n.groupId,e);if(!r.has(e)||o.has(a))continue;const d=t.get(n.groupId)??[];d.includes(e)||d.push(e),t.set(n.groupId,d)}return t})(r,p,f):new Map,[I]=await Promise.all([a(i,e.fetchUserInfos),d(l,e.hydrateGroupNamecards)]),g=new Map(I.map(e=>[e.userId,e])),E=n(e.cacheManager,r,e.includeNameCard),U=new Map;for(const t of r){const e=t.user.userId,r=s(t.groupId,e),n=o(e,t.user,g.get(e)??c.get(e)),a=E.get(r)??f.get(r);U.set(r,void 0!==a?{...n,nameCard:a}:n)}return{usersByContextKey:U,fetchedUserInfos:I,missingUserIds:i.filter(e=>!g.has(e))}};exports.getGroupUserInfoContextKey=s,exports.mapUploadAdapterError=r=>{if(r instanceof e.UploadError)return r;if((e=>"object"==typeof e&&null!==e)(r)){const s=r.details;if(r.code===e.PLATFORM_ERROR_CODE.MISSING_CAPABILITY){const o=s?.capability;if(r.stage===e.PLATFORM_ERROR_STAGE.RUNTIME&&"string"==typeof o&&o.includes("FileSystem")){const o=r instanceof Error?r.message:"Upload failed";return new e.UploadError(o,{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:s})}return new e.UploadError("Upload capability is missing for current platform",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:s})}if(r.stage===e.PLATFORM_ERROR_STAGE.UPLOAD)return(e=>{const r=e?.reason;return!("string"!=typeof r||!r.toLowerCase().includes("abort"))})(s)?new e.UploadError("Upload canceled",{code:e.ERROR_CODES.UPLOAD_ABORTED,details:s}):(e=>{const r=e?.reason;return!("string"!=typeof r||!r.toLowerCase().includes("timeout"))})(s)?new e.UploadError("Upload timeout",{code:e.ERROR_CODES.UPLOAD_TIMEOUT,details:s}):new e.UploadError("Upload failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:s})}const s=r instanceof Error?r.message:"Upload failed";return new e.UploadError(s,{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{cause:r}})},exports.resolveGroupUserInfoContexts=u,exports.resolveGroupUserInfoMap=async e=>{const r=await u({...e,contexts:e.users.map(r=>({groupId:e.groupId,user:r}))}),o=new Map;for(const t of e.users){const n=t.userId.trim();if(!n||o.has(n))continue;const a=r.usersByContextKey.get(s(e.groupId.trim(),n));a&&o.set(n,a)}return{usersById:o,fetchedUserInfos:r.fetchedUserInfos,missingUserIds:r.missingUserIds}};
|
package/chunks/{group-user-info-resolver-DMccCqez.js → group-user-info-resolver-rs5Fnr0l.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{U as e,P as r,a as s,E as t,l as n}from"./common-
|
|
1
|
+
import{U as e,P as r,a as s,E as t,l as n}from"./common-gbNWJrBc.js";const a=n=>{if(n instanceof e)return n;if((e=>"object"==typeof e&&null!==e)(n)){const a=n.details;if(n.code===r.MISSING_CAPABILITY){const r=a?.capability;if(n.stage===s.RUNTIME&&"string"==typeof r&&r.includes("FileSystem")){const r=n instanceof Error?n.message:"Upload failed";return new e(r,{code:t.UPLOAD_REQUEST_FAILED,details:a})}return new e("Upload capability is missing for current platform",{code:t.UPLOAD_REQUIRED_FIELD_MISSING,details:a})}if(n.stage===s.UPLOAD)return(e=>{const r=e?.reason;return!("string"!=typeof r||!r.toLowerCase().includes("abort"))})(a)?new e("Upload canceled",{code:t.UPLOAD_ABORTED,details:a}):(e=>{const r=e?.reason;return!("string"!=typeof r||!r.toLowerCase().includes("timeout"))})(a)?new e("Upload timeout",{code:t.UPLOAD_TIMEOUT,details:a}):new e("Upload failed",{code:t.UPLOAD_REQUEST_FAILED,details:a})}const a=n instanceof Error?n.message:"Upload failed";return new e(a,{code:t.UPLOAD_REQUEST_FAILED,details:{cause:n}})},o=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],u=(e,r)=>`${e}\0${r}`,c=(e,r,s)=>{const t={userId:e};for(const n of o){const e=s?.[n]??r?.[n];void 0!==e&&(t[n]=e)}return t},d=e=>c(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),i=(e,r,s)=>{const t=/* @__PURE__ */new Map;if(!e?.getGroupNamecard||!s)return t;for(const n of r){const r=e.getGroupNamecard(n.groupId,n.user.userId,!1);r&&t.set(u(n.groupId,n.user.userId),r.namecard)}return t},f=async(e,r)=>{if(0===e.length||!r)return[];try{return await r({userIds:e})}catch(s){return n.warn("Group user info hydration failed",{userIds:e,error:s}),[]}},I=async(e,r)=>{r&&0!==e.size&&await Promise.all([...e.entries()].map(async([e,s])=>{try{await r(e,s)}catch(t){n.warn("Group namecard hydration failed",{groupId:e,userIds:s,error:t})}}))},l=async e=>{const r=(e=>{const r=[],s=/* @__PURE__ */new Set;for(const t of e){const e=t.groupId.trim(),n=t.user.userId.trim();if(!e||!n)continue;const a=u(e,n);s.has(a)||(s.add(a),r.push({groupId:e,user:{...t.user,userId:n}}))}return r})(e.contexts),s=(e=>{const r=[],s=/* @__PURE__ */new Set;for(const t of e)s.has(t.user.userId)||(s.add(t.user.userId),r.push(t.user.userId));return r})(r),t=((e,r)=>{const s=/* @__PURE__ */new Map;if(!e)return s;for(const n of r){const r=e.getRuntimeUserInfo?.(n,!1)??null;r&&s.set(n,r)}const t=r.filter(e=>!s.has(e));for(const n of e.getUserInfoSummaries?.(t,!1)??[])s.set(n.userId,d(n));return s})(e.cacheManager,s),n=s.filter(e=>!t.has(e)),a=new Set(n),o=i(e.cacheManager,r,e.includeNameCard),l=e.includeNameCard?((e,r,s)=>{const t=/* @__PURE__ */new Map;for(const n of e){const e=n.user.userId,a=u(n.groupId,e);if(!r.has(e)||s.has(a))continue;const o=t.get(n.groupId)??[];o.includes(e)||o.push(e),t.set(n.groupId,o)}return t})(r,a,o):/* @__PURE__ */new Map,[p]=await Promise.all([f(n,e.fetchUserInfos),I(l,e.hydrateGroupNamecards)]),g=new Map(p.map(e=>[e.userId,e])),m=i(e.cacheManager,r,e.includeNameCard),U=/* @__PURE__ */new Map;for(const d of r){const e=d.user.userId,r=u(d.groupId,e),s=c(e,d.user,g.get(e)??t.get(e)),n=m.get(r)??o.get(r);U.set(r,void 0!==n?{...s,nameCard:n}:s)}return{usersByContextKey:U,fetchedUserInfos:p,missingUserIds:n.filter(e=>!g.has(e))}},p=async e=>{const r=await l({...e,contexts:e.users.map(r=>({groupId:e.groupId,user:r}))}),s=/* @__PURE__ */new Map;for(const t of e.users){const n=t.userId.trim();if(!n||s.has(n))continue;const a=r.usersByContextKey.get(u(e.groupId.trim(),n));a&&s.set(n,a)}return{usersById:s,fetchedUserInfos:r.fetchedUserInfos,missingUserIds:r.missingUserIds}};export{l as a,u as g,a as m,p as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const e=require("./common-Cg-lTASK.cjs"),t=require("./cache-utils-gowrxNr8.cjs"),r=require("./index-P1vnLSK2.cjs"),a=require("./multibody-content-BmdQukoX.cjs"),i=require("./query-params-BHyPuD2k.cjs"),s={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};const o={TEXT:0,IMAGE:1,VIDEO:2,LOCATION:3,VOICE:4,FILE:5,COMMAND:6,CUSTOM:7,COMBINE:8},n=0,d=1,u=2,h=3,l=4,c=1,m=2,p=3,g=4,y=5,f=6,_=7,b=8,T=e=>{if("function"==typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let r=0;r<e.length;r+=1){const a=e[r]??0;if(a<128){t+=String.fromCharCode(a);continue}if(a>=192&&a<224){const i=e[r+1]??0;t+=String.fromCharCode((31&a)<<6|63&i),r+=1;continue}if(a>=224&&a<240){const i=e[r+1]??0,s=e[r+2]??0;t+=String.fromCharCode((15&a)<<12|(63&i)<<6|63&s),r+=2;continue}const i=((7&a)<<18|(63&(e[r+1]??0))<<12|(63&(e[r+2]??0))<<6|63&(e[r+3]??0))-65536;t+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),r+=3}return t},v=e=>{let t=e;if("string"==typeof t)try{t=JSON.parse(t)}catch{return}if(!t||"object"!=typeof t||!("translations"in t))return;const r=t.translations;if(!Array.isArray(r))return;const a=[];for(const i of r)i&&"object"==typeof i&&"code"in i&&"text"in i&&"string"==typeof i.code&&i.code.trim()&&"string"==typeof i.text&&a.push([i.code,i.text]);return a.length>0?Object.fromEntries(a):void 0},I="websdk2:device-info",C="webim",S="web",R=e=>{if("string"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?`${e}`:"";if("bigint"==typeof e)return e.toString();if(e&&"object"==typeof e&&"low"in e&&"high"in e&&"number"==typeof e.low&&"number"==typeof e.high){const t=e;return new r.Long(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},N=e=>{if(!e||0===e.length)return{};const t={};for(const r of e){const e="string"==typeof r.key?r.key:"";if(!e)continue;const a="number"==typeof r.type?r.type:_;if(a!==c)if(a!==m&&a!==p&&a!==g)if(a!==y)if(a!==f){if(a!==b)t[e]="string"==typeof r.stringValue?r.stringValue:"";else if("string"==typeof r.stringValue)try{t[e]=JSON.parse(r.stringValue)}catch{t[e]=r.stringValue}}else t[e]=Number(r.doubleValue??0);else t[e]=Number(r.floatValue??0);else t[e]=Number(r.varintValue??0);else t[e]=Boolean(r.varintValue)}return t},E=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),O=e=>{const t=Array.isArray(e.contents)?e.contents[0]:void 0;return E(t)?t:void 0};class A{constructor(e,t=!1){this.userId=e,this.useCustomAttachmentUpload=t}decodeMetadata(e,t,r,a){const i=this.resolveMessageMetaPayload(e.meta,a),s={},o={modifiedInfo:this.resolveModifiedInfo(i),reactions:this.resolveReactions(i),isContentReplaced:this.resolveContentReplaced(i),chatThread:this.resolveChatThreadMessageContext(i),chatThreadOverview:this.resolveChatThreadOverview(i),isPeerRead:this.resolvePeerRead(i,t,r),groupReadCount:this.resolveGroupReadCount(i,t),stream:this.decodeStreamMeta(e.stream,O(e))};for(const[n,d]of Object.entries(o))void 0!==d&&Object.assign(s,{[n]:d});return o.chatThread&&(s.isChatThread=!0),E(e.msgConfig)&&e.msgConfig.allowGroupAck&&(s.needReadReceipt=!0),s}decodeContent(t,r){const a="number"==typeof t.type?t.type:o.TEXT,i="string"==typeof t.remotePath&&t.remotePath.length>0||"string"==typeof t.title&&t.title.length>0||"string"==typeof t.summary&&t.summary.length>0||"number"==typeof t.combineLevel&&t.combineLevel>0,s=Object.prototype.hasOwnProperty.call(t,"subType")&&0===t.subType;if(a===o.COMBINE||a===o.TEXT&&(s||i)){return{type:"combine",body:{title:"string"==typeof t.title?t.title:"",summary:"string"==typeof t.summary?t.summary:"",filename:"string"==typeof t.displayName?t.displayName:"combine",filetype:"application/octet-stream",url:"string"==typeof t.remotePath?t.remotePath:void 0,secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0,combineLevel:"number"==typeof t.combineLevel?t.combineLevel:0}}}if(a===o.TEXT){const e=v(r);return{type:"text",body:{content:"string"==typeof t.text?t.text:"",...e?{translations:e}:{}}}}if(a===o.COMMAND)return{type:"cmd",body:{action:"string"==typeof t.action?t.action:""}};if(a===o.CUSTOM){const e=N(t.customExts);return{type:"custom",body:{event:"string"==typeof t.customEvent?t.customEvent:"",params:e}}}if(a===o.LOCATION)return{type:"location",body:{latitude:"number"==typeof t.latitude?t.latitude:0,longitude:"number"==typeof t.longitude?t.longitude:0,address:"string"==typeof t.address?t.address:void 0,buildingName:"string"==typeof t.buildingName?t.buildingName:void 0}};if(a===o.IMAGE){const r=t.size??{},a="number"==typeof r.width?r.width:0,i="number"==typeof r.height?r.height:0,s=e.fromProtocolImageType(t.imageType)===e.IMAGE_TYPE_ORIGINAL,o="string"==typeof t.remotePath?t.remotePath:"",n=e.deriveImageUrls(o,{deriveVariants:!this.useCustomAttachmentUpload}),d="string"==typeof t.thumbnailRemotePath&&t.thumbnailRemotePath.length>0?t.thumbnailRemotePath:void 0;return{type:"image",body:{localUrl:"",filename:"string"==typeof t.displayName?t.displayName:"image",filetype:"application/octet-stream",width:a,height:i,isGif:1===t.subType,isOriginalImage:s,originalImageUrl:n.originalImageUrl,bigImageUrl:n.bigImageUrl,secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0,thumbnailUrl:d??n.thumbnailUrl}}}if(a===o.VIDEO){const e=t.size??{},r="number"==typeof e.width?e.width:void 0,a="number"==typeof e.height?e.height:void 0,i="string"==typeof t.thumbnailRemotePath?t.thumbnailRemotePath:void 0;return{type:"video",body:{url:"string"==typeof t.remotePath?t.remotePath:"",filename:"string"==typeof t.displayName?t.displayName:"video",filetype:"application/octet-stream",duration:"number"==typeof t.duration?t.duration:0,width:r,height:a,secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0,thumbnailUrl:i}}}if(a===o.VOICE){return{type:"voice",body:{url:"string"==typeof t.remotePath?t.remotePath:"",filename:"string"==typeof t.displayName?t.displayName:"voice",filetype:"application/octet-stream",duration:"number"==typeof t.duration?t.duration:0,secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0}}}if(a===o.FILE){return{type:"file",body:{url:"string"==typeof t.remotePath?t.remotePath:"",filename:"string"==typeof t.displayName?t.displayName:"file",filetype:"application/octet-stream",secret:"string"==typeof t.secretKey?t.secretKey:void 0,fileLength:"number"==typeof t.fileLength?t.fileLength:void 0}}}return null}decodeStreamMeta(e,t){if(!e||"object"!=typeof e)return;const r=e,a=Number(R(r.streamSeq));if(!Number.isFinite(a))return;const i="number"==typeof r.streamStatus?r.streamStatus:u,s="number"==typeof r.streamError?r.streamError:0,o="number"==typeof r.streamFinishReason?r.streamFinishReason:void 0,n=this.resolveContentText(t),d=n;return{customType:"string"==typeof r.streamType?r.streamType:void 0,seq:a,status:this.mapStreamStatus(i,s),errorType:s,finishReason:o,deltaText:n,fullText:d}}mapStreamStatus(e,t){return t>0?s.ERROR:e===n?s.START:e===d?s.START_COMPLETED:e===h?s.COMPLETED:e===l?s.FULL:s.IN_PROGRESS}resolveContentText(e){return e&&"string"==typeof e.text?e.text:e&&"string"==typeof e.customEvent?e.customEvent:""}resolveContentReplaced(e){const t=this.parseMetaPayload(e);if(t&&Object.prototype.hasOwnProperty.call(t,"callback_replace"))return Boolean(t.callback_replace)}resolveMessageMetaPayload(e,t){const r=this.parseMetaPayload(e),a=this.parseMetaPayload(t);return r&&a?{...a,...r}:r??a??e??t}resolvePeerRead(e,t,r){if("singleChat"!==t||"SEND"!==r)return;const a=this.parseMetaPayload(e);return"boolean"==typeof a?.isRead?a.isRead:void 0}resolveGroupReadCount(e,t){if("groupChat"!==t)return;const r=this.parseMetaPayload(e),a=r?.group_read_ack;return"number"==typeof a&&Number.isInteger(a)&&a>=0?a:void 0}resolveModifiedInfo(e){const t=this.parseMetaPayload(e),r=t?.edit_msg;if(!E(r))return;const a="string"==typeof r.operator?r.operator:"",i=this.toFiniteNumber(r.count),s=this.toFiniteNumber(r.edit_time);return a&&void 0!==i&&void 0!==s?{operatorId:a,operationCount:i,operationTime:s}:void 0}resolveChatThreadMessageContext(e){const t=this.parseMetaPayload(e),r=t?.thread;if(!E(r)||0===Object.keys(r).length)return;const a=this.readString(r.msg_parent_id??r.messageId),i=this.readString(r.muc_parent_id??r.parentId);if(!a||!i)return;const s=this.readString(r.thread_name??r.chatThreadName);return{messageId:a,parentId:i,...s?{chatThreadName:s}:{}}}resolveChatThreadOverview(e){const t=this.parseMetaPayload(e),r=t?.thread_overview??t?.threadOverview;if(!E(r)||0===Object.keys(r).length)return;const a=this.readString(r.id??r.thread_id??r.chatThreadId),i=this.readString(r.muc_parent_id??r.parentId);if(!a||!i)return;const s=this.readString(r.name),o=this.resolveChatThreadOverviewLastMessage(r.last_message??r.lastMessage,a);return{chatThreadId:a,parentId:i,...s?{name:s}:{},...void 0!==o?{lastMessage:o}:{},...this.numberField("createdAt",r.create_timestamp??r.createdAt),...this.numberField("updatedAt",r.update_timestamp??r.updatedAt),...this.numberField("messageCount",r.message_count??r.messageCount)}}resolveChatThreadOverviewLastMessage(e,t){if(!E(e)||0===Object.keys(e).length)return null;const r=this.readString(e.msgId??e.msg_id??e.id);if(!r)return null;const a=this.toFiniteNumber(e.timestamp)??0,i=this.resolveThreadLastMessagePayload(e),s=this.readString(i?.from)??this.readString(e.from)??"",o=this.readString(i?.to)??this.readString(e.to)??t,n=Array.isArray(i?.bodies)?i.bodies:[],d=n.length>=2?this.composeThreadBodies(n):null;if(n.length>=2&&!d)return null;const u=E(n[0])?n[0]:null,h=this.readString(u?.type)??this.readString(e.type),l=d?.type??this.mapThreadMessageType(h),c=d?.body??this.normalizeThreadLastMessageBody(l,u,e),m=t,p=s===this.userId?"SEND":"RECEIVE";return{msgServerId:r,msgLocalId:"",from:s,to:o,sender:{userId:s},conversationId:m,conversationType:"groupChat",type:l,sendStatus:"sent",ext:E(i?.ext)?i.ext:{},timestamp:a,body:c,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(E(t))return t;if("string"==typeof t){const e=this.parseMetaPayload(t);if(e)return e}return null}composeThreadBodies(e){return a.composeSegments(e.map(e=>{if(!E(e))return null;if(a.isCombineRestSegment(e))return{type:"combine",body:this.normalizeThreadLastMessageBody("combine",e,e)};const t=a.mapRestSegmentType(this.readString(e.type));return t?{type:t,body:this.normalizeThreadLastMessageBody(t,e,e)}:null}))}mapThreadMessageType(e){switch(e){case"txt":default:return"text";case"img":return"image";case"loc":return"location";case"audio":return"voice";case"video":return"video";case"file":return"file";case"cmd":return"cmd";case"custom":return"custom";case"combine":return"combine";case"text":case"image":case"voice":case"location":return e}}normalizeThreadLastMessageBody(t,r,a){if(!r){return{content:this.readString(a.msg??a.content??a.text)??""}}switch(t){case"text":default:return{content:this.readString(r.msg??r.content??r.text)??""};case"image":{const t=this.readString(r.url)??"",a=e.deriveImageUrls(t,{deriveVariants:!this.useCustomAttachmentUpload});return{localUrl:"",filename:this.readString(r.filename)??"image",filetype:this.readString(r.filetype)??"application/octet-stream",width:this.toFiniteNumber(r.width)??0,height:this.toFiniteNumber(r.height)??0,isGif:!0===r.isGif,isOriginalImage:!1,originalImageUrl:a.originalImageUrl,bigImageUrl:a.bigImageUrl,thumbnailUrl:this.readString(r.thumb)??a.thumbnailUrl,secret:this.readString(r.secret),fileLength:this.toFiniteNumber(r.file_length??r.fileLength)}}case"voice":return{url:this.readString(r.url)??"",filename:this.readString(r.filename)??"voice",filetype:this.readString(r.filetype)??"application/octet-stream",duration:this.toFiniteNumber(r.duration??r.length)??0,secret:this.readString(r.secret),fileLength:this.toFiniteNumber(r.file_length??r.fileLength)};case"video":return{url:this.readString(r.url)??"",filename:this.readString(r.filename)??"video",filetype:this.readString(r.filetype)??"application/octet-stream",duration:this.toFiniteNumber(r.duration??r.length)??0,width:this.toFiniteNumber(r.width),height:this.toFiniteNumber(r.height),thumbnailUrl:this.readString(r.thumb),secret:this.readString(r.secret),fileLength:this.toFiniteNumber(r.file_length??r.fileLength)};case"file":return{url:this.readString(r.url)??"",filename:this.readString(r.filename)??"file",filetype:this.readString(r.filetype)??"application/octet-stream",secret:this.readString(r.secret),fileLength:this.toFiniteNumber(r.file_length??r.fileLength)};case"location":return{latitude:this.toFiniteNumber(r.lat??r.latitude)??0,longitude:this.toFiniteNumber(r.lng??r.longitude)??0,address:this.readString(r.addr??r.address),buildingName:this.readString(r.buildingName)};case"cmd":return{action:this.readString(r.action)??""};case"custom":return{event:this.readString(r.event??r.customEvent)??"",params:E(r.params??r.customExts)?r.params??r.customExts:{}};case"combine":return{title:this.readString(r.title)??"",summary:this.readString(r.summary)??"",filename:this.readString(r.filename)??"combine",filetype:"application/octet-stream",url:this.readString(r.url),secret:this.readString(r.secret),fileLength:this.toFiniteNumber(r.file_length??r.fileLength),combineLevel:this.toFiniteNumber(r.combineLevel)??0}}}readString(e){return"string"==typeof e&&e.length>0?e:void 0}numberField(e,t){const r=this.toFiniteNumber(t);return void 0===r?{}:{[e]:r}}parseMetaPayload(e){const t=this.normalizeMetaPayload(e);if(t){if(0===t.length)return null;try{const e=JSON.parse(T(t));return E(e)?e:null}catch{return null}}if(E(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return E(t)?t:null}catch{return null}return null}toFiniteNumber(e){const t="number"==typeof e?e:"string"==typeof e?Number(e):Number.NaN;return Number.isFinite(t)?t:void 0}resolveReactions(e){const t=this.parseMetaPayload(e),r=t?.reaction;if(Array.isArray(r)&&0!==r.length)return r.filter(E).map(e=>({reaction:"string"==typeof e.reaction?e.reaction:"",count:"number"==typeof e.count?e.count:0,userList:Array.isArray(e.userList)?e.userList.filter(e=>"string"==typeof e):[],isAddedBySelf:"boolean"==typeof e.state?e.state:void 0}))}normalizeMetaPayload(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):null}}class M{constructor(e,t){this.chatThreadId=e,this.manager=t}getInfo(){return this.manager.getChatThreadInfo({chatThreadId:this.chatThreadId})}refresh(){return this.getInfo()}join(){return this.manager.joinChatThread({chatThreadId:this.chatThreadId})}leave(){return this.manager.leaveChatThread({chatThreadId:this.chatThreadId})}destroy(){return this.manager.destroyChatThread({chatThreadId:this.chatThreadId})}updateName(e){return this.manager.updateChatThreadName({chatThreadId:this.chatThreadId,name:e.name})}getMemberList(e={}){return this.manager.getChatThreadMemberList({chatThreadId:this.chatThreadId,...e})}removeMember(e){return this.manager.removeChatThreadMember({chatThreadId:this.chatThreadId,memberId:e.memberId})}}const L=t=>new e.ValidationError(`${t} is required`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}}),w=(t,r)=>new e.ValidationError(r,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:r,rule:"invalid_format"}]}}),U=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw L(t);return e.trim()},$=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw w(t,`${t} must be a string`);return e},x=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw w(t,`${t} must be an integer between 1 and 50`);return e},P=t=>{const{orgName:r,appName:a}=e.parseAppKey(t.appKey);return{orgName:r,appName:a,encodedUserId:encodeURIComponent(t.userId),encodedResource:encodeURIComponent(t.clientResource)}},D=e=>t.isRecord(e)?e:null,F=e=>{const t=D(e);return t?.data??e},V=e=>{const t=D(e);if(Array.isArray(t?.entities))return t.entities;const r=F(e);if(Array.isArray(r))return r;const a=D(r);return Array.isArray(a?.entities)?a.entities:Array.isArray(a?.affiliations)?a.affiliations:[]},j=e=>{const t=D(e),r=D(t?.data),a=D(t?.properties);return("string"==typeof r?.cursor?r.cursor:void 0)??("string"==typeof a?.cursor?a.cursor:void 0)??("string"==typeof t?.cursor?t.cursor:void 0)??""},k=e=>{const r=D(e);if(!r)return null;const a=("string"==typeof r.id?r.id:void 0)??("string"==typeof r.msgId?r.msgId:void 0);if(!a)return null;const i="number"==typeof r.timestamp?r.timestamp:0,s=r.payload,o="string"==typeof s?t.safeJsonParse(s,{}):D(s)??{},n=Array.isArray(o.bodies)?o.bodies:[];if(n.length>=2){const e=new A("").composeThreadBodies(n);if("multi_body"===e?.type&&Array.isArray(e.body))return{msgId:a,type:"multi_body",body:e.body.map(e=>({...e})),timestamp:i}}const d=D(n[0])??{};return{msgId:a,type:("string"==typeof d.type?d.type:void 0)??("string"==typeof o.type?o.type:void 0)??"",body:d,timestamp:i}},z=e=>{const t=D(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.thread_id?t.thread_id:void 0)??("string"==typeof t.chatThreadId?t.chatThreadId:void 0),a=("string"==typeof t.parentId?t.parentId:void 0)??("string"==typeof t.groupId?t.groupId:void 0)??("string"==typeof t.group_id?t.group_id:void 0),i="string"==typeof t.name?t.name:"";return r&&a&&i?{chatThreadId:r,parentId:a,name:i,ownerId:"string"==typeof t.owner?t.owner:void 0,memberCount:"number"==typeof t.affiliationsCount?t.affiliationsCount:"number"==typeof t.affiliations_count?t.affiliations_count:void 0,messageCount:"number"==typeof t.messageCount?t.messageCount:"number"==typeof t.message_count?t.message_count:void 0,createdAt:"number"==typeof t.created?t.created:"number"==typeof t.createTimestamp?t.createTimestamp:void 0,lastMessage:k(t.lastMessage??t.last_message)}:null},q=e=>({items:V(e).map(e=>z(e)).filter(e=>null!==e),cursor:j(e)}),B=async(e,t,r)=>{const a=P(t),i=U(r,"chatThreadId");return(e=>{const t=F(e),r=Array.isArray(t)?t[0]:t,a=z(r);if(!a)throw w("response.data","response.data is invalid");return a})(await e.get(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(i)}`,{operation:"getChatThreadInfo"}))},G=async(e,t,r)=>{const a=P(t),s=U(r.chatThreadId,"params.chatThreadId"),o=x(r.pageSize,"params.pageSize"),n=$(r.cursor,"params.cursor"),d=i.createQueryParams({limit:String(o),cursor:n}),u=await e.get(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(s)}/users?${d.toString()}`,{operation:"getChatThreadMemberList"});return{items:V(h=u).map(e=>{if("string"==typeof e)return{memberId:e};const t=D(e);if(!t)return null;const r=("string"==typeof t.memberId?t.memberId:void 0)??("string"==typeof t.user?t.user:void 0)??("string"==typeof t.username?t.username:void 0);return r?{memberId:r,joinedAt:"number"==typeof t.joinedAt?t.joinedAt:void 0}:null}).filter(e=>null!==e),cursor:j(h)};var h},K=async(e,t,r)=>{const a=P(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw L("params.chatThreadIds");if(r.chatThreadIds.length>20)throw w("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const i=r.chatThreadIds.map((e,t)=>U(e,`params.chatThreadIds[${t}]`)),s=await e.post(`/${a.orgName}/${a.appName}/thread/message`,{threadIds:i},{operation:"getChatThreadLastMessageList"});return{items:V(s).map(e=>{const t=D(e);if(!t)return null;const r=("string"==typeof t.chatThreadId?t.chatThreadId:void 0)??("string"==typeof t.thread_id?t.thread_id:void 0);return r?{chatThreadId:r,lastMessage:k(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},H=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{common:{},apis:{createChatThread:{range:"4,110,201,210,301,303,606",localErrors:{createChatThread:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},service_limit_exceeded:{code:4,httpStatus:400,retryable:!1,aliases:["limit_exceeded"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getJoinedChatThreadList:{range:"110,201,210,301,303,606",localErrors:{getJoinedChatThreadList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","GROUP_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadInfo:{range:"110,201,210,301,303,606",localErrors:{getChatThreadInfo:{validation_invalid:{code:110,retryable:!1}},getInfo:{validation_invalid:{code:110,retryable:!1}},refresh:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},joinChatThread:{range:"4,110,201,210,301,303,606",localErrors:{joinChatThread:{validation_invalid:{code:110,retryable:!1}},join:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},service_limit_exceeded:{code:4,httpStatus:400,retryable:!1,aliases:["limit_exceeded"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},leaveChatThread:{range:"110,201,210,301,303,606",localErrors:{leaveChatThread:{validation_invalid:{code:110,retryable:!1}},leave:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},destroyChatThread:{range:"110,201,210,301,303,606",localErrors:{destroyChatThread:{validation_invalid:{code:110,retryable:!1}},destroy:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},updateChatThreadName:{range:"110,201,210,301,303,606",localErrors:{updateChatThreadName:{validation_invalid:{code:110,retryable:!1}},updateName:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadMemberList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadMemberList:{validation_invalid:{code:110,retryable:!1}},getMemberList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},removeChatThreadMember:{range:"110,201,210,301,303,606",localErrors:{removeChatThreadMember:{validation_invalid:{code:110,retryable:!1}},removeMember:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}},getChatThreadLastMessageList:{range:"110,201,210,301,303,606",localErrors:{getChatThreadLastMessageList:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,httpStatus:401,retryable:!1,aliases:["unauthorized"]},permission_denied:{code:210,httpStatus:403,retryable:!1,aliases:["group_authorization","forbidden"]},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","THREAD_NOT_FOUND"]},request_timeout:{code:301,httpStatus:504,retryable:!0,aliases:["timeout"]},service_error:{code:303,httpStatus:500,retryable:!0,aliases:["server_unknown_error"]}}}}}),J=class{constructor(){this.capabilities=["rawNotify:chatThread"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.registry=new Map}bind(e,t){this.client=e,this.eventContext=t??null,this.registry.clear()}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}handleRawNotify(e){if("chatThread"!==e.type)return;const t=this.buildChatThreadPublicEvent(e.payload);t&&this.eventContext?.dispatch?.(t.eventName,t.payload)}getChatThread(t){const r=t.trim();if(0===r.length)throw new e.ValidationError("chatThreadId is required",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadId",message:"chatThreadId is required",rule:"required"}]}});const a=this.registry.get(r);if(a)return a;const i=new M(r,this);return this.registry.set(r,i),i}async createChatThread(e){return this.runOperation("createChatThread",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const a=P(t),i=U(r.parentId,"params.parentId"),s=U(r.name,"params.name"),o=U(r.messageId,"params.messageId"),n=await e.post(`/${a.orgName}/${a.appName}/thread?resource=${a.encodedResource}`,{name:s,msg_id:o,group_id:i,owner:t.userId},{operation:"createChatThread"}),d=D(F(n)),u="string"==typeof d?.thread_id?d.thread_id:void 0;if(!u)throw w("response.data.thread_id","response.data.thread_id is invalid");return{chatThreadId:u}})(this.getRestClient(t),t,e)})}async getChatThreadList(e){return this.runOperation("getChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const a=P(t),s=U(r.parentId,"params.parentId"),o=x(r.pageSize,"params.pageSize"),n=$(r.cursor,"params.cursor"),d=i.createQueryParams({limit:String(o),cursor:n}),u=await e.get(`/${a.orgName}/${a.appName}/threads/chatgroups/${encodeURIComponent(s)}?${d.toString()}`,{operation:"getChatThreadList"});return q(u)})(this.getRestClient(t),t,e)})}async getJoinedChatThreadList(e={}){return this.runOperation("getJoinedChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r={})=>{const a=P(t),s=x(r.pageSize,"params.pageSize"),o=$(r.cursor,"params.cursor"),n=i.createQueryParams({limit:String(s),cursor:o}),d="string"==typeof r.parentId&&r.parentId.trim().length>0?`/${a.orgName}/${a.appName}/threads/chatgroups/${encodeURIComponent(r.parentId.trim())}/user/${a.encodedUserId}?${n.toString()}`:`/${a.orgName}/${a.appName}/threads/user/${a.encodedUserId}?${n.toString()}`,u=await e.get(d,{operation:"getJoinedChatThreadList"});return q(u)})(this.getRestClient(t),t,e)})}async getChatThreadInfo(e){return this.runOperation("getChatThreadInfo",async()=>{const t=this.getRestContextOrThrow();return B(this.getRestClient(t),t,e.chatThreadId)})}async joinChatThread(e){return this.runOperation("joinChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=P(t),i=U(r,"chatThreadId");await e.post(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(i)}/user/${a.encodedUserId}/join?resource=${a.encodedResource}`,void 0,{operation:"joinChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async leaveChatThread(e){return this.runOperation("leaveChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=P(t),i=U(r,"chatThreadId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(i)}/user/${a.encodedUserId}/quit?resource=${a.encodedResource}`,{operation:"leaveChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async destroyChatThread(e){return this.runOperation("destroyChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=P(t),i=U(r,"chatThreadId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(i)}?resource=${a.encodedResource}`,{operation:"destroyChatThread"})})(this.getRestClient(t),t,e.chatThreadId)})}async updateChatThreadName(e){return this.runOperation("updateChatThreadName",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=P(t),i=U(r.chatThreadId,"params.chatThreadId"),s=U(r.name,"params.name");await e.put(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(i)}?resource=${a.encodedResource}`,{name:s},{operation:"updateChatThreadName"})})(this.getRestClient(t),t,e)})}async getChatThreadMemberList(e){return this.runOperation("getChatThreadMemberList",async()=>{const t=this.getRestContextOrThrow();return G(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const a=P(t),i=U(r.chatThreadId,"params.chatThreadId"),s=U(r.memberId,"params.memberId");await e.delete(`/${a.orgName}/${a.appName}/thread/${encodeURIComponent(i)}/users/${encodeURIComponent(s)}?resource=${a.encodedResource}`,{operation:"removeChatThreadMember"})})(this.getRestClient(t),t,e)})}async getChatThreadLastMessageList(e){return this.runOperation("getChatThreadLastMessageList",async()=>{const t=this.getRestContextOrThrow();return K(this.getRestClient(t),t,e)})}getClientOrThrow(){if(!this.client)throw new e.ValidationError("ChatThreadManager is not bound to client",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadManager.client",message:"ChatThreadManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getEventContextOrThrow(){if(!this.eventContext)throw new e.ValidationError("ChatThreadManager is not bound to event context",{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadManager.eventContext",message:"ChatThreadManager is not bound to event context",rule:"required"}]}});return this.eventContext}getRestClient(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:H,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}async runOperation(t,r){try{return await r()}catch(a){if(a instanceof e.SDKError)throw a;const r=a instanceof Error?a.message:String(a);throw new e.SDKError(`ChatThreadManager ${t} failed: ${r}`,e.ERROR_CODES.UNKNOWN)}}buildChatThreadPublicEvent(e){const t=e.payload,r="string"==typeof t.id?t.id:"",a="string"==typeof t.muc_parent_id?t.muc_parent_id:"";if(!r||!a)return null;const i="string"==typeof t.msg_parent_id?t.msg_parent_id:void 0,s="string"==typeof t.name?t.name:void 0,o="number"==typeof t.message_count?t.message_count:void 0,n=t.last_message&&"object"==typeof t.last_message?this.tryBuildThreadMessageSnippet(t.last_message):void 0,d="number"==typeof t.timestamp?t.timestamp:0,u="string"==typeof t.from?t.from:void 0,h={chatThreadId:r,parentId:a,name:s??"",messageId:i,messageCount:o,lastMessage:n};switch(t.operation){case"create":return{eventName:"onChatThreadCreated",payload:{chatThreadId:r,parentId:a,operatorId:u,chatThreadName:s,messageId:i,thread:h,timestamp:d}};case"update":case"update_msg":return{eventName:"onChatThreadUpdated",payload:{chatThreadId:r,parentId:a,operatorId:u,chatThreadName:s,messageId:i,messageCount:o,lastMessage:n,thread:h,timestamp:d}};case"delete":return{eventName:"onChatThreadDestroyed",payload:{chatThreadId:r,parentId:a,operatorId:u,timestamp:d}};case"kick":return{eventName:"onChatThreadUserRemoved",payload:{chatThreadId:r,parentId:a,operatorId:u,memberId:t.userIds?.[0],timestamp:d}};default:return null}}tryBuildThreadMessageSnippet(e){const t=("string"==typeof e.id?e.id:void 0)??("string"==typeof e.msgId?e.msgId:void 0);if(!t)return null;const r=e.payload&&"object"==typeof e.payload?e.payload:{};return{msgId:t,type:"string"==typeof r.type?r.type:"",body:r,timestamp:"number"==typeof e.timestamp?e.timestamp:0}}};J.key="chatThreadManager";let Y=J;exports.ChatThread=M,exports.ChatThreadManager=Y,exports.CompressType={COMPRESS_NONE:0,COMPRESS_LZ4:2},exports.ContentType=o,exports.EncryptType={ENCRYPT_NONE:0},exports.ImageType={ORIGINAL:"original",LARGE:"large"},exports.MessagePayloadDecoder=A,exports.MsyncCommand={SYNC:0,UNREAD:1,NOTICE:2,PROVISION:3,LOGOUT:4},exports.MsyncMessageType={NORMAL:0,SINGLECHAT:1,GROUPCHAT:2,CHATROOM:3,READ_ACK:4,DELIVER_ACK:5,RECALL:6,CHANNEL_ACK:7,EDIT:8},exports.NameSpace={STATISTIC:0,CHAT:1,MUC:2,ROSTER:3,NOTIFY:5},exports.ProvisionErrorCode={OK:0,FAIL:1,UNAUTHORIZED:2,MISSING_PARAMETER:3,WRONG_PARAMETER:4,REDIRECT:5,TOKEN_EXPIRED:6,PERMISSION_DENIED:7,NO_ROUTE:8,UNKNOWN_COMMAND:9,PB_PARSER_ERROR:10,BIND_ANOTHER_DEVICE:11,IM_FORBIDDEN:12,TOO_MANY_DEVICES:13,PLATFORM_LIMIT:14,USER_MUTED:15,ENCRYPT_DISABLE:16,ENCRYPT_ENABLE:17,DECRYPT_FAILURE:18,PERMISSION_DENIED_EXTERNAL:19,RESOURCE_CHANGED:20},exports.RouteType={ROUTE_ALL:0,ROUTE_ONLINE:1,ROUTE_DIRECT:2},exports.StreamMessageStatus=s,exports.buildDeviceInfo=t=>{const r=Date.now(),a=t.deviceId,i=t.customOSPlatform,s=void 0!==i?t.customDeviceName:void 0,o=e.getRuntimeGlobal().localStorage,n=()=>{if(!o)return null;try{const t=o.getItem(I);if(!t)return null;const r=JSON.parse(t);if("object"==typeof(e=r)&&null!==e&&!Array.isArray(e)&&"string"==typeof r.deviceId&&"string"==typeof r.deviceName&&"string"==typeof r.deviceUuid)return{deviceId:r.deviceId,deviceName:r.deviceName,deviceUuid:r.deviceUuid}}catch{return null}var e;return null},d=e=>{if(o)try{o.setItem(I,JSON.stringify(e))}catch{}},u=e=>void 0===i?e:{deviceId:`custom${i}_${e.deviceUuid}`,deviceName:s??a,deviceUuid:e.deviceUuid};if(t.useFixedDeviceId){const e=n();if(e)return u(e);if(a===C){const e=`${S}_${r}`,t=u({deviceId:`${a}_${e}`,deviceName:a,deviceUuid:e});return d(t),t}if(void 0!==i){const e=u({deviceId:`webim_${S}_${a}`,deviceName:a,deviceUuid:`${S}_${r}`});return d(e),e}const t={deviceId:`webim_${S}_${a}`,deviceName:`webim_${S}_${a}`,deviceUuid:`webim_${S}_${a}`};return d(t),t}if(a===C){const e=`random_${S}_${r}`;return u({deviceId:`${a}_${e}`,deviceName:a,deviceUuid:e})}if(void 0!==i){return u({deviceId:`webim_${S}_${a}`,deviceName:a,deviceUuid:`random_${S}_${r}`})}return{deviceId:`webim_${S}_${a}`,deviceName:`webim_${S}_${a}`,deviceUuid:`webim_${S}_${a}`}},exports.buildJid=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),exports.decodeKeyValueList=N,exports.decodeUtf8=T,exports.encodeKeyValueRecord=e=>{const t=[];for(const[r,a]of Object.entries(e))if(void 0!==a)if("boolean"!=typeof a)if("number"!=typeof a)if("string"!=typeof a)try{t.push({key:r,type:b,stringValue:JSON.stringify(a)})}catch{t.push({key:r,type:_,stringValue:Object.prototype.toString.call(a)})}else t.push({key:r,type:_,stringValue:a});else Number.isInteger(a)?t.push({key:r,type:m,varintValue:a}):t.push({key:r,type:f,doubleValue:a});else t.push({key:r,type:c,varintValue:a?1:0});return t},exports.encodeUtf8=e=>{if("function"==typeof TextEncoder)return(new TextEncoder).encode(e);const t=[];for(let r=0;r<e.length;r+=1){let a=e.charCodeAt(r);if(a>=55296&&a<=56319&&r+1<e.length){const t=e.charCodeAt(r+1);t>=56320&&t<=57343&&(a=65536+(a-55296<<10)+(t-56320),r+=1)}a<=127?t.push(a):a<=2047?t.push(192|a>>6,128|63&a):a<=65535?t.push(224|a>>12,128|a>>6&63,128|63&a):t.push(240|a>>18,128|a>>12&63,128|a>>6&63,128|63&a)}return new Uint8Array(t)},exports.isStreamMessage=function(e){return"object"==typeof e.stream&&null!==e.stream},exports.longToString=R,exports.readTranslations=v,exports.toNumericId=e=>{if(/^\d+$/.test(e))return e;const t=r.Long.fromString("1099511628211",!0);let a=r.Long.fromString("1469598103934665603",!0);for(let i=0;i<e.length;i+=1)a=a.xor(r.Long.fromInt(e.charCodeAt(i),!0)).multiply(t).toUnsigned();return a.isZero()?"1":a.toString()},exports.toProtocolTranslations=e=>!e||"object"!=typeof e||Array.isArray(e)?[]:Object.entries(e).filter(([e,t])=>e.trim().length>0&&"string"==typeof t).map(([e,t])=>({code:e,text:t}));
|