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
|
@@ -1 +1 @@
|
|
|
1
|
-
var IMSDK=function(e){"use strict";const t="disconnected",r="connecting",s="connected",n="reconnecting",i="reconnectFailed",o="onConnecting",a="onConnected",c="onDisconnected",d="onReconnectFailed",u="onTokenWillExpire",l="onTokenExpired",h="onOfflineMessageSyncStart",p="onOfflineMessageSyncFinish",m="onSendTimeout",f="onGroupNotify",g="onChatRoomNotify",y="onChatThreadNotify",v="onUserInfoNotify",I="__internal:onMessageSent",b="login",_="reconnect",T="online",C="offline-recover",S="heartbeat-failed",E="send-timeout",w="close",R="error",A="limit",N="offline",O="token-expired",M="onMessage",U="onStreamMessage",L="onConversationListUpdate",k="onMessageReadReceipts",D="onMessageDelivered",P="onMessageRecalled",x="onMessageUpdated",F="onReactionChanged",B="onPinnedMessageChanged",G="onMultiDeviceContact",q="onMultiDeviceConversation",$="onSyncDataStart",j="onSyncDataFinished",V={LOG:"onLog"},K="onPresenceStatusChange",z="onContactInvited",H="onContactDeleted",W="onContactAdded",J="onContactRefuse",Q="onContactAgreed",Z="onContactInfoUpdated",Y="onInvitationReceived",X="onRequestToJoinReceived",ee="onRequestToJoinAccepted",te="onRequestToJoinDeclined",re="onInvitationAccepted",se="onInvitationDeclined",ne="onUserRemoved",ie="onGroupDestroyed",oe="onAutoAcceptInvitationFromGroup",ae="onMuteListAdded",ce="onMuteListRemoved",de="onAllowListAdded",ue="onAllowListRemoved",le="onAllMemberMuteStateChanged",he="onAdminAdded",pe="onAdminRemoved",me="onOwnerChanged",fe="onMembersJoined",ge="onMembersExited",ye="onAnnouncementChanged",ve="onSharedFileAdded",Ie="onSharedFileDeleted",be="onGroupInfoChanged",_e="onGroupDisabledChanged",Te="onGroupMemberAttributeChanged",Ce="onUserGroupNamecardUpdated",Se="__chatroom:onChatRoomDestroyed",Ee="__chatroom:onMembersJoined",we="__chatroom:onMembersExited",Re="__chatroom:onRemovedFromChatRoom",Ae="__chatroom:onMuteListAdded",Ne="__chatroom:onMuteListRemoved",Oe="__chatroom:onAllowListAdded",Me="__chatroom:onAllowListRemoved",Ue="__chatroom:onAllMemberMuteStateChanged",Le="__chatroom:onAdminAdded",ke="__chatroom:onAdminRemoved",De="__chatroom:onOwnerChanged",Pe="__chatroom:onAnnouncementChanged",xe="__chatroom:onChatRoomInfoChanged",Fe="__chatroom:onAttributesUpdate",Be="__chatroom:onAttributesRemoved",Ge={TOKEN_BOUND:"onPushTokenBound",TOKEN_BIND_FAILED:"onPushTokenBindFailed",TOKEN_REMOVE_FAILED:"onPushTokenRemoveFailed"},qe="onChatRoomDestroyed",$e="onMembersJoined",je="onMembersExited",Ve="onRemovedFromChatRoom",Ke="onMuteListAdded",ze="onMuteListRemoved",He="onAllowListAdded",We="onAllowListRemoved",Je="onAllMemberMuteStateChanged",Qe="onAdminAdded",Ze="onAdminRemoved",Ye="onOwnerChanged",Xe="onAnnouncementChanged",et="onChatRoomInfoChanged",rt="onAttributesUpdate",st="onAttributesRemoved",nt={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function it(e){return"object"==typeof e.stream&&null!==e.stream}const ot={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},at="[REDACTED]",ct=e=>{if(!e)return"";const t=e.includes("?"),r=e.includes("#");try{return((e,t,r)=>(e.username&&(e.username=at),e.password&&(e.password=at),e.search=t?`?${at}`:"",e.hash=r?`#${at}`:"",e.toString()))(new URL(e),t,r)}catch{const t=[e.indexOf("?"),e.indexOf("#")].filter(e=>e>=0).sort((e,t)=>e-t)[0];return void 0===t?"[invalid-url]":`${e.slice(0,t)}?${at}`}},dt=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>"url"===e.toLowerCase()&&"string"==typeof t?[e,ct(t)]:[e,t]));class ut extends Error{constructor(e,t=ot.UNKNOWN,r){super(e),this.name="SDKError",this.code=t,this.details=r?.details?dt(r.details):void 0,Error.captureStackTrace&&Error.captureStackTrace(this,ut)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class lt extends ut{constructor(e,t){super(e,t?.code??ot.REST_NETWORK_ERROR,t),this.name="NetworkError"}}class ht extends ut{constructor(e,t){super(e,t?.code??ot.CONNECTION_WEBSOCKET_ERROR,t),this.name="ConnectionError"}}class pt extends ut{constructor(e,t){super(e,t?.code??ot.AUTH_UNAUTHORIZED,t),this.name="AuthenticationError"}}class mt extends ut{constructor(e,t){super(e,t?.code??ot.VALIDATION_UNKNOWN,t),this.name="ValidationError"}}class ft extends ut{constructor(e,t){super(e,t?.code??ot.MESSAGE_SEND_FAILED,t),this.name="MessageSendError"}}class gt extends ut{constructor(e,t){super(e,t?.code??ot.MESSAGE_DECODE_FAILED,t),this.name="MessageReceiveError"}}class yt extends ut{constructor(e,t){super(e,t?.code??ot.STORAGE_OPERATION_FAILED,t),this.name="StorageError"}}class vt extends ut{constructor(e,t){super(e,t?.code??ot.REST_NETWORK_ERROR,t),this.name="RestTransportError"}}class It extends ut{constructor(e,t){super(e,t?.code??ot.REST_BUSINESS_UNKNOWN,t),this.name="RestBusinessError"}}class bt extends ut{constructor(e,t){super(e,t?.code??ot.UPLOAD_REQUEST_FAILED,t),this.name="UploadError"}}const _t=0,Tt=1,Ct=2,St=3,Et=4,wt=0,Rt=1,At=2,Nt=3,Ot=4,Mt=5,Ut=6,Lt=7,kt=8,Dt=0,Pt=1,xt=2,Ft=3,Bt=4,Gt=5,qt=6,$t=7,jt=8,Vt=0,Kt=1,zt=2,Ht=3,Wt=4,Jt=0,Qt=1,Zt=2,Yt=3,Xt=5,er=0,tr=1,rr=2,sr=0,nr=0,ir=2,or=0,ar=1,cr=2,dr=3,ur=4,lr=5,hr=6,pr=7,mr=8,fr=9,gr=10,yr=11,vr=12,Ir=13,br=14,_r=15,Tr=16,Cr=17,Sr=18,Er=19,wr=20,Rr=1,Ar=2,Nr=3,Or=4,Mr=5,Ur=6,Lr=7,kr=8,Dr="Sorry, user register limit",Pr="Sorry, user register rate limit",xr="Sorry, token expired",Fr="Sorry, token or password does not match login info",Br="Sorry, user not found",Gr="Sorry, the app month live count limit",qr="Sorry, the app day live count limit",$r="Sorry, the app online count limit",jr={[ar]:ot.AUTH_UNAUTHORIZED,[cr]:ot.AUTH_UNAUTHORIZED,[dr]:ot.VALIDATION_REQUIRED,[ur]:ot.VALIDATION_INVALID_FORMAT,[lr]:ot.CONNECTION_WEBSOCKET_ERROR,[hr]:ot.AUTH_TOKEN_EXPIRED,[pr]:ot.AUTH_FORBIDDEN,[Er]:ot.AUTH_FORBIDDEN,[mr]:ot.CONNECTION_WEBSOCKET_ERROR,[fr]:ot.UNKNOWN,[gr]:ot.UNKNOWN,[yr]:ot.AUTH_BIND_ANOTHER_DEVICE,[vr]:ot.AUTH_FORBIDDEN,[Ir]:ot.AUTH_LOGIN_TOO_MANY_DEVICES,[br]:ot.SERVICE_LIMIT_EXCEEDED,[_r]:ot.AUTH_USER_MUTED,[Tr]:ot.UNKNOWN,[Cr]:ot.UNKNOWN,[Sr]:ot.MESSAGE_DECODE_FAILED,[wr]:ot.USER_DEVICE_CHANGED},Vr=new Set([ar,cr,dr,ur,hr,pr,Er,fr,gr,yr,vr,Ir,br,_r,Tr,Cr,Sr,wr]),Kr={[Dr]:ot.SERVICE_LIMIT_EXCEEDED,[Pr]:ot.SERVICE_LIMIT_EXCEEDED,[xr]:ot.AUTH_TOKEN_EXPIRED,[Fr]:ot.AUTH_UNAUTHORIZED,[Br]:ot.AUTH_UNAUTHORIZED,blocked:ot.MESSAGE_BLOCKED_BY_RECIPIENT,"group not found":ot.GROUP_NOT_EXIST,"illegal chatroom tag":ot.VALIDATION_REQUIRED,"not in group or chatroom":ot.GROUP_NOT_JOINED,"exceed recall time limit":ot.MESSAGE_RECALL_TIME_LIMIT,"message recall disabled":ot.SERVICE_NOT_ENABLED,"group ack not open":ot.SERVICE_NOT_ENABLED,"group ack msg permission denied":ot.GROUP_PERMISSION_DENIED,"the message has expired":ot.MESSAGE_EXPIRED,"limit send group ack msg":ot.SERVICE_LIMIT_EXCEEDED,"not in group or chatroom white list":ot.MESSAGE_ILLEGAL_WHITELIST,nonroster:ot.USER_NOT_ON_ROSTER,"group is disabled":ot.GROUP_DISABLED,"roaming is not open":ot.SERVICE_NOT_ENABLED,"Sorry, message does not exist":ot.VALIDATION_REQUIRED,"Sorry, edit limit reached":ot.SERVICE_LIMIT_EXCEEDED,"Sorry, You do not have permission":ot.AUTH_FORBIDDEN,"Sorry, format is incorrect":ot.VALIDATION_REQUIRED,"Sorry, edit is not available":ot.SERVER_SERVING_DISABLED,"Sorry, edit fail":ot.MESSAGE_EDIT_FAILED},zr=[["limit directed users",ot.SERVICE_LIMIT_EXCEEDED],["no permission to recall message",ot.AUTH_FORBIDDEN]],Hr={[Gr]:ot.SERVICE_LIMIT_EXCEEDED,[qr]:ot.SERVICE_LIMIT_EXCEEDED,[$r]:ot.SERVICE_LIMIT_EXCEEDED,"sensitive words":ot.MESSAGE_INCLUDE_ILLEGAL_CONTENT,"blocked by mod_antispam":ot.MESSAGE_INCLUDE_ILLEGAL_CONTENT,"user is mute":ot.USER_MUTED_BY_ADMIN,"traffic limit":ot.MESSAGE_CURRENT_LIMITING,"Sorry, data is too large":ot.MESSAGE_SIZE_LIMIT},Wr=(e,t)=>{if("number"!=typeof e)return{code:ot.UNKNOWN,retryable:!0};const r=((e,t)=>{if(t){if(e===ar){const e=Kr[t];if(void 0!==e)return e;for(const[r,s]of zr)if(t.includes(r))return s;try{const e=JSON.parse(t);if("moderation"===e.error_type)return ot.THIRD_MODERATION_FAILED;if("string"==typeof e.error_type)return ot.THIRD_DEFAULT_FAILED}catch{}return}return e===pr?Hr[t]:e===Er?ot.MESSAGE_EXTERNAL_LOGIC_BLOCKED:e===_r?ot.AUTH_USER_MUTED:void 0}})(e,t),s=jr[e]??ot.UNKNOWN;return{code:r??s,retryable:!Vr.has(e)}},Jr={[ot.SERVICE_LIMIT_EXCEEDED]:"Message operation exceeded a service limit",[ot.AUTH_TOKEN_EXPIRED]:"Message cannot be sent because the authentication token expired",[ot.VALIDATION_REQUIRED]:"Message cannot be sent because the request is invalid",[ot.AUTH_UNAUTHORIZED]:"Message cannot be sent because authentication failed",[ot.AUTH_FORBIDDEN]:"Message operation is forbidden",[ot.AUTH_BIND_ANOTHER_DEVICE]:"Message cannot be sent because the account is bound to another device",[ot.AUTH_LOGIN_TOO_MANY_DEVICES]:"Message cannot be sent because the account is logged in on too many devices",[ot.AUTH_USER_MUTED]:"Message cannot be sent because the user is muted in the group or chat room",[ot.MESSAGE_BLOCKED_BY_RECIPIENT]:"Message cannot be sent because you are blocked by the recipient",[ot.USER_MUTED_BY_ADMIN]:"Message cannot be sent because the user is globally muted",[ot.USER_DEVICE_CHANGED]:"Message cannot be sent because the current device has changed",[ot.USER_NOT_ON_ROSTER]:"Message cannot be sent because the recipient is not in your contact list",[ot.CONNECTION_WEBSOCKET_ERROR]:"Message cannot be sent because the server is unreachable",[ot.SERVER_SERVING_DISABLED]:"Message editing is not available",[ot.MESSAGE_DECODE_FAILED]:"Message processing failed",[ot.MESSAGE_INCLUDE_ILLEGAL_CONTENT]:"Message contains prohibited content",[ot.MESSAGE_SEND_TRAFFIC_LIMIT]:"Message sending traffic limit exceeded",[ot.MESSAGE_RECALL_TIME_LIMIT]:"The message recall time limit has been exceeded",[ot.SERVICE_NOT_ENABLED]:"The required messaging service is not enabled",[ot.MESSAGE_EXPIRED]:"The message has expired",[ot.MESSAGE_ILLEGAL_WHITELIST]:"The user is not in the group or chat room allowlist",[ot.MESSAGE_EXTERNAL_LOGIC_BLOCKED]:"The message was blocked by external logic",[ot.MESSAGE_CURRENT_LIMITING]:"Message sending rate limit exceeded",[ot.MESSAGE_SIZE_LIMIT]:"Message size exceeds the limit",[ot.MESSAGE_EDIT_FAILED]:"Message editing failed",[ot.GROUP_NOT_JOINED]:"The user is not in the group or chat room",[ot.GROUP_PERMISSION_DENIED]:"The user does not have permission to perform this group message operation",[ot.GROUP_NOT_EXIST]:"The group does not exist",[ot.GROUP_DISABLED]:"The group is disabled",[ot.THIRD_MODERATION_FAILED]:"The message was rejected by content moderation",[ot.THIRD_DEFAULT_FAILED]:"The message was rejected by a third-party service"},Qr=3e5,Zr=12e4,Yr=[1e3,2e3],Xr={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"},es=e=>"undefined"!=typeof Blob&&e instanceof Blob,ts=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),r=t.length>0?t[t.length-1]:void 0;if(r)return r},rs=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const r=e.slice(t+1).toLowerCase();return Xr[r]},ss=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t&&t.length>0)return t}},ns=e=>{const t=e.file,r=e.sourceMeta,s=t.name||(r?ss(r,["name","fileName","filename"]):void 0),n=e.file.type||(r?ss(r,["type","mimeType","filetype"]):void 0),i=e.file.size||(r?((e,t)=>{for(const r of t){const t=e[r];if("number"==typeof t&&Number.isFinite(t))return t}})(r,["size","fileSize","fileLength"]):void 0),o=is({fileName:s,fileType:n,fileSize:i,fallbackName:e.fallbackName,fallbackMimeType:e.fallbackMimeType,fallbackSize:e.fallbackSize});return{source:{sourceType:"web-file",file:e.file,name:o.fileName,mimeType:o.fileType,size:o.fileSize},fileName:o.fileName,fileType:o.fileType,fileSize:o.fileSize,webFile:e.file}},is=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),os=e=>{const{file:t,fallbackName:r,fallbackMimeType:s,fallbackSize:n}=e,i=(e=>{if(es(e))return e;if("object"!=typeof e||null===e)return;const t=e;for(const r of["file","originFileObj","raw","blob"]){const e=t[r];if(es(e))return e}})(t);if(i)return ns({file:i,fallbackName:r,fallbackMimeType:s,fallbackSize:n,sourceMeta:"object"==typeof t&&null!==t?t:void 0});if((e=>"object"==typeof e&&null!==e&&"path"in e)(t)){const e=ts(t.path),i=is({fileName:t.name??e,fileType:t.type??rs(t.name??e),fileSize:t.size,fallbackName:r,fallbackMimeType:s,fallbackSize:n});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=ts(t.uri),i=is({fileName:t.name??e,fileType:t.type??rs(t.name??e),fileSize:t.size,fallbackName:r,fallbackMimeType:s,fallbackSize:n});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 o=is({fallbackName:r,fallbackMimeType:s,fallbackSize:n});return{source:{sourceType:"web-file",name:o.fileName,mimeType:o.fileType,size:o.fileSize},fileName:o.fileName,fileType:o.fileType,fileSize:o.fileSize}},as=5242880,cs=5242880,ds="CHAT",us="GROUP",ls="ROOM",hs="original",ps="large",ms=e=>/^https?:\/\//i.test(e),fs=e=>{const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw new bt("Invalid appKey for upload",{code:ot.UPLOAD_INVALID_APPKEY,details:{appKey:e}});return{orgName:t[0],appName:t[1]}},gs=e=>"singleChat"===e?ds:"groupChat"===e?us:ls,ys=(e,t)=>Is(e,{size:t}),vs=e=>{try{return decodeURIComponent(e)}catch{return e}},Is=(e,t)=>{const[r="",s]=e.split("#",2),[n,i=""]=r.split("?",2),o=i.split("&").filter(Boolean);return Object.entries(t).forEach(([e,t])=>{const r=encodeURIComponent(e),s=o.filter(t=>{const[s=""]=t.split("=",2);return s!==r&&vs(s)!==e});o.length=0,o.push(...s),void 0!==t&&o.push(`${r}=${encodeURIComponent(String(t))}`)}),`${n}${o.length>0?`?${o.join("&")}`:""}${s?`#${s}`:""}`},bs=(e,t)=>{if(!e)return"";const r={};return e.includes("em-redirect")||(r["em-redirect"]="true"),t&&!e.includes("share-secret=")&&(r["share-secret"]=t),0===Object.keys(r).length?e:Is(e,r)},_s=e=>{const t=(r=e.messageType,s=e.imageType,"image"!==r?"attachment":s===hs?"image-origin":"image-big");var r,s;const n=(e=>"image-origin"===e?204800:1048576)(t),i=e.fileSize>n;return{shouldPrecheck:i,thresholdType:t,thresholdBytes:n,actualBytes:e.fileSize,reason:i?"threshold-exceeded":"below-threshold"}},Ts=(e,t)=>{if(!e)return{};if(!1===t?.deriveVariants)return{originalImageUrl:e};const r=(e=>{const[t="",r]=e.split("#",2),[s,n=""]=t.split("?",2),i=n.split("&").filter(Boolean).filter(e=>{const[t="",r=""]=e.split("=",2),s=vs(t),n=vs(r);return"size"!==s||!["big","large","thumbnail","small"].includes(n)}).join("&");return`${s}${i?`?${i}`:""}${r?`#${r}`:""}`})(e);return{originalImageUrl:r,bigImageUrl:ys(r,"large"),thumbnailUrl:ys(r,"small")}},Cs=e=>e===hs?"origin":"large",Ss=e=>2===e?ps:hs,Es=e=>{const t=e.response.entities?.[0];if(!t?.uuid)throw new bt("Upload response missing uuid",{code:ot.UPLOAD_REQUEST_FAILED,details:{response:e.response}});const r=t["share-secret"],s=t["file-metadata"]??{},n="number"==typeof s["content-length"]?s["content-length"]:e.fallbackSize,i="string"==typeof s["content-type"]?s["content-type"]:e.fileType,o=`${e.restBaseUrl}/${e.orgName}/${e.appName}/chatfiles/${t.uuid}`;if("image"===e.messageType){const t=(e.imageType??ps)===hs;return{...Ts(o,{deriveVariants:!e.useCustomAttachmentUpload}),isOriginalImage:t,secret:r,fileLength:n,filetype:i,filename:e.fileName,width:e.width,height:e.height}}const a="video"===e.messageType?`${o}?vframe=true`:void 0;return{url:o,secret:r,fileLength:n,filetype:i,filename:e.fileName,thumbnailUrl:a}},ws=e=>new Promise(t=>{setTimeout(t,e)});const Rs=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(" "):"",r=t?`${e.message} ${t}`:e.message;return`${e.timestamp} [${e.level}] ${r}`}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 r=e;for(;r.length>this.maxChunkBytes;)t.push(r.slice(0,this.maxChunkBytes)),r=r.slice(this.maxChunkBytes);return r.length>0&&t.push(r),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 ws(this.chunkDelayMs)}}finally{this.reporting=!1}}}async reportChunk(e){if(!this.canReport())return!1;const{restBaseUrl:t,appKey:r,userId:s,token:n,resource:i,requestAdapter:o}=this.context;if(!(t&&r&&s&&n&&o))return!1;let a="",c="";try{const e=fs(r);a=e.orgName,c=e.appName}catch{return!1}const d=`${t}/${a}/${c}/sdk/users/${s}/client/logs`,u={resource:i??"webim",logContent:e};try{const e=await o.request({url:d,method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json"},body:u,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}}},As="[MASKED]",Ns=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),Os=e=>!!e&&Ns.has((e=>e.toLowerCase())(e)),Ms=(e,t,r)=>{const s=r??new WeakSet;if("string"==typeof e)return((e,t)=>Os(t)?As: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:(n=e).name,message:n.message};var n;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>Ms(e,void 0,s));if("object"==typeof e){if(s.has(e))return"[Circular]";if(s.add(e),(e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Date||e instanceof Error))(e)){const t={};for(const[r,n]of Object.entries(e))Os(r)?t[r]=As:t[r]=Ms(n,r,s);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},Us="undefined"!=typeof document;let Ls=null,Ds=!1;const Ps={DEBUG:0,WARN:1,ERROR:2};class xs{constructor(e="WARN"){this.consoleEnabled=!0,this.level=e}setLevel(e){this.level=e}setConsoleEnabled(e){this.consoleEnabled=e}shouldLog(e){return Ps[e]>=Ps[this.level]}emit(e,t,r){const s=(e=>{const t=new WeakSet;return e.map(e=>Ms(e,void 0,t))})(r),n=((e,t,r)=>({timestamp:(new Date).toISOString(),level:e,message:t,args:r}))(e,t,s);if(Rs.append(n),this.consoleEnabled){const r=new Date,n=`[Chat][${e}][${`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}:${String(r.getSeconds()).padStart(2,"0")}.${String(r.getMilliseconds()).padStart(3,"0")}`}]`;Us?console.log(`%c${n}`,"color: rgb(0, 157, 255); font-weight: bold",t,...s):console.log(n,t,...s)}const i=Ls;i&&!Ds&&Promise.resolve().then(()=>{if(i===Ls){Ds=!0;try{i(n)}catch{}finally{Ds=!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 Fs=new xs;function Bs(e){Rs.setState(e)}function Gs(e){Rs.updateContext(e)}async function qs(){await Rs.reportNow()}function $s(){Rs.stop()}const js=(e,...t)=>Fs.debug(e,...t),Vs=(e,...t)=>Fs.warn(e,...t),Ks=(e,...t)=>Fs.error(e,...t),zs=e=>{if("function"==typeof TextEncoder)return(new TextEncoder).encode(e);const t=[];for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>=55296&&s<=56319&&r+1<e.length){const t=e.charCodeAt(r+1);t>=56320&&t<=57343&&(s=65536+(s-55296<<10)+(t-56320),r+=1)}s<=127?t.push(s):s<=2047?t.push(192|s>>6,128|63&s):s<=65535?t.push(224|s>>12,128|s>>6&63,128|63&s):t.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s)}return new Uint8Array(t)},Hs=e=>{if("function"==typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let r=0;r<e.length;r+=1){const s=e[r]??0;if(s<128){t+=String.fromCharCode(s);continue}if(s>=192&&s<224){const n=e[r+1]??0;t+=String.fromCharCode((31&s)<<6|63&n),r+=1;continue}if(s>=224&&s<240){const n=e[r+1]??0,i=e[r+2]??0;t+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&i),r+=2;continue}const n=((7&s)<<18|(63&(e[r+1]??0))<<12|(63&(e[r+2]??0))<<6|63&(e[r+3]??0))-65536;t+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),r+=3}return t};class Ws{constructor(){this.lastEventKey=null}normalize(e,u){const l=(e=>{switch(e){case r:case n:return o;case s:return a;case t:return c;case i:return d;default:return null}})(e);if(!l)return null;const h=((e,t)=>[e,t.state,t.reason,String(t.attempt),String(t.maxAttempts),String(t.isLoginPhase),String(t.isOnline),String(t.errorCode??""),t.errorMessage??""].join("|"))(l,u);return this.lastEventKey===h?null:(this.lastEventKey=h,{eventName:l,payload:u})}reset(){this.lastEventKey=null}}const Js={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"},Qs="init",Zs="request",Ys="upload",Xs="socket",en="proto",tn="runtime",rn="PLATFORM_INIT_FAILED",sn="PLATFORM_MISSING_CAPABILITY",nn="PLATFORM_REQUEST_FAILED",on="PLATFORM_UPLOAD_FAILED",an="PLATFORM_SOCKET_FAILED",cn="PLATFORM_PROTO_FAILED",dn=(e,t)=>{const r=new Error(e);return r.name="PlatformAdapterError",r.code=t.code,r.stage=t.stage,r.retryable=t.retryable,t.details&&(r.details=dt(t.details)),r},un=0,ln=1,hn=2,pn=3,mn=["__uniConfig","skipWaiting","registration","navigator","process","window","document","localStorage","fetch","WebSocket","XMLHttpRequest","FormData","TextEncoder","TextDecoder","crypto"],fn=e=>{if(e)return e;return((e,t)=>{if(!e)return t;if(0===Object.keys(t).length)return e;const r={},s=e;for(const n of mn)try{const e=s[n];void 0!==e&&(r[n]=e)}catch{}for(const n of Object.keys(t))r[n]=t[n];return r})("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}:{}})},gn={web:Js.WEB,"mp-weixin":Js.WECHAT_MINIAPP,"mp-alipay":Js.ALIPAY_MINIAPP,"mp-baidu":Js.BAIDU_MINIAPP,"mp-toutiao":Js.TOUTIAO_MINIAPP,"mp-lark":Js.LARK_MINIAPP,"mp-qq":Js.QQ_MINIAPP,"mp-kuaishou":Js.KUAISHOU_MINIAPP,"mp-jd":Js.JD_MINIAPP,"mp-360":Js.MINIAPP_360,"mp-harmony":Js.HARMONY_MINIAPP,"quickapp-webview":Js.QUICKAPP,"quickapp-webview-union":Js.QUICKAPP,"quickapp-webview-huawei":Js.QUICKAPP},yn=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},vn=e=>(e=>yn(e,"canIUse")&&yn(e,"getSystemInfo"))(e)||(e=>yn(e,"request")&&yn(e,"connectSocket"))(e),In=e=>yn(e,"request")&&yn(e,"connectSocket")&&yn(e,"uploadFile"),bn=(e,t)=>t===Js.WECHAT_MINIAPP?e.wx:t===Js.QQ_MINIAPP?e.qq:t===Js.TOUTIAO_MINIAPP?e.tt:t===Js.BAIDU_MINIAPP?e.swan:t===Js.ALIPAY_MINIAPP?e.my:t===Js.DINGTALK_MINIAPP?e.dd:t===Js.JD_MINIAPP?e.jd:t===Js.KUAISHOU_MINIAPP?e.ks:t===Js.UNIAPP?e.uni:void 0,_n=e=>{const t=e?.miniGlobal;return vn(t)?t:e},Tn=e=>{const t=_n(e);return In(t)?t:void 0},Cn=e=>void 0!==e.window&&void 0!==e.document,Sn=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),En=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;if(vn(t))return!0;try{if(!yn(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},wn=e=>In(e.wx)?Js.WECHAT_MINIAPP:In(e.my)?Js.ALIPAY_MINIAPP:In(e.dd)?Js.DINGTALK_MINIAPP:In(e.swan)?Js.BAIDU_MINIAPP:In(e.tt)?Js.TOUTIAO_MINIAPP:In(e.qq)?Js.QQ_MINIAPP:In(e.jd)?Js.JD_MINIAPP:In(e.ks)?Js.KUAISHOU_MINIAPP:void 0,Rn=e=>void 0!==wn(e),An=e=>{const t=wn(e);if(t)return t;try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;if("string"==typeof r)return gn[r]??Js.UNIAPP}catch{return Js.UNIAPP}return Cn(e)?Js.WEB:Js.UNIAPP},Nn=(e,t)=>{const r=Tn(bn(e,t));if(r)return r;const s=Tn(e.uni);return s||(e.uni??e)},On=(e,t)=>{const r=e??fn();if(t){const e=t===Js.UNIAPP||En(r),s=e?An(r):t;return{platform:t,hostPlatform:s,framework:e?"uniapp":Cn(r)?"web":"native",global:e?Nn(r,s):_n(bn(r,t))??r}}if(En(r)){const e=An(r);return{platform:Js.UNIAPP,hostPlatform:e,framework:"uniapp",global:Nn(r,e)}}return vn(r.swan)?{platform:Js.BAIDU_MINIAPP,hostPlatform:Js.BAIDU_MINIAPP,framework:"native",global:_n(r.swan)??r.swan}:vn(r.tt)?{platform:Js.TOUTIAO_MINIAPP,hostPlatform:Js.TOUTIAO_MINIAPP,framework:"native",global:_n(r.tt)??r.tt}:vn(r.dd)?{platform:Js.DINGTALK_MINIAPP,hostPlatform:Js.DINGTALK_MINIAPP,framework:"native",global:_n(r.dd)??r.dd}:vn(r.my)?{platform:Js.ALIPAY_MINIAPP,hostPlatform:Js.ALIPAY_MINIAPP,framework:"native",global:_n(r.my)??r.my}:vn(r.wx)?{platform:Js.WECHAT_MINIAPP,hostPlatform:Js.WECHAT_MINIAPP,framework:"native",global:_n(r.wx)??r.wx}:vn(r.qq)?{platform:Js.QQ_MINIAPP,hostPlatform:Js.QQ_MINIAPP,framework:"native",global:_n(r.qq)??r.qq}:vn(r.jd)?{platform:Js.JD_MINIAPP,hostPlatform:Js.JD_MINIAPP,framework:"native",global:_n(r.jd)??r.jd}:vn(r.ks)?{platform:Js.KUAISHOU_MINIAPP,hostPlatform:Js.KUAISHOU_MINIAPP,framework:"native",global:_n(r.ks)??r.ks}:(e=>"ReactNative"===e.navigator?.product)(r)?{platform:Js.REACT_NATIVE,hostPlatform:Js.REACT_NATIVE,framework:"react-native",global:r}:(e=>"string"==typeof e.process?.versions?.electron)(r)?{platform:Cn(r)?Js.ELECTRON_RENDERER:Js.ELECTRON_MAIN,hostPlatform:Cn(r)?Js.ELECTRON_RENDERER:Js.ELECTRON_MAIN,framework:"electron",global:r}:Sn(r)||Cn(r)?{platform:Js.WEB,hostPlatform:Js.WEB,framework:Sn(r)?"worker":"web",global:r}:{platform:Js.UNKNOWN,hostPlatform:Js.UNKNOWN,framework:"native",global:r}},Mn=e=>e===Js.WECHAT_MINIAPP||e===Js.QQ_MINIAPP||e===Js.TOUTIAO_MINIAPP||e===Js.BAIDU_MINIAPP||e===Js.ALIPAY_MINIAPP||e===Js.DINGTALK_MINIAPP||e===Js.LARK_MINIAPP||e===Js.KUAISHOU_MINIAPP||e===Js.JD_MINIAPP||e===Js.MINIAPP_360||e===Js.HARMONY_MINIAPP||e===Js.QUICKAPP||e===Js.UNIAPP,Un=["request","upload","socket","proto"],Ln=(e,t=Un)=>{const r=((e,t=Un)=>t.filter(t=>!e[t]))(e,t);if(0!==r.length)throw dn("Platform missing required capabilities.",{code:sn,stage:Qs,retryable:!1,details:{required:[...t],missing:r}})};var kn=null;try{kn=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Dn(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function Pn(e){return!0===(e&&e.__isLong__)}function xn(e){var t=Math.clz32(e&-e);return e?31-t:t}Dn.prototype.__isLong__,Object.defineProperty(Dn.prototype,"__isLong__",{value:!0}),Dn.isLong=Pn;var Fn={},Bn={};function Gn(e,t){var r,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=Bn[e])?s:(r=$n(e,0,!0),n&&(Bn[e]=r),r):(n=-128<=(e|=0)&&e<128)&&(s=Fn[e])?s:(r=$n(e,e<0?-1:0,!1),n&&(Fn[e]=r),r)}function qn(e,t){if(isNaN(e))return t?Zn:Qn;if(t){if(e<0)return Zn;if(e>=Hn)return ri}else{if(e<=-Wn)return si;if(e+1>=Wn)return ti}return e<0?qn(-e,t).neg():$n(e%zn|0,e/zn|0,t)}function $n(e,t,r){return new Dn(e,t,r)}Dn.fromInt=Gn,Dn.fromNumber=qn,Dn.fromBits=$n;var jn=Math.pow;function Vn(e,t,r){if(0===e.length)throw Error("empty string");if("number"==typeof t?(r=t,t=!1):t=!!t,"NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return t?Zn:Qn;if((r=r||10)<2||36<r)throw RangeError("radix");var s;if((s=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return Vn(e.substring(1),t,r).neg();for(var n=qn(jn(r,8)),i=Qn,o=0;o<e.length;o+=8){var a=Math.min(8,e.length-o),c=parseInt(e.substring(o,o+a),r);if(a<8){var d=qn(jn(r,a));i=i.mul(d).add(qn(c))}else i=(i=i.mul(n)).add(qn(c))}return i.unsigned=t,i}function Kn(e,t){return"number"==typeof e?qn(e,t):"string"==typeof e?Vn(e,t):$n(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}Dn.fromString=Vn,Dn.fromValue=Kn;var zn=4294967296,Hn=zn*zn,Wn=Hn/2,Jn=Gn(1<<24),Qn=Gn(0);Dn.ZERO=Qn;var Zn=Gn(0,!0);Dn.UZERO=Zn;var Yn=Gn(1);Dn.ONE=Yn;var Xn=Gn(1,!0);Dn.UONE=Xn;var ei=Gn(-1);Dn.NEG_ONE=ei;var ti=$n(-1,2147483647,!1);Dn.MAX_VALUE=ti;var ri=$n(-1,-1,!0);Dn.MAX_UNSIGNED_VALUE=ri;var si=$n(0,-2147483648,!1);Dn.MIN_VALUE=si;var ni=Dn.prototype;ni.toInt=function(){return this.unsigned?this.low>>>0:this.low},ni.toNumber=function(){return this.unsigned?(this.high>>>0)*zn+(this.low>>>0):this.high*zn+(this.low>>>0)},ni.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(si)){var t=qn(e),r=this.div(t),s=r.mul(t).sub(this);return r.toString(e)+s.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var n=qn(jn(e,6),this.unsigned),i=this,o="";;){var a=i.div(n),c=(i.sub(a.mul(n)).toInt()>>>0).toString(e);if((i=a).isZero())return c+o;for(;c.length<6;)c="0"+c;o=""+c+o}},ni.getHighBits=function(){return this.high},ni.getHighBitsUnsigned=function(){return this.high>>>0},ni.getLowBits=function(){return this.low},ni.getLowBitsUnsigned=function(){return this.low>>>0},ni.getNumBitsAbs=function(){if(this.isNegative())return this.eq(si)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},ni.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&(-1===e&&!(0===this.low&&-2097152===this.high))},ni.isZero=function(){return 0===this.high&&0===this.low},ni.eqz=ni.isZero,ni.isNegative=function(){return!this.unsigned&&this.high<0},ni.isPositive=function(){return this.unsigned||this.high>=0},ni.isOdd=function(){return!(1&~this.low)},ni.isEven=function(){return!(1&this.low)},ni.equals=function(e){return Pn(e)||(e=Kn(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},ni.eq=ni.equals,ni.notEquals=function(e){return!this.eq(e)},ni.neq=ni.notEquals,ni.ne=ni.notEquals,ni.lessThan=function(e){return this.comp(e)<0},ni.lt=ni.lessThan,ni.lessThanOrEqual=function(e){return this.comp(e)<=0},ni.lte=ni.lessThanOrEqual,ni.le=ni.lessThanOrEqual,ni.greaterThan=function(e){return this.comp(e)>0},ni.gt=ni.greaterThan,ni.greaterThanOrEqual=function(e){return this.comp(e)>=0},ni.gte=ni.greaterThanOrEqual,ni.ge=ni.greaterThanOrEqual,ni.compare=function(e){if(Pn(e)||(e=Kn(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},ni.comp=ni.compare,ni.negate=function(){return!this.unsigned&&this.eq(si)?si:this.not().add(Yn)},ni.neg=ni.negate,ni.add=function(e){Pn(e)||(e=Kn(e));var t=this.high>>>16,r=65535&this.high,s=this.low>>>16,n=65535&this.low,i=e.high>>>16,o=65535&e.high,a=e.low>>>16,c=0,d=0,u=0,l=0;return u+=(l+=n+(65535&e.low))>>>16,d+=(u+=s+a)>>>16,c+=(d+=r+o)>>>16,c+=t+i,$n((u&=65535)<<16|(l&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},ni.subtract=function(e){return Pn(e)||(e=Kn(e)),this.add(e.neg())},ni.sub=ni.subtract,ni.multiply=function(e){if(this.isZero())return this;if(Pn(e)||(e=Kn(e)),kn)return $n(kn.mul(this.low,this.high,e.low,e.high),kn.get_high(),this.unsigned);if(e.isZero())return this.unsigned?Zn:Qn;if(this.eq(si))return e.isOdd()?si:Qn;if(e.eq(si))return this.isOdd()?si:Qn;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Jn)&&e.lt(Jn))return qn(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,r=65535&this.high,s=this.low>>>16,n=65535&this.low,i=e.high>>>16,o=65535&e.high,a=e.low>>>16,c=65535&e.low,d=0,u=0,l=0,h=0;return l+=(h+=n*c)>>>16,u+=(l+=s*c)>>>16,l&=65535,u+=(l+=n*a)>>>16,d+=(u+=r*c)>>>16,u&=65535,d+=(u+=s*a)>>>16,u&=65535,d+=(u+=n*o)>>>16,d+=t*c+r*a+s*o+n*i,$n((l&=65535)<<16|(h&=65535),(d&=65535)<<16|(u&=65535),this.unsigned)},ni.mul=ni.multiply,ni.divide=function(e){if(Pn(e)||(e=Kn(e)),e.isZero())throw Error("division by zero");var t,r,s;if(kn)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?$n((this.unsigned?kn.div_u:kn.div_s)(this.low,this.high,e.low,e.high),kn.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Zn:Qn;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Zn;if(e.gt(this.shru(1)))return Xn;s=Zn}else{if(this.eq(si))return e.eq(Yn)||e.eq(ei)?si:e.eq(si)?Yn:(t=this.shr(1).div(e).shl(1)).eq(Qn)?e.isNegative()?Yn:ei:(r=this.sub(e.mul(t)),s=t.add(r.div(e)));if(e.eq(si))return this.unsigned?Zn:Qn;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Qn}for(r=this;r.gte(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var n=Math.ceil(Math.log(t)/Math.LN2),i=n<=48?1:jn(2,n-48),o=qn(t),a=o.mul(e);a.isNegative()||a.gt(r);)a=(o=qn(t-=i,this.unsigned)).mul(e);o.isZero()&&(o=Yn),s=s.add(o),r=r.sub(a)}return s},ni.div=ni.divide,ni.modulo=function(e){return Pn(e)||(e=Kn(e)),kn?$n((this.unsigned?kn.rem_u:kn.rem_s)(this.low,this.high,e.low,e.high),kn.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},ni.mod=ni.modulo,ni.rem=ni.modulo,ni.not=function(){return $n(~this.low,~this.high,this.unsigned)},ni.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},ni.clz=ni.countLeadingZeros,ni.countTrailingZeros=function(){return this.low?xn(this.low):xn(this.high)+32},ni.ctz=ni.countTrailingZeros,ni.and=function(e){return Pn(e)||(e=Kn(e)),$n(this.low&e.low,this.high&e.high,this.unsigned)},ni.or=function(e){return Pn(e)||(e=Kn(e)),$n(this.low|e.low,this.high|e.high,this.unsigned)},ni.xor=function(e){return Pn(e)||(e=Kn(e)),$n(this.low^e.low,this.high^e.high,this.unsigned)},ni.shiftLeft=function(e){return Pn(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?$n(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):$n(0,this.low<<e-32,this.unsigned)},ni.shl=ni.shiftLeft,ni.shiftRight=function(e){return Pn(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?$n(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):$n(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},ni.shr=ni.shiftRight,ni.shiftRightUnsigned=function(e){return Pn(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?$n(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):$n(32===e?this.high:this.high>>>e-32,0,this.unsigned)},ni.shru=ni.shiftRightUnsigned,ni.shr_u=ni.shiftRightUnsigned,ni.rotateLeft=function(e){var t;return Pn(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?$n(this.high,this.low,this.unsigned):e<32?(t=32-e,$n(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),$n(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},ni.rotl=ni.rotateLeft,ni.rotateRight=function(e){var t;return Pn(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?$n(this.high,this.low,this.unsigned):e<32?(t=32-e,$n(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),$n(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},ni.rotr=ni.rotateRight,ni.toSigned=function(){return this.unsigned?$n(this.low,this.high,!1):this},ni.toUnsigned=function(){return this.unsigned?this:$n(this.low,this.high,!0)},ni.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},ni.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},ni.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},Dn.fromBytes=function(e,t,r){return r?Dn.fromBytesLE(e,t):Dn.fromBytesBE(e,t)},Dn.fromBytesLE=function(e,t){return new Dn(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},Dn.fromBytesBE=function(e,t){return new Dn(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},"function"==typeof BigInt&&(Dn.fromBigInt=function(e,t){return $n(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},Dn.fromValue=function(e,t){return"bigint"==typeof e?Dn.fromBigInt(e,t):Kn(e,t)},ni.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e});var ii="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function oi(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var r=function e(){var r=!1;try{r=this instanceof e}catch{}return r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}),r}var ai,ci,di={exports:{}},ui={},li={};function hi(){if(ci)return ai;return ci=1,ai=function(e,t){var r=new Array(arguments.length-1),s=0,n=2,i=!0;for(;n<arguments.length;)r[s++]=arguments[n++];return new Promise(function(n,o){r[s]=function(e){if(i)if(i=!1,e)o(e);else{for(var t=new Array(arguments.length-1),r=0;r<t.length;)t[r++]=arguments[r];n.apply(null,t)}};try{e.apply(t||null,r)}catch(a){i&&(i=!1,o(a))}})},ai}var pi,mi,fi,gi,yi,vi={};var Ii,bi,_i,Ti,Ci,Si={};var Ei,wi,Ri,Ai,Ni,Oi,Mi,Ui,Li,ki,Di={exports:{}};Di.exports;function Pi(){return Ei||(Ei=1,e=Di,t=Di.exports,"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=null;try{t=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function r(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function s(e){return!0===(e&&e.__isLong__)}function n(e){var t=Math.clz32(e&-e);return e?31-t:t}r.prototype.__isLong__,Object.defineProperty(r.prototype,"__isLong__",{value:!0}),r.isLong=s;var i={},o={};function a(e,t){var r,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=o[e])?s:(r=d(e,0,!0),n&&(o[e]=r),r):(n=-128<=(e|=0)&&e<128)&&(s=i[e])?s:(r=d(e,e<0?-1:0,!1),n&&(i[e]=r),r)}function c(e,t){if(isNaN(e))return t?I:v;if(t){if(e<0)return I;if(e>=f)return S}else{if(e<=-g)return E;if(e+1>=g)return C}return e<0?c(-e,t).neg():d(e%m|0,e/m|0,t)}function d(e,t,s){return new r(e,t,s)}r.fromInt=a,r.fromNumber=c,r.fromBits=d;var u=Math.pow;function l(e,t,r){if(0===e.length)throw Error("empty string");if("number"==typeof t?(r=t,t=!1):t=!!t,"NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return t?I:v;if((r=r||10)<2||36<r)throw RangeError("radix");var s;if((s=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return l(e.substring(1),t,r).neg();for(var n=c(u(r,8)),i=v,o=0;o<e.length;o+=8){var a=Math.min(8,e.length-o),d=parseInt(e.substring(o,o+a),r);if(a<8){var h=c(u(r,a));i=i.mul(h).add(c(d))}else i=(i=i.mul(n)).add(c(d))}return i.unsigned=t,i}function h(e,t){return"number"==typeof e?c(e,t):"string"==typeof e?l(e,t):d(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}r.fromString=l,r.fromValue=h;var p=65536,m=p*p,f=m*m,g=f/2,y=a(1<<24),v=a(0);r.ZERO=v;var I=a(0,!0);r.UZERO=I;var b=a(1);r.ONE=b;var _=a(1,!0);r.UONE=_;var T=a(-1);r.NEG_ONE=T;var C=d(-1,2147483647,!1);r.MAX_VALUE=C;var S=d(-1,-1,!0);r.MAX_UNSIGNED_VALUE=S;var E=d(0,-2147483648,!1);r.MIN_VALUE=E;var w=r.prototype;w.toInt=function(){return this.unsigned?this.low>>>0:this.low},w.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},w.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(E)){var t=c(e),r=this.div(t),s=r.mul(t).sub(this);return r.toString(e)+s.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var n=c(u(e,6),this.unsigned),i=this,o="";;){var a=i.div(n),d=(i.sub(a.mul(n)).toInt()>>>0).toString(e);if((i=a).isZero())return d+o;for(;d.length<6;)d="0"+d;o=""+d+o}},w.getHighBits=function(){return this.high},w.getHighBitsUnsigned=function(){return this.high>>>0},w.getLowBits=function(){return this.low},w.getLowBitsUnsigned=function(){return this.low>>>0},w.getNumBitsAbs=function(){if(this.isNegative())return this.eq(E)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},w.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&-1===e&&!(0===this.low&&-2097152===this.high)},w.isZero=function(){return 0===this.high&&0===this.low},w.eqz=w.isZero,w.isNegative=function(){return!this.unsigned&&this.high<0},w.isPositive=function(){return this.unsigned||this.high>=0},w.isOdd=function(){return!(1&~this.low)},w.isEven=function(){return!(1&this.low)},w.equals=function(e){return s(e)||(e=h(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},w.eq=w.equals,w.notEquals=function(e){return!this.eq(e)},w.neq=w.notEquals,w.ne=w.notEquals,w.lessThan=function(e){return this.comp(e)<0},w.lt=w.lessThan,w.lessThanOrEqual=function(e){return this.comp(e)<=0},w.lte=w.lessThanOrEqual,w.le=w.lessThanOrEqual,w.greaterThan=function(e){return this.comp(e)>0},w.gt=w.greaterThan,w.greaterThanOrEqual=function(e){return this.comp(e)>=0},w.gte=w.greaterThanOrEqual,w.ge=w.greaterThanOrEqual,w.compare=function(e){if(s(e)||(e=h(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},w.comp=w.compare,w.negate=function(){return!this.unsigned&&this.eq(E)?E:this.not().add(b)},w.neg=w.negate,w.add=function(e){s(e)||(e=h(e));var t=this.high>>>16,r=65535&this.high,n=this.low>>>16,i=65535&this.low,o=e.high>>>16,a=65535&e.high,c=e.low>>>16,u=0,l=0,p=0,m=0;return p+=(m+=i+(65535&e.low))>>>16,l+=(p+=n+c)>>>16,u+=(l+=r+a)>>>16,u+=t+o,d((p&=65535)<<16|(m&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},w.subtract=function(e){return s(e)||(e=h(e)),this.add(e.neg())},w.sub=w.subtract,w.multiply=function(e){if(this.isZero())return this;if(s(e)||(e=h(e)),t)return d(t.mul(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned);if(e.isZero())return this.unsigned?I:v;if(this.eq(E))return e.isOdd()?E:v;if(e.eq(E))return this.isOdd()?E:v;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(y)&&e.lt(y))return c(this.toNumber()*e.toNumber(),this.unsigned);var r=this.high>>>16,n=65535&this.high,i=this.low>>>16,o=65535&this.low,a=e.high>>>16,u=65535&e.high,l=e.low>>>16,p=65535&e.low,m=0,f=0,g=0,b=0;return g+=(b+=o*p)>>>16,f+=(g+=i*p)>>>16,g&=65535,f+=(g+=o*l)>>>16,m+=(f+=n*p)>>>16,f&=65535,m+=(f+=i*l)>>>16,f&=65535,m+=(f+=o*u)>>>16,m+=r*p+n*l+i*u+o*a,d((g&=65535)<<16|(b&=65535),(m&=65535)<<16|(f&=65535),this.unsigned)},w.mul=w.multiply,w.divide=function(e){if(s(e)||(e=h(e)),e.isZero())throw Error("division by zero");var r,n,i;if(t)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?d((this.unsigned?t.div_u:t.div_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?I:v;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return I;if(e.gt(this.shru(1)))return _;i=I}else{if(this.eq(E))return e.eq(b)||e.eq(T)?E:e.eq(E)?b:(r=this.shr(1).div(e).shl(1)).eq(v)?e.isNegative()?b:T:(n=this.sub(e.mul(r)),i=r.add(n.div(e)));if(e.eq(E))return this.unsigned?I:v;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();i=v}for(n=this;n.gte(e);){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var o=Math.ceil(Math.log(r)/Math.LN2),a=o<=48?1:u(2,o-48),l=c(r),p=l.mul(e);p.isNegative()||p.gt(n);)p=(l=c(r-=a,this.unsigned)).mul(e);l.isZero()&&(l=b),i=i.add(l),n=n.sub(p)}return i},w.div=w.divide,w.modulo=function(e){return s(e)||(e=h(e)),t?d((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},w.mod=w.modulo,w.rem=w.modulo,w.not=function(){return d(~this.low,~this.high,this.unsigned)},w.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},w.clz=w.countLeadingZeros,w.countTrailingZeros=function(){return this.low?n(this.low):n(this.high)+32},w.ctz=w.countTrailingZeros,w.and=function(e){return s(e)||(e=h(e)),d(this.low&e.low,this.high&e.high,this.unsigned)},w.or=function(e){return s(e)||(e=h(e)),d(this.low|e.low,this.high|e.high,this.unsigned)},w.xor=function(e){return s(e)||(e=h(e)),d(this.low^e.low,this.high^e.high,this.unsigned)},w.shiftLeft=function(e){return s(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):d(0,this.low<<e-32,this.unsigned)},w.shl=w.shiftLeft,w.shiftRight=function(e){return s(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):d(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},w.shr=w.shiftRight,w.shiftRightUnsigned=function(e){return s(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):d(32===e?this.high:this.high>>>e-32,0,this.unsigned)},w.shru=w.shiftRightUnsigned,w.shr_u=w.shiftRightUnsigned,w.rotateLeft=function(e){var t;return s(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?d(this.high,this.low,this.unsigned):e<32?(t=32-e,d(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),d(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},w.rotl=w.rotateLeft,w.rotateRight=function(e){var t;return s(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?d(this.high,this.low,this.unsigned):e<32?(t=32-e,d(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),d(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},w.rotr=w.rotateRight,w.toSigned=function(){return this.unsigned?d(this.low,this.high,!1):this},w.toUnsigned=function(){return this.unsigned?this:d(this.low,this.high,!0)},w.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},w.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},w.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},r.fromBytes=function(e,t,s){return s?r.fromBytesLE(e,t):r.fromBytesBE(e,t)},r.fromBytesLE=function(e,t){return new r(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},r.fromBytesBE=function(e,t){return new r(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},"function"==typeof BigInt&&(r.fromBigInt=function(e,t){return d(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},r.fromValue=function(e,t){return"bigint"==typeof e?r.fromBigInt(e,t):h(e,t)},w.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e}),e.default=r}(t),e.exports=(r=t).default||r),Di.exports;var e,t,r}function xi(){return wi||(wi=1,function(e){var t,r,s=e;function n(e){return"__proto__"===e||"prototype"===e||"constructor"===e}function i(e){var t="boolean"==typeof arguments[arguments.length-1],r=t?arguments.length-1:arguments.length;t=t&&arguments[arguments.length-1];for(var s=1;s<r;++s){var i=arguments[s];if(i)for(var o=Object.keys(i),a=0;a<o.length;++a)n(o[a])||void 0!==e[o[a]]&&t||(e[o[a]]=i[o[a]])}return e}function o(e){function t(e,r){if(!(this instanceof t))return new t(e,r);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),r&&i(this,r)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}s.asPromise=hi(),s.base64=(pi||(pi=1,function(e){var t=e;t.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var r=new Array(64),s=new Array(123),n=0;n<64;)s[r[n]=n<26?n+65:n<52?n+71:n<62?n-4:n-59|43]=n++;t.encode=function(e,t,s){for(var n,i=null,o=[],a=0,c=0;t<s;){var d=e[t++];switch(c){case 0:o[a++]=r[d>>2],n=(3&d)<<4,c=1;break;case 1:o[a++]=r[n|d>>4],n=(15&d)<<2,c=2;break;case 2:o[a++]=r[n|d>>6],o[a++]=r[63&d],c=0}a>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=r[n],o[a++]=61,1===c&&(o[a++]=61)),i?(a&&i.push(String.fromCharCode.apply(String,o.slice(0,a))),i.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var i="invalid encoding";t.decode=function(e,t,r){for(var n,o=r,a=0,c=0;c<e.length;){var d=e.charCodeAt(c++);if(61===d&&a>1)break;if(void 0===(d=s[d]))throw Error(i);switch(a){case 0:n=d,a=1;break;case 1:t[r++]=n<<2|(48&d)>>4,n=d,a=2;break;case 2:t[r++]=(15&n)<<4|(60&d)>>2,n=d,a=3;break;case 3:t[r++]=(3&n)<<6|d,a=0}}if(1===a)throw Error(i);return r-o},t.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}(vi)),vi),s.EventEmitter=function(){if(fi)return mi;function e(){this._listeners=Object.create(null)}return fi=1,mi=e,e.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},e.prototype.off=function(e,t){if(void 0===e)this._listeners=Object.create(null);else if(void 0===t)this._listeners[e]=[];else{var r=this._listeners[e];if(!r)return this;for(var s=0;s<r.length;)r[s].fn===t?r.splice(s,1):++s}return this},e.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var r=[],s=1;s<arguments.length;)r.push(arguments[s++]);for(s=0;s<t.length;)t[s].fn.apply(t[s++].ctx,r)}return this},mi}(),s.float=function(){if(yi)return gi;function e(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),s=128===r[3];function n(e,s,n){t[0]=e,s[n]=r[0],s[n+1]=r[1],s[n+2]=r[2],s[n+3]=r[3]}function i(e,s,n){t[0]=e,s[n]=r[3],s[n+1]=r[2],s[n+2]=r[1],s[n+3]=r[0]}function o(e,s){return r[0]=e[s],r[1]=e[s+1],r[2]=e[s+2],r[3]=e[s+3],t[0]}function a(e,s){return r[3]=e[s],r[2]=e[s+1],r[1]=e[s+2],r[0]=e[s+3],t[0]}e.writeFloatLE=s?n:i,e.writeFloatBE=s?i:n,e.readFloatLE=s?o:a,e.readFloatBE=s?a:o}():function(){function i(e,t,r,s){var n=t<0?1:0;if(n&&(t=-t),0===t)e(1/t>0?0:2147483648,r,s);else if(isNaN(t))e(2143289344,r,s);else if(t>34028234663852886e22)e((n<<31|2139095040)>>>0,r,s);else if(t<11754943508222875e-54)e((n<<31|Math.round(t/1401298464324817e-60))>>>0,r,s);else{var i=Math.floor(Math.log(t)/Math.LN2);e((n<<31|i+127<<23|8388607&Math.round(t*Math.pow(2,-i)*8388608))>>>0,r,s)}}function o(e,t,r){var s=e(t,r),n=2*(s>>31)+1,i=s>>>23&255,o=8388607&s;return 255===i?o?NaN:n*(1/0):0===i?1401298464324817e-60*n*o:n*Math.pow(2,i-150)*(o+8388608)}e.writeFloatLE=i.bind(null,t),e.writeFloatBE=i.bind(null,r),e.readFloatLE=o.bind(null,s),e.readFloatBE=o.bind(null,n)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),s=128===r[7];function n(e,s,n){t[0]=e,s[n]=r[0],s[n+1]=r[1],s[n+2]=r[2],s[n+3]=r[3],s[n+4]=r[4],s[n+5]=r[5],s[n+6]=r[6],s[n+7]=r[7]}function i(e,s,n){t[0]=e,s[n]=r[7],s[n+1]=r[6],s[n+2]=r[5],s[n+3]=r[4],s[n+4]=r[3],s[n+5]=r[2],s[n+6]=r[1],s[n+7]=r[0]}function o(e,s){return r[0]=e[s],r[1]=e[s+1],r[2]=e[s+2],r[3]=e[s+3],r[4]=e[s+4],r[5]=e[s+5],r[6]=e[s+6],r[7]=e[s+7],t[0]}function a(e,s){return r[7]=e[s],r[6]=e[s+1],r[5]=e[s+2],r[4]=e[s+3],r[3]=e[s+4],r[2]=e[s+5],r[1]=e[s+6],r[0]=e[s+7],t[0]}e.writeDoubleLE=s?n:i,e.writeDoubleBE=s?i:n,e.readDoubleLE=s?o:a,e.readDoubleBE=s?a:o}():function(){function i(e,t,r,s,n,i){var o=s<0?1:0;if(o&&(s=-s),0===s)e(0,n,i+t),e(1/s>0?0:2147483648,n,i+r);else if(isNaN(s))e(0,n,i+t),e(2146959360,n,i+r);else if(s>17976931348623157e292)e(0,n,i+t),e((o<<31|2146435072)>>>0,n,i+r);else{var a;if(s<22250738585072014e-324)e((a=s/5e-324)>>>0,n,i+t),e((o<<31|a/4294967296)>>>0,n,i+r);else{var c=Math.floor(Math.log(s)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=s*Math.pow(2,-c))>>>0,n,i+t),e((o<<31|c+1023<<20|1048576*a&1048575)>>>0,n,i+r)}}}function o(e,t,r,s,n){var i=e(s,n+t),o=e(s,n+r),a=2*(o>>31)+1,c=o>>>20&2047,d=4294967296*(1048575&o)+i;return 2047===c?d?NaN:a*(1/0):0===c?5e-324*a*d:a*Math.pow(2,c-1075)*(d+4503599627370496)}e.writeDoubleLE=i.bind(null,t,0,4),e.writeDoubleBE=i.bind(null,r,4,0),e.readDoubleLE=o.bind(null,s,0,4),e.readDoubleBE=o.bind(null,n,4,0)}(),e}function t(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function r(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function n(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}return yi=1,gi=e(e)}(),s.utf8=(Ii||(Ii=1,r=65533,(t=Si).length=function(e){for(var t=0,r=0,s=0;s<e.length;++s)(r=e.charCodeAt(s))<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(s+1))?(++s,t+=4):t+=3;return t},t.read=function(e,t,s){if(s-t<1)return"";for(var n,i,o,a,c=null,d=[],u=0;t<s;)(n=e[t++])<=127?d[u++]=n:n>=192&&n<224?(o=(31&n)<<6|63&e[t++],d[u++]=o>=128?o:r):n>=224&&n<240?(a=(15&n)<<12|(63&e[t++])<<6|63&e[t++],d[u++]=a>=2048?a:r):n>=240&&((i=(7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])<65536||i>1114111?d[u++]=r:(i-=65536,d[u++]=55296+(i>>10),d[u++]=56320+(1023&i))),u>8191&&((c||(c=[])).push(String.fromCharCode.apply(String,d.slice(0,u))),u=0);return c?(u&&c.push(String.fromCharCode.apply(String,d.slice(0,u))),c.join("")):String.fromCharCode.apply(String,d.slice(0,u))},t.write=function(e,t,r){for(var s,n,i=r,o=0;o<e.length;++o)(s=e.charCodeAt(o))<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(n=e.charCodeAt(o+1)))?(s=65536+((1023&s)<<10)+(1023&n),++o,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-i}),Si),s.pool=_i?bi:(_i=1,bi=function(e,t,r){var s=r||8192,n=s>>>1,i=null,o=s;return function(r){if(r<1||r>n)return e(r);o+r>s&&(i=e(s),o=0);var a=t.call(i,o,o+=r);return 7&o&&(o=1+(7|o)),a}}),s.LongBits=function(){if(Ci)return Ti;Ci=1,Ti=t;var e=xi();function t(e,t){this.lo=e>>>0,this.hi=t>>>0}var r=t.zero=new t(0,0);r.toNumber=function(){return 0},r.zzEncode=r.zzDecode=function(){return this},r.length=function(){return 1};var s=t.zeroHash="\0\0\0\0\0\0\0\0";t.fromNumber=function(e){if(0===e)return r;var s=e<0;s&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return s&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new t(n,i)},t.from=function(s){if("number"==typeof s)return t.fromNumber(s);if(e.isString(s)){if(!e.Long)return t.fromNumber(parseInt(s,10));s=e.Long.fromString(s)}return s.low||s.high?new t(s.low>>>0,s.high>>>0):r},t.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},t.prototype.toLong=function(t){return e.Long?new e.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var n=String.prototype.charCodeAt;return t.fromHash=function(e){return e===s?r:new t((n.call(e,0)|n.call(e,1)<<8|n.call(e,2)<<16|n.call(e,3)<<24)>>>0,(n.call(e,4)|n.call(e,5)<<8|n.call(e,6)<<16|n.call(e,7)<<24)>>>0)},t.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},t.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},t.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},t.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10},Ti}(),s.isUnsafeProperty=n,s.isNode=Boolean(void 0!==ii&&ii&&ii.process&&ii.process.versions&&ii.process.versions.node),s.global=s.isNode&&ii||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||li,s.emptyArray=Object.freeze?Object.freeze([]):[],s.emptyObject=Object.freeze?Object.freeze({}):{},s.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},s.isString=function(e){return"string"==typeof e||e instanceof String},s.isObject=function(e){return e&&"object"==typeof e},s.isset=s.isSet=function(e,t){var r=e[t];return!(null==r||!Object.hasOwnProperty.call(e,t))&&("object"!=typeof r||(Array.isArray(r)?r.length:Object.keys(r).length)>0)},s.Buffer=function(){try{var e=s.global.Buffer;return e.prototype.utf8Write?e:null}catch(t){return null}}(),s._Buffer_from=null,s._Buffer_allocUnsafe=null,s.newBuffer=function(e){return"number"==typeof e?s.Buffer?s._Buffer_allocUnsafe(e):new s.Array(e):s.Buffer?s._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},s.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,s.Long=s.global.dcodeIO&&s.global.dcodeIO.Long||s.global.Long||function(){try{var e=Pi();return e&&e.isLong?e:null}catch(t){return null}}(),s.key2Re=/^true|false|0|1$/,s.key32Re=/^-?(?:0|[1-9][0-9]*)$/,s.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,s.longToHash=function(e){return e?s.LongBits.from(e).toHash():s.LongBits.zeroHash},s.longFromHash=function(e,t){var r=s.LongBits.fromHash(e);return s.Long?s.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},s.merge=i,s.nestingLimit=32,s.recursionLimit=100,s.makeProp=function(e,t){Object.defineProperty(e,t,{enumerable:!0,configurable:!0,writable:!0})},s.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},s.newError=o,s.ProtocolError=o("ProtocolError"),s.oneOfGetter=function(e){for(var t={},r=0;r<e.length;++r)t[e[r]]=1;return function(){for(var e=Object.keys(this),r=e.length-1;r>-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},s.oneOfSetter=function(e){return function(t){for(var r=0;r<e.length;++r)e[r]!==t&&delete this[e[r]]}},s.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},s._configure=function(){var e=s.Buffer;e?(s._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,r){return new e(t,r)},s._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):s._Buffer_from=s._Buffer_allocUnsafe=null}}(li)),li}function Fi(){if(Ai)return Ri;Ai=1,Ri=c;var e,t=xi(),r=t.LongBits,s=t.base64,n=t.utf8;function i(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function o(){}function a(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function c(){this.len=0,this.head=new i(o,0,0),this.tail=this.head,this.states=null}var d=function(){return t.Buffer?function(){return(c.create=function(){return new e})()}:function(){return new c}};function u(e,t,r){t[r]=255&e}function l(e,t){this.len=e,this.next=void 0,this.val=t}function h(e,t,r){for(var s=e.lo,n=e.hi;n;)t[r++]=127&s|128,s=(s>>>7|n<<25)>>>0,n>>>=7;for(;s>127;)t[r++]=127&s|128,s>>>=7;t[r++]=s}function p(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}c.create=d(),c.alloc=function(e){return new t.Array(e)},t.Array!==Array&&(c.alloc=t.pool(c.alloc,t.Array.prototype.subarray)),c.prototype._push=function(e,t,r){return this.tail=this.tail.next=new i(e,t,r),this.len+=t,this},l.prototype=Object.create(i.prototype),l.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},c.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new l((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},c.prototype.int32=function(e){return(e|=0)<0?this._push(h,10,r.fromNumber(e)):this.uint32(e)},c.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},c.prototype.uint64=function(e){var t=r.from(e);return this._push(h,t.length(),t)},c.prototype.int64=c.prototype.uint64,c.prototype.sint64=function(e){var t=r.from(e).zzEncode();return this._push(h,t.length(),t)},c.prototype.bool=function(e){return this._push(u,1,e?1:0)},c.prototype.fixed32=function(e){return this._push(p,4,e>>>0)},c.prototype.sfixed32=c.prototype.fixed32,c.prototype.fixed64=function(e){var t=r.from(e);return this._push(p,4,t.lo)._push(p,4,t.hi)},c.prototype.sfixed64=c.prototype.fixed64,c.prototype.float=function(e){return this._push(t.float.writeFloatLE,4,e)},c.prototype.double=function(e){return this._push(t.float.writeDoubleLE,8,e)};var m=t.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var s=0;s<e.length;++s)t[r+s]=e[s]};return c.prototype.bytes=function(e){var r=e.length>>>0;if(!r)return this._push(u,1,0);if(t.isString(e)){var n=c.alloc(r=s.length(e));s.decode(e,n,0),e=n}return this.uint32(r)._push(m,r,e)},c.prototype.string=function(e){var t=n.length(e);return t?this.uint32(t)._push(n.write,t,e):this._push(u,1,0)},c.prototype.fork=function(){return this.states=new a(this),this.head=this.tail=new i(o,0,0),this.len=0,this},c.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new i(o,0,0),this.len=0),this},c.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},c.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},c._configure=function(t){e=t,c.create=d(),e._configure()},Ri}function Bi(){if(Ui)return Mi;Ui=1,Mi=i;var e,t=xi(),r=t.LongBits,s=t.utf8;function n(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function i(e){this.buf=e,this.pos=0,this.len=e.length}var o="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new i(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new i(e);throw Error("illegal buffer")},a=function(){return t.Buffer?function(r){return(i.create=function(r){return t.Buffer.isBuffer(r)?new e(r):o(r)})(r)}:o};function c(){var e=new r(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw n(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw n(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function d(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function u(){if(this.pos+8>this.len)throw n(this,8);return new r(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}return i.create=a(),i.prototype._slice=t.Array.prototype.subarray||t.Array.prototype.slice,i.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,n(this,10);return e}}(),i.prototype.int32=function(){return 0|this.uint32()},i.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},i.prototype.bool=function(){return 0!==this.uint32()},i.prototype.fixed32=function(){if(this.pos+4>this.len)throw n(this,4);return d(this.buf,this.pos+=4)},i.prototype.sfixed32=function(){if(this.pos+4>this.len)throw n(this,4);return 0|d(this.buf,this.pos+=4)},i.prototype.float=function(){if(this.pos+4>this.len)throw n(this,4);var e=t.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},i.prototype.double=function(){if(this.pos+8>this.len)throw n(this,4);var e=t.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},i.prototype.bytes=function(){var e=this.uint32(),r=this.pos,s=this.pos+e;if(s>this.len)throw n(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(r,s);if(r===s){var i=t.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,s)},i.prototype.string=function(){var e=this.bytes();return s.read(e,0,e.length)},i.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw n(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw n(this)}while(128&this.buf[this.pos++]);return this},i.recursionLimit=t.recursionLimit,i.prototype.skipType=function(e,t){if(void 0===t&&(t=0),t>i.recursionLimit)throw Error("maximum nesting depth exceeded");switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e,t+1);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},i._configure=function(r){e=r,i.create=a(),e._configure();var s=t.Long?"toLong":"toNumber";t.merge(i.prototype,{int64:function(){return c.call(this)[s](!1)},uint64:function(){return c.call(this)[s](!0)},sint64:function(){return c.call(this).zzDecode()[s](!1)},fixed64:function(){return u.call(this)[s](!0)},sfixed64:function(){return u.call(this)[s](!1)}})},Mi}var Gi,qi,$i,ji,Vi,Ki,zi={};function Hi(){return $i||($i=1,zi.Service=function(){if(qi)return Gi;qi=1,Gi=t;var e=xi();function t(t,r,s){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");e.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=Boolean(r),this.responseDelimited=Boolean(s)}return(t.prototype=Object.create(e.EventEmitter.prototype)).constructor=t,t.prototype.rpcCall=function t(r,s,n,i,o){if(!i)throw TypeError("request must be specified");var a=this;if(!o)return e.asPromise(t,a,r,s,n,i);if(a.rpcImpl)try{return a.rpcImpl(r,s[a.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(e,t){if(e)return a.emit("error",e,r),o(e);if(null!==t){if(!(t instanceof n))try{t=n[a.responseDelimited?"decodeDelimited":"decode"](t)}catch(s){return a.emit("error",s,r),o(s)}return a.emit("data",t,r),o(null,t)}a.end(!0)})}catch(c){return a.emit("error",c,r),void setTimeout(function(){o(c)},0)}else setTimeout(function(){o(Error("already ended"))},0)},t.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this},Gi}()),zi}function Wi(){return Vi?ji:(Vi=1,ji=Object.create(null))}function Ji(){return Ki||(Ki=1,function(e){var t=e;function r(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}t.build="minimal",t.Writer=Fi(),t.BufferWriter=function(){if(Oi)return Ni;Oi=1,Ni=r;var e=Fi();(r.prototype=Object.create(e.prototype)).constructor=r;var t=xi();function r(){e.call(this)}function s(e,r,s){e.length<40?t.utf8.write(e,r,s):r.utf8Write?r.utf8Write(e,s):r.write(e,s)}return r._configure=function(){r.alloc=t._Buffer_allocUnsafe,r.writeBytesBuffer=t.Buffer&&t.Buffer.prototype instanceof Uint8Array&&"set"===t.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var s=0;s<e.length;)t[r++]=e[s++]}},r.prototype.bytes=function(e){t.isString(e)&&(e=t._Buffer_from(e,"base64"));var s=e.length>>>0;return this.uint32(s),s&&this._push(r.writeBytesBuffer,s,e),this},r.prototype.string=function(e){var r=t.Buffer.byteLength(e);return this.uint32(r),r&&this._push(s,r,e),this},r._configure(),Ni}(),t.Reader=Bi(),t.BufferReader=function(){if(ki)return Li;ki=1,Li=r;var e=Bi();(r.prototype=Object.create(e.prototype)).constructor=r;var t=xi();function r(t){e.call(this,t)}return r._configure=function(){t.Buffer&&(r.prototype._slice=t.Buffer.prototype.slice)},r.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},r._configure(),Li}(),t.util=xi(),t.rpc=Hi(),t.roots=Wi(),t.configure=r,r()}(ui)),ui}var Qi,Zi,Yi={},Xi={exports:{}};function eo(){if(Zi)return Qi;Zi=1,Qi=t;var e=/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/;function t(r,s){"string"==typeof r&&(s=r,r=void 0);var n=[];function i(e){if("string"!=typeof e){var r=o();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var s=Object.keys(e),a=new Array(s.length+1),c=new Array(s.length),d=0;d<s.length;)a[d]=s[d],c[d]=e[s[d++]];return a[d]=r,Function.apply(null,a).apply(null,c)}return Function(r)()}for(var u=new Array(arguments.length-1),l=0;l<u.length;)u[l]=arguments[++l];if(l=0,e=e.replace(/%([%dfijs])/g,function(e,t){var r=u[l++];switch(t){case"d":case"f":return String(Number(r));case"i":return String(Math.floor(r));case"j":return JSON.stringify(r);case"s":return String(r)}return"%"}),l!==u.length)throw Error("parameter count mismatch");return n.push(e),i}function o(t){return"function "+function(t){if(!t)return"";if(!(t=String(t).replace(/[^\w$]/g,"")))return"";/^\d/.test(t)&&(t="_"+t);return e.test(t)?t+"_":t}(t||s)+"("+(r&&r.join(",")||"")+"){\n "+n.join("\n ")+"\n}"}return i.toString=o,i}return t.verbose=!1,Qi}const to=oi(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var ro,so,no,io;function oo(){if(io)return no;io=1,no=r;var e=hi(),t=function(){if(so)return ro;so=1;var e=null;try{(e=to)&&e.readFile&&e.readFileSync||(e=null)}catch(t){}return ro=e}();function r(s,n,i){return"function"==typeof n?(i=n,n={}):n||(n={}),i?!n.xhr&&t&&t.readFile?t.readFile(s,function(e,t){return e&&"undefined"!=typeof XMLHttpRequest?r.xhr(s,n,i):e?i(e):i(null,n.binary?t:t.toString("utf8"))}):r.xhr(s,n,i):e(r,this,s,n)}return r.xhr=function(e,t,r){var s=new XMLHttpRequest;s.onreadystatechange=function(){if(4===s.readyState){if(0!==s.status&&200!==s.status)return r(Error("status "+s.status));if(t.binary){var e=s.response;if(!e){e=[];for(var n=0;n<s.responseText.length;++n)e.push(255&s.responseText.charCodeAt(n))}return r(null,"undefined"!=typeof Uint8Array?new Uint8Array(e):e)}return r(null,s.responseText)}},t.binary&&("overrideMimeType"in s&&s.overrideMimeType("text/plain; charset=x-user-defined"),s.responseType="arraybuffer"),s.open("GET",e),s.send()},no}var ao,co={};var uo,lo,ho,po,mo,fo,go,yo,vo,Io,bo,_o,To,Co,So,Eo,wo,Ro={};function Ao(){if(mo)return po;mo=1,po=c;var e=ha();((c.prototype=Object.create(e.prototype)).constructor=c).className="Namespace";var t,r,s,n=ua(),i=ca(),o=la();function a(e,t){if(e&&e.length){for(var r={},s=0;s<e.length;++s)r[e[s].name]=e[s].toJSON(t);return r}}function c(t,r){e.call(this,t,r),this.nested=void 0,this._nestedArray=null,this._lookupCache=Object.create(null),this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0}function d(e){e._nestedArray=null,e._lookupCache=Object.create(null);for(var t=e;t=t.parent;)t._lookupCache=Object.create(null);return e}return c.fromJSON=function(e,t,r){return r=i.checkDepth(r),new c(e,t.options).addJSON(t.nested,r)},c.arrayToJSON=a,c.isReservedId=function(e,t){if(e)for(var r=0;r<e.length;++r)if("string"!=typeof e[r]&&e[r][0]<=t&&e[r][1]>t)return!0;return!1},c.isReservedName=function(e,t){if(e)for(var r=0;r<e.length;++r)if(e[r]===t)return!0;return!1},Object.defineProperty(c.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=i.toArray(this.nested))}}),c.prototype.toJSON=function(e){return i.toObject(["options",this.options,"nested",a(this.nestedArray,e)])},c.prototype.addJSON=function(e,o){o=i.checkDepth(o);if(e)for(var a,d=Object.keys(e),u=0;u<d.length;++u)a=e[d[u]],this.add((void 0!==a.fields?t.fromJSON:void 0!==a.values?s.fromJSON:void 0!==a.methods?r.fromJSON:void 0!==a.id?n.fromJSON:c.fromJSON)(d[u],a,o+1));return this},c.prototype.get=function(e){return this.nested&&Object.prototype.hasOwnProperty.call(this.nested,e)?this.nested[e]:null},c.prototype.getEnum=function(e){if(this.nested&&Object.prototype.hasOwnProperty.call(this.nested,e)&&this.nested[e]instanceof s)return this.nested[e].values;throw Error("no such enum: "+e)},c.prototype.add=function(e){if(!(e instanceof n&&void 0!==e.extend||e instanceof t||e instanceof o||e instanceof s||e instanceof r||e instanceof c))throw TypeError("object must be a valid nested object");if("__proto__"===e.name)return this;if(this.nested){var i=this.get(e.name);if(i){if(!(i instanceof c&&e instanceof c)||i instanceof t||i instanceof r)throw Error("duplicate name '"+e.name+"' in "+this);for(var a=i.nestedArray,u=0;u<a.length;++u)e.add(a[u]);this.remove(i),this.nested||(this.nested={}),e.setOptions(i.options,!0)}}else this.nested={};this.nested[e.name]=e,this instanceof t||this instanceof r||this instanceof s||this instanceof n||e._edition||(e._edition=e._defaultEdition),this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0;for(var l=this;l=l.parent;)l._needsRecursiveFeatureResolution=!0,l._needsRecursiveResolve=!0;return e.onAdd(this),d(this)},c.prototype.remove=function(t){if(!(t instanceof e))throw TypeError("object must be a ReflectionObject");if(t.parent!==this)throw Error(t+" is not a member of "+this);return delete this.nested[t.name],Object.keys(this.nested).length||(this.nested=void 0),t.onRemove(this),d(this)},c.prototype.define=function(e,t){if(i.isString(e))e=e.split(".");else if(!Array.isArray(e))throw TypeError("illegal path");if(e&&e.length&&""===e[0])throw Error("path must be relative");if(e.length>i.recursionLimit)throw Error("max depth exceeded");for(var r=this;e.length>0;){var s=e.shift();if(r.nested&&r.nested[s]){if(!((r=r.nested[s])instanceof c))throw Error("path conflicts with non-namespace objects")}else r.add(r=new c(s))}return t&&r.addJSON(t),r},c.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;this._resolveFeaturesRecursive(this._edition);var e=this.nestedArray,t=0;for(this.resolve();t<e.length;)e[t]instanceof c?e[t++].resolveAll():e[t++].resolve();return this._needsRecursiveResolve=!1,this},c.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(this._needsRecursiveFeatureResolution=!1,t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.nestedArray.forEach(e=>{e._resolveFeaturesRecursive(t)}),this):this},c.prototype.lookup=function(e,t,r){if("boolean"==typeof t?(r=t,t=void 0):t&&!Array.isArray(t)&&(t=[t]),i.isString(e)&&e.length){if("."===e)return this.root;e=e.split(".")}else if(!e.length)return this;var s=e.join(".");if(""===e[0])return this.root.lookup(e.slice(1),t);var n=this.root._fullyQualifiedObjects&&this.root._fullyQualifiedObjects["."+s];if(n&&(!t||t.indexOf(n.constructor)>-1))return n;if((n=this._lookupImpl(e,s))&&(!t||t.indexOf(n.constructor)>-1))return n;if(r)return null;for(var o=this;o.parent;){if((n=o.parent._lookupImpl(e,s))&&(!t||t.indexOf(n.constructor)>-1))return n;o=o.parent}return null},c.prototype._lookupImpl=function(e,t){if(Object.prototype.hasOwnProperty.call(this._lookupCache,t))return this._lookupCache[t];var r=this.get(e[0]),s=null;if(r)1===e.length?s=r:r instanceof c&&(e=e.slice(1),s=r._lookupImpl(e,e.join(".")));else for(var n=0;n<this.nestedArray.length;++n)if(this._nestedArray[n]instanceof c&&(r=this._nestedArray[n]._lookupImpl(e,t))){s=r;break}return this._lookupCache[t]=s,s},c.prototype.lookupType=function(e){var r=this.lookup(e,[t]);if(!r)throw Error("no such type: "+e);return r},c.prototype.lookupEnum=function(e){var t=this.lookup(e,[s]);if(!t)throw Error("no such Enum '"+e+"' in "+this);return t},c.prototype.lookupTypeOrEnum=function(e){var r=this.lookup(e,[t,s]);if(!r)throw Error("no such Type or Enum '"+e+"' in "+this);return r},c.prototype.lookupService=function(e){var t=this.lookup(e,[r]);if(!t)throw Error("no such Service '"+e+"' in "+this);return t},c._configure=function(e,n,i){t=e,r=n,s=i},po}function No(){if(go)return fo;go=1,fo=s;var e=ua();((s.prototype=Object.create(e.prototype)).constructor=s).className="MapField";var t=da(),r=ca();function s(t,s,n,i,o,a){if(e.call(this,t,s,i,void 0,void 0,o,a),!r.isString(n))throw TypeError("keyType must be a string");this.keyType=n,this.resolvedKeyType=null,this.map=!0}return s.fromJSON=function(e,t){return new s(e,t.id,t.keyType,t.type,t.options,t.comment)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},s.prototype.resolve=function(){if(this.resolved)return this;if(void 0===t.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return e.prototype.resolve.call(this)},s.d=function(e,t,n){return"function"==typeof n?n=r.decorateType(n).name:n&&"object"==typeof n&&(n=r.decorateEnum(n).name),function(i,o){r.decorateType(i.constructor).add(new s(o,e,t,n))}},fo}function Oo(){if(vo)return yo;vo=1,yo=r;var e=ha();((r.prototype=Object.create(e.prototype)).constructor=r).className="Method";var t=ca();function r(r,s,n,i,o,a,c,d,u){if(t.isObject(o)?(c=o,o=a=void 0):t.isObject(a)&&(c=a,a=void 0),void 0!==s&&!t.isString(s))throw TypeError("type must be a string");if(!t.isString(n))throw TypeError("requestType must be a string");if(!t.isString(i))throw TypeError("responseType must be a string");e.call(this,r,c),this.type=s||"rpc",this.requestType=n,this.requestStream=!!o||void 0,this.responseType=i,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=d,this.parsedOptions=u}return r.fromJSON=function(e,t){return new r(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},r.prototype.toJSON=function(e){var r=!!e&&Boolean(e.keepComments);return t.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",r?this.comment:void 0,"parsedOptions",this.parsedOptions])},r.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),e.prototype.resolve.call(this))},yo}function Mo(){if(bo)return Io;bo=1,Io=n;var e=Ao();((n.prototype=Object.create(e.prototype)).constructor=n).className="Service";var t=Oo(),r=ca(),s=Hi();function n(t,r){e.call(this,t,r),this.methods={},this._methodsArray=null}function i(e){return e._methodsArray=null,e}return n.fromJSON=function(e,s,i){i=r.checkDepth(i);var o=new n(e,s.options);if(s.methods)for(var a=Object.keys(s.methods),c=0;c<a.length;++c)o.add(t.fromJSON(a[c],s.methods[a[c]]));return s.nested&&o.addJSON(s.nested,i),s.edition&&(o._edition=s.edition),o.comment=s.comment,o._defaultEdition="proto3",o},n.prototype.toJSON=function(t){var s=e.prototype.toJSON.call(this,t),n=!!t&&Boolean(t.keepComments);return r.toObject(["edition",this._editionToJSON(),"options",s&&s.options||void 0,"methods",e.arrayToJSON(this.methodsArray,t)||{},"nested",s&&s.nested||void 0,"comment",n?this.comment:void 0])},Object.defineProperty(n.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=r.toArray(this.methods))}}),n.prototype.get=function(t){return Object.prototype.hasOwnProperty.call(this.methods,t)?this.methods[t]:e.prototype.get.call(this,t)},n.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;e.prototype.resolve.call(this);for(var t=this.methodsArray,r=0;r<t.length;++r)t[r].resolve();return this},n.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.methodsArray.forEach(e=>{e._resolveFeaturesRecursive(t)}),this):this},n.prototype.add=function(r){if(this.get(r.name))throw Error("duplicate name '"+r.name+"' in "+this);return r instanceof t?"__proto__"===r.name?this:(this.methods[r.name]=r,r.parent=this,i(this)):e.prototype.add.call(this,r)},n.prototype.remove=function(r){if(r instanceof t){if(this.methods[r.name]!==r)throw Error(r+" is not a member of "+this);return delete this.methods[r.name],r.parent=null,i(this)}return e.prototype.remove.call(this,r)},n.prototype.create=function(e,t,n){for(var i,o=new s.Service(e,t,n),a=0;a<this.methodsArray.length;++a){o[r.lcFirst((i=this._methodsArray[a]).resolve().name).replace(/[^$\w_]/g,"")]=function(e,t,r){return function(n,i){return s.Service.prototype.rpcCall.call(this,e,t,r,n,i)}}(i,i.resolvedRequestType.ctor,i.resolvedResponseType.ctor)}return o},Io}function Uo(){if(To)return _o;To=1,_o=t;var e=xi();function t(e){if(e)for(var t=Object.keys(e),r=0;r<t.length;++r){var s=t[r];"__proto__"!==s&&(this[s]=e[s])}}return t.create=function(e){return this.$type.create(e)},t.encode=function(e,t){return this.$type.encode(e,t)},t.encodeDelimited=function(e,t){return this.$type.encodeDelimited(e,t)},t.decode=function(e){return this.$type.decode(e)},t.decodeDelimited=function(e){return this.$type.decodeDelimited(e)},t.verify=function(e){return this.$type.verify(e)},t.fromObject=function(e){return this.$type.fromObject(e)},t.toObject=function(e,t){return this.$type.toObject(e,t)},t.prototype.toJSON=function(){return this.$type.toObject(this,e.toJSONOptions)},_o}function Lo(){if(So)return Co;So=1,Co=function(n){for(var i=r.codegen(["r","l","e","n"],n.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("if(n===undefined)n=0")("if(n>Reader.recursionLimit)")('throw Error("maximum nesting depth exceeded")')("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(n.fieldsArray.filter(function(e){return e.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),o=0;o<n.fieldsArray.length;++o){var a=n._fieldsArray[o].resolve(),c=a.resolvedType instanceof e?"int32":a.type,d="m"+r.safeProp(a.name);i("case %i: {",a.id),a.map?(i("if(%s===util.emptyObject)",d)("%s={}",d)("var c2 = r.uint32()+r.pos"),void 0!==t.defaults[a.keyType]?i("k=%j",t.defaults[a.keyType]):i("k=null"),void 0!==t.defaults[c]?i("value=%j",t.defaults[c]):i("value=null"),i("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===t.basic[c]?i("value=types[%i].decode(r,r.uint32(),undefined,n+1)",o):i("value=r.%s()",c),i("break")("default:")("r.skipType(tag2&7,n)")("break")("}")("}"),void 0!==t.long[a.keyType]?i('%s[typeof k==="object"?util.longToHash(k):k]=value',d):("string"===a.keyType&&i('if(k==="__proto__")')("util.makeProp(%s,k)",d),i("%s[k]=value",d))):a.repeated?(i("if(!(%s&&%s.length))",d,d)("%s=[]",d),void 0!==t.packed[c]&&i("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",d,c)("}else"),void 0===t.basic[c]?i(a.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4),n+1))":"%s.push(types[%i].decode(r,r.uint32(),undefined,n+1))",d,o):i("%s.push(r.%s())",d,c)):void 0===t.basic[c]?i(a.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4),n+1)":"%s=types[%i].decode(r,r.uint32(),undefined,n+1)",d,o):i("%s=r.%s()",d,c),i("break")("}")}for(i("default:")("r.skipType(t&7,n)")("break")("}")("}"),o=0;o<n._fieldsArray.length;++o){var u=n._fieldsArray[o];u.required&&i("if(!Object.hasOwnProperty.call(m,%j))",u.name)("throw util.ProtocolError(%j,{instance:m})",s(u))}return i("return m")};var e=pa(),t=da(),r=ca();function s(e){return"missing required '"+e.name+"'"}return Co}function ko(){if(wo)return Eo;wo=1,Eo=function(e){var i=t.codegen(["m","n"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected")("if(n===undefined)n=0")("if(n>util.recursionLimit)")("return%j","maximum nesting depth exceeded"),o=e.oneofsArray,a={};o.length&&i("var p={}");for(var c=0;c<e.fieldsArray.length;++c){var d=e._fieldsArray[c].resolve(),u="m"+t.safeProp(d.name);if(d.optional&&i("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",u,d.name),d.map)i("if(!util.isObject(%s))",u)("return%j",r(d,"object"))("var k=Object.keys(%s)",u)("for(var i=0;i<k.length;++i){"),n(i,d,"k[i]"),s(i,d,c,u+"[k[i]]")("}");else if(d.repeated)i("if(!Array.isArray(%s))",u)("return%j",r(d,"array"))("for(var i=0;i<%s.length;++i){",u),s(i,d,c,u+"[i]")("}");else{if(d.partOf){var l=t.safeProp(d.partOf.name);1===a[d.partOf.name]&&i("if(p%s===1)",l)("return%j",d.partOf.name+": multiple values"),a[d.partOf.name]=1,i("p%s=1",l)}s(i,d,c,u)}d.optional&&i("}")}return i("return null")};var e=pa(),t=ca();function r(e,t){return e.name+": "+t+(e.repeated&&"array"!==t?"[]":e.map&&"object"!==t?"{k:"+e.keyType+"}":"")+" expected"}function s(t,s,n,i){if(s.resolvedType)if(s.resolvedType instanceof e){t("switch(%s){",i)("default:")("return%j",r(s,"enum value"));for(var o=Object.keys(s.resolvedType.values),a=0;a<o.length;++a)t("case %i:",s.resolvedType.values[o[a]]);t("break")("}")}else t("{")("var e=types[%i].verify(%s,n+1);",n,i)("if(e)")("return%j+e",s.name+".")("}");else switch(s.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.isInteger(%s))",i)("return%j",r(s,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",i,i,i,i)("return%j",r(s,"integer|Long"));break;case"float":case"double":t('if(typeof %s!=="number")',i)("return%j",r(s,"number"));break;case"bool":t('if(typeof %s!=="boolean")',i)("return%j",r(s,"boolean"));break;case"string":t("if(!util.isString(%s))",i)("return%j",r(s,"string"));break;case"bytes":t('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',i,i,i)("return%j",r(s,"buffer"))}return t}function n(e,t,s){switch(t.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.key32Re.test(%s))",s)("return%j",r(t,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.key64Re.test(%s))",s)("return%j",r(t,"integer|Long key"));break;case"bool":e("if(!util.key2Re.test(%s))",s)("return%j",r(t,"boolean key"))}return e}return Eo}var Do,Po={};function xo(){return Do||(Do=1,function(e){var t=e,r=pa(),s=ca();function n(e,t,s,n){var i=!1;if(t.resolvedType)if(t.resolvedType instanceof r){e("switch(d%s){",n);for(var o=t.resolvedType.values,a=Object.keys(o),c=0;c<a.length;++c)o[a[c]]!==t.typeDefault||i||(e("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',n,n,n),t.repeated||e("break"),i=!0),e("case%j:",a[c])("case %i:",o[a[c]])("m%s=%j",n,o[a[c]])("break");e("}")}else e("if(!util.isObject(d%s))",n)("throw TypeError(%j)",t.fullName+": object expected")("m%s=types[%i].fromObject(d%s,n+1)",n,s,n);else{var d=!1;switch(t.type){case"double":case"float":e("m%s=Number(d%s)",n,n);break;case"uint32":case"fixed32":e("m%s=d%s>>>0",n,n);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",n,n);break;case"uint64":case"fixed64":d=!0;case"int64":case"sint64":case"sfixed64":e("if(util.Long)")("m%s=util.Long.fromValue(d%s,%j)",n,n,d)('else if(typeof d%s==="string")',n)("m%s=parseInt(d%s,10)",n,n)('else if(typeof d%s==="number")',n)("m%s=d%s",n,n)('else if(typeof d%s==="object")',n)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",n,n,n,d?"true":"");break;case"bytes":e('if(typeof d%s==="string")',n)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",n,n,n)("else if(d%s.length >= 0)",n)("m%s=d%s",n,n);break;case"string":e("m%s=String(d%s)",n,n);break;case"bool":e("m%s=Boolean(d%s)",n,n)}}return e}function i(e,t,s,n){if(t.resolvedType)t.resolvedType instanceof r?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,s,n,n,s,n,n):e("d%s=types[%i].toObject(m%s,o,q+1)",n,s,n);else{var i=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":case"fixed64":i=!0;case"int64":case"sint64":case"sfixed64":e('if(typeof BigInt!=="undefined"&&o.longs===BigInt)')('d%s=typeof m%s==="number"?BigInt(m%s):util.Long.fromBits(m%s.low>>>0,m%s.high>>>0,%j).toBigInt()',n,n,n,n,n,i)('else if(typeof m%s==="number")',n)("d%s=o.longs===String?String(m%s):m%s",n,n,n)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",n,n,n,n,i?"true":"",n);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}t.fromObject=function(e){var t=e.fieldsArray,i=s.codegen(["d","n"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return i("return new this.ctor");i("if(!util.isObject(d))")("throw TypeError(%j)",e.fullName+": object expected")("if(n===undefined)n=0")("if(n>util.recursionLimit)")('throw Error("maximum nesting depth exceeded")'),i("var m=new this.ctor");for(var o=0;o<t.length;++o){var a=t[o].resolve(),c=s.safeProp(a.name);a.map?(i("if(d%s){",c)("if(!util.isObject(d%s))",c)("throw TypeError(%j)",a.fullName+": object expected")("m%s={}",c)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",c),i('if(ks[i]==="__proto__")')("util.makeProp(m%s,ks[i])",c),n(i,a,o,c+"[ks[i]]")("}")("}")):a.repeated?(i("if(d%s){",c)("if(!Array.isArray(d%s))",c)("throw TypeError(%j)",a.fullName+": array expected")("m%s=[]",c)("for(var i=0;i<d%s.length;++i){",c),n(i,a,o,c+"[i]")("}")("}")):(a.resolvedType instanceof r||i("if(d%s!=null){",c),n(i,a,o,c),a.resolvedType instanceof r||i("}"))}return i("return m")},t.toObject=function(e){var t=e.fieldsArray.slice().sort(s.compareFieldsById);if(!t.length)return s.codegen()("return {}");for(var n=s.codegen(["m","o","q"],e.name+"$toObject")("if(!o)")("o={}")("if(q===undefined)q=0")("if(q>util.recursionLimit)")('throw Error("max depth exceeded")')("var d={}"),o=[],a=[],c=[],d=0;d<t.length;++d)t[d].partOf||(t[d].resolve().repeated?o:t[d].map?a:c).push(t[d]);if(o.length){for(n("if(o.arrays||o.defaults){"),d=0;d<o.length;++d)n("d%s=[]",s.safeProp(o[d].name));n("}")}if(a.length){for(n("if(o.objects||o.defaults){"),d=0;d<a.length;++d)n("d%s={}",s.safeProp(a[d].name));n("}")}if(c.length){for(n("if(o.defaults){"),d=0;d<c.length;++d){var u=c[d],l=s.safeProp(u.name);if(u.resolvedType instanceof r)n("d%s=o.enums===String?%j:%j",l,u.resolvedType.valuesById[u.typeDefault],u.typeDefault);else if(u.long)n("if(util.Long){")("var n=new util.Long(%i,%i,%j)",u.typeDefault.low,u.typeDefault.high,u.typeDefault.unsigned)('d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():typeof BigInt!=="undefined"&&o.longs===BigInt?n.toBigInt():n',l)("}else")('d%s=o.longs===String?%j:typeof BigInt!=="undefined"&&o.longs===BigInt?BigInt(%j):%i',l,u.typeDefault.toString(),u.typeDefault.toString(),u.typeDefault.toNumber());else if(u.bytes){var h=Array.prototype.slice.call(u.typeDefault);n("if(o.bytes===String)d%s=%j",l,String.fromCharCode.apply(String,u.typeDefault))("else{")("d%s=%j",l,h)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",l,l)("}")}else n("d%s=%j",l,u.typeDefault)}n("}")}var p=!1;for(d=0;d<t.length;++d){u=t[d];var m=e._fieldsArray.indexOf(u);l=s.safeProp(u.name);u.map?(p||(p=!0,n("var ks2")),n("if(m%s&&(ks2=Object.keys(m%s)).length){",l,l)("d%s={}",l)("for(var j=0;j<ks2.length;++j){"),n('if(ks2[j]==="__proto__")')("util.makeProp(d%s,ks2[j])",l),i(n,u,m,l+"[ks2[j]]")("}")):u.repeated?(n("if(m%s&&m%s.length){",l,l)("d%s=[]",l)("for(var j=0;j<m%s.length;++j){",l),i(n,u,m,l+"[j]")("}")):(n("if(m%s!=null&&Object.hasOwnProperty.call(m,%j)){",l,u.name),i(n,u,m,l),u.partOf&&n("if(o.oneofs)")("d%s=%j",s.safeProp(u.partOf.name),u.name)),n("}")}return n("return d")}}(Po)),Po}var Fo,Bo,Go,qo,$o,jo,Vo,Ko,zo,Ho,Wo,Jo,Qo,Zo,Yo,Xo,ea,ta,ra,sa,na={};function ia(){return Fo||(Fo=1,e=na,t=Uo(),r=xi(),e[".google.protobuf.Any"]={fromObject:function(e,t){if(e&&e["@type"]){var r=e["@type"].substring(e["@type"].lastIndexOf("/")+1),s=this.lookup(r);if(s){var n="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===n.indexOf("/")&&(n="/"+n),this.create({type_url:n,value:s.encode(s.fromObject(e,void 0===t?1:t+1)).finish()})}}return this.fromObject(e,t)},toObject:function(e,s,n){if(void 0===n&&(n=0),n>r.recursionLimit)throw Error("max depth exceeded");var i="",o="";if(s&&s.json&&e.type_url&&e.value){o=e.type_url.substring(e.type_url.lastIndexOf("/")+1),i=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var a=this.lookup(o);a&&(e=a.decode(e.value,void 0,void 0,n+1))}if(!(e instanceof this.ctor)&&e instanceof t){var c=e.$type.toObject(e,s,n+1);return""===i&&(i="type.googleapis.com/"),o=i+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),c["@type"]=o,c}return this.toObject(e,s,n)}}),na;var e,t,r}function oa(){if(Go)return Bo;Go=1,Bo=f;var e=Ao();((f.prototype=Object.create(e.prototype)).constructor=f).className="Type";var t=pa(),r=la(),s=ua(),n=No(),i=Mo(),o=Uo(),a=Bi(),c=Fi(),d=ca(),u=ma(),l=Lo(),h=ko(),p=xo(),m=ia();function f(t,r){t=t.replace(/\W/g,""),e.call(this,t,r),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function g(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}return Object.defineProperties(f.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t<e.length;++t){var r=this.fields[e[t]],s=r.id;if(this._fieldsById[s])throw Error("duplicate id "+s+" in "+this);this._fieldsById[s]=r}return this._fieldsById}},fieldsArray:{get:function(){return this._fieldsArray||(this._fieldsArray=d.toArray(this.fields))}},oneofsArray:{get:function(){return this._oneofsArray||(this._oneofsArray=d.toArray(this.oneofs))}},ctor:{get:function(){return this._ctor||(this.ctor=f.generateConstructor(this)())},set:function(e){var t=e.prototype;t instanceof o||((e.prototype=new o).constructor=e,d.merge(e.prototype,t)),e.$type=e.prototype.$type=this,d.merge(e,o,!0),this._ctor=e;for(var r=0;r<this.fieldsArray.length;++r)this._fieldsArray[r].resolve();var s={};for(r=0;r<this.oneofsArray.length;++r)s[this._oneofsArray[r].resolve().name]={get:d.oneOfGetter(this._oneofsArray[r].oneof),set:d.oneOfSetter(this._oneofsArray[r].oneof)};r&&Object.defineProperties(e.prototype,s)}}}),f.generateConstructor=function(e){for(var t,r=d.codegen(["p"],e.name),s=0;s<e.fieldsArray.length;++s)(t=e._fieldsArray[s]).map?r("this%s={}",d.safeProp(t.name)):t.repeated&&r("this%s=[]",d.safeProp(t.name));return r('if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null&&ks[i]!=="__proto__")')("this[ks[i]]=p[ks[i]]")},f.fromJSON=function(o,a,c){if(void 0===c&&(c=0),c>d.nestingLimit)throw Error("max depth exceeded");var u=new f(o,a.options);u.extensions=a.extensions,u.reserved=a.reserved;for(var l=Object.keys(a.fields),h=0;h<l.length;++h)u.add((void 0!==a.fields[l[h]].keyType?n.fromJSON:s.fromJSON)(l[h],a.fields[l[h]]));if(a.oneofs)for(l=Object.keys(a.oneofs),h=0;h<l.length;++h)u.add(r.fromJSON(l[h],a.oneofs[l[h]]));if(a.nested)for(l=Object.keys(a.nested),h=0;h<l.length;++h){var p=a.nested[l[h]];u.add((void 0!==p.id?s.fromJSON:void 0!==p.fields?f.fromJSON:void 0!==p.values?t.fromJSON:void 0!==p.methods?i.fromJSON:e.fromJSON)(l[h],p,c+1))}return a.extensions&&a.extensions.length&&(u.extensions=a.extensions),a.reserved&&a.reserved.length&&(u.reserved=a.reserved),a.group&&(u.group=!0),a.comment&&(u.comment=a.comment),a.edition&&(u._edition=a.edition),u._defaultEdition="proto3",u},f.prototype.toJSON=function(t){var r=e.prototype.toJSON.call(this,t),s=!!t&&Boolean(t.keepComments);return d.toObject(["edition",this._editionToJSON(),"options",r&&r.options||void 0,"oneofs",e.arrayToJSON(this.oneofsArray,t),"fields",e.arrayToJSON(this.fieldsArray.filter(function(e){return!e.declaringField}),t)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:void 0,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"group",this.group||void 0,"nested",r&&r.nested||void 0,"comment",s?this.comment:void 0])},f.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;e.prototype.resolveAll.call(this);var t=this.oneofsArray;for(s=0;s<t.length;)t[s++].resolve();for(var r=this.fieldsArray,s=0;s<r.length;)r[s++].resolve();return this},f.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.oneofsArray.forEach(e=>{e._resolveFeatures(t)}),this.fieldsArray.forEach(e=>{e._resolveFeatures(t)}),this):this},f.prototype.get=function(e){return Object.prototype.hasOwnProperty.call(this.fields,e)?this.fields[e]:this.oneofs&&Object.prototype.hasOwnProperty.call(this.oneofs,e)?this.oneofs[e]:this.nested&&Object.prototype.hasOwnProperty.call(this.nested,e)?this.nested[e]:null},f.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);if(t instanceof s&&void 0===t.extend){if(this._fieldsById?this._fieldsById[t.id]:this.fieldsById[t.id])throw Error("duplicate id "+t.id+" in "+this);if(this.isReservedId(t.id))throw Error("id "+t.id+" is reserved in "+this);if(this.isReservedName(t.name)||"$"===t.name.charAt(0))throw Error("name '"+t.name+"' is reserved in "+this);return"__proto__"===t.name?this:(t.parent&&t.parent.remove(t),this.fields[t.name]=t,t.message=this,t.onAdd(this),g(this))}if(t instanceof r){if("$"===t.name.charAt(0))throw Error("name '"+t.name+"' is reserved in "+this);return"__proto__"===t.name?this:(this.oneofs||(this.oneofs={}),this.oneofs[t.name]=t,t.onAdd(this),g(this))}return e.prototype.add.call(this,t)},f.prototype.remove=function(t){if(t instanceof s&&void 0===t.extend){if(!this.fields||this.fields[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.fields[t.name],t.parent=null,t.onRemove(this),g(this)}if(t instanceof r){if(!this.oneofs||this.oneofs[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.oneofs[t.name],t.parent=null,t.onRemove(this),g(this)}return e.prototype.remove.call(this,t)},f.prototype.isReservedId=function(t){return e.isReservedId(this.reserved,t)},f.prototype.isReservedName=function(t){return e.isReservedName(this.reserved,t)},f.prototype.create=function(e){return new this.ctor(e)},f.prototype.setup=function(){for(var e=this.fullName,t=[],r=0;r<this.fieldsArray.length;++r)t.push(this._fieldsArray[r].resolve().resolvedType);this.encode=u(this)({Writer:c,types:t,util:d}),this.decode=l(this)({Reader:a,types:t,util:d}),this.verify=h(this)({types:t,util:d}),this.fromObject=p.fromObject(this)({types:t,util:d}),this.toObject=p.toObject(this)({types:t,util:d});var s=m[e];if(s){var n=Object.create(this);n.fromObject=this.fromObject,this.fromObject=s.fromObject.bind(n),n.toObject=this.toObject,this.toObject=s.toObject.bind(n)}return this},f.prototype.encode=function(e,t){return this.setup().encode.apply(this,arguments)},f.prototype.encodeDelimited=function(e,t){return this.encode(e,t&&t.len?t.fork():t).ldelim()},f.prototype.decode=function(e,t,r,s){return this.setup().decode(e,t,r,s)},f.prototype.decodeDelimited=function(e){return e instanceof a||(e=a.create(e)),this.decode(e,e.uint32())},f.prototype.verify=function(e,t){return this.setup().verify(e,t)},f.prototype.fromObject=function(e,t){return this.setup().fromObject(e,t)},f.prototype.toObject=function(e,t){return this.setup().toObject.apply(this,arguments)},f.d=function(e){return function(t){d.decorateType(t,e)}},Bo}function aa(){if($o)return qo;$o=1,qo=c;var e=Ao();((c.prototype=Object.create(e.prototype)).constructor=c).className="Root";var t,r,s,n=ua(),i=pa(),o=la(),a=ca();function c(t){e.call(this,"",t),this.deferred=[],this.files=[],this._edition="proto2",this._fullyQualifiedObjects={}}function d(){}c.fromJSON=function(e,t,r){return r=a.checkDepth(r),t||(t=new c),e.options&&t.setOptions(e.options),t.addJSON(e.nested,r).resolveAll()},c.prototype.resolvePath=a.path.resolve,c.prototype.fetch=a.fetch,c.prototype.load=function e(t,n,i){"function"==typeof n&&(i=n,n=void 0);var o=this;if(!i)return a.asPromise(e,o,t,n);var c=i===d;function u(e,t){if(i){if(c)throw e;t&&t.resolveAll();var r=i;i=null,r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in s)return r}return null}function h(e,t,s){void 0===s&&(s=0);try{if(s>a.recursionLimit)throw Error("max depth exceeded");if(a.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),a.isString(t)){r.filename=e;var i,d=r(t,o,n),h=0;if(d.imports)for(;h<d.imports.length;++h)(i=l(d.imports[h])||o.resolvePath(e,d.imports[h]))&&p(i,!1,s+1);if(d.weakImports)for(h=0;h<d.weakImports.length;++h)(i=l(d.weakImports[h])||o.resolvePath(e,d.weakImports[h]))&&p(i,!0,s+1)}else o.setOptions(t.options).addJSON(t.nested)}catch(f){u(f)}c||m||u(null,o)}function p(e,t,r){if(void 0===r&&(r=0),e=l(e)||e,!(o.files.indexOf(e)>-1))if(o.files.push(e),e in s)c?h(e,s[e],r):(++m,setTimeout(function(){--m,h(e,s[e],r)}));else if(c){var n;try{n=a.fs.readFileSync(e).toString("utf8")}catch(d){return void(t||u(d))}h(e,n,r)}else++m,o.fetch(e,function(s,n){--m,i&&(s?t?m||u(null,o):u(s):h(e,n,r))})}var m=0;a.isString(t)&&(t=[t]);for(var f,g=0;g<t.length;++g)(f=o.resolvePath("",t[g]))&&p(f);return c?(o.resolveAll(),o):(m||u(null,o),o)},c.prototype.loadSync=function(e,t){if(!a.isNode)throw Error("not supported");return this.load(e,t,d)},c.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(e){return"'extend "+e.extend+"' in "+e.parent.fullName}).join(", "));return e.prototype.resolveAll.call(this)};var u=/^[A-Z]/;function l(e,t){var r=t.parent.lookup(t.extend);if(r){var s=new n(t.fullName,t.id,t.type,t.rule,void 0,t.options);return r.get(s.name)||(s.declaringField=t,t.extensionField=s,r.add(s)),!0}return!1}return c.prototype._handleAdd=function(e){if(e instanceof n)void 0===e.extend||e.extensionField||l(0,e)||this.deferred.push(e);else if(e instanceof i)u.test(e.name)&&(e.parent[e.name]=e.values);else if(!(e instanceof o)){if(e instanceof t)for(var r=0;r<this.deferred.length;)l(0,this.deferred[r])?this.deferred.splice(r,1):++r;for(var s=0;s<e.nestedArray.length;++s)this._handleAdd(e._nestedArray[s]);u.test(e.name)&&(e.parent[e.name]=e)}(e instanceof t||e instanceof i||e instanceof n)&&(this._fullyQualifiedObjects[e.fullName]=e)},c.prototype._handleRemove=function(t){if(t instanceof n){if(void 0!==t.extend)if(t.extensionField)t.extensionField.parent.remove(t.extensionField),t.extensionField=null;else{var r=this.deferred.indexOf(t);r>-1&&this.deferred.splice(r,1)}}else if(t instanceof i)u.test(t.name)&&delete t.parent[t.name];else if(t instanceof e){for(var s=0;s<t.nestedArray.length;++s)this._handleRemove(t._nestedArray[s]);u.test(t.name)&&delete t.parent[t.name]}delete this._fullyQualifiedObjects[t.fullName]},c._configure=function(e,n,i){t=e,r=n,s=i},qo}function ca(){if(jo)return Xi.exports;jo=1;var e,t,r,s,n,i,o=Xi.exports=xi(),a=Wi();o.codegen=eo(),o.fetch=oo(),o.path=(ao||(ao=1,s=(r=co).isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},n=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=s(e),n="";r&&(n=t.shift()+"/");for(var i=0;i<t.length;)".."===t[i]?i>0&&".."!==t[i-1]?t.splice(--i,2):r?t.splice(i,1):++i:"."===t[i]?t.splice(i,1):++i;return n+t.join("/")},r.resolve=function(e,t,r){return r||(t=n(t)),s(t)?t:(r||(e=n(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?n(e+"/"+t):t)}),co),o.patterns=(uo||(uo=1,(i=Ro).numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,i.typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,i.reservedRe=/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/),Ro);var c=o.patterns.reservedRe;o.fs=function(){if(ho)return lo;ho=1;var e=null;try{(e=to)&&e.readFile&&e.readFileSync||(e=null)}catch(t){}return lo=e}(),o.checkDepth=function(e){if(void 0===e&&(e=0),e>o.recursionLimit)throw Error("max depth exceeded");return e},o.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),s=0;s<t.length;)r[s]=e[t[s++]];return r}return[]},o.toObject=function(e){for(var t={},r=0;r<e.length;){var s=e[r++],n=e[r++];void 0!==n&&(t[s]=n)}return t},o.isReserved=function(e){return c.test(e)},o.safeProp=function(e){return!/^[$\w_]+$/.test(e)||c.test(e)?"["+JSON.stringify(e)+"]":"."+e},o.ucFirst=function(e){return e.charAt(0).toUpperCase()+e.substring(1)};var d=/_([a-z])/g;o.camelCase=function(e){return e.substring(0,1)+e.substring(1).replace(d,function(e,t){return t.toUpperCase()})},o.compareFieldsById=function(e,t){return e.id-t.id},o.decorateType=function(t,r){if(t.$type)return r&&t.$type.name!==r&&(o.decorateRoot.remove(t.$type),t.$type.name=r,o.decorateRoot.add(t.$type)),t.$type;e||(e=oa());var s=new e(r||t.name);return o.decorateRoot.add(s),s.ctor=t,Object.defineProperty(t,"$type",{value:s,enumerable:!1}),Object.defineProperty(t.prototype,"$type",{value:s,enumerable:!1}),s};var u=0;return o.decorateEnum=function(e){if(e.$type)return e.$type;t||(t=pa());var r=new t("Enum"+u++,e);return o.decorateRoot.add(r),Object.defineProperty(e,"$type",{value:r,enumerable:!1}),r},o.setProperty=function(e,t,r,s){if("object"!=typeof e)throw TypeError("dst must be an object");if(!t)throw TypeError("path must be specified");if((t=t.split(".")).length>o.recursionLimit)throw Error("max depth exceeded");return function e(t,r,n){var i=r.shift();if(o.isUnsafeProperty(i))return t;if(r.length>0)t[i]=e(t[i]||{},r,n);else{var a=t[i];if(a&&s)return t;a&&(n=[].concat(a).concat(n)),t[i]=n}return t}(e,t,r)},Object.defineProperty(o,"decorateRoot",{get:function(){return a.decorated||(a.decorated=new(aa()))}}),Xi.exports}function da(){return Vo||(Vo=1,function(e){var t=e,r=ca(),s=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function n(e,t){var r=0,n=Object.create(null);for(t|=0;r<e.length;)n[s[r+t]]=e[r++];return n}t.basic=n([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),t.defaults=n([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",r.emptyArray,null]),t.long=n([0,0,0,1,1],7),t.mapKey=n([0,0,0,5,5,0,0,0,1,1,0,2],2),t.packed=n([1,5,0,0,0,5,5,0,0,0,1,1,0])}(Yi)),Yi}function ua(){if(zo)return Ko;zo=1,Ko=o;var e=ha();((o.prototype=Object.create(e.prototype)).constructor=o).className="Field";var t,r=pa(),s=da(),n=ca(),i=/^required|optional|repeated$/;function o(t,r,o,a,c,d,u){if(n.isObject(a)?(u=c,d=a,a=c=void 0):n.isObject(c)&&(u=d,d=c,c=void 0),e.call(this,t,d),!n.isInteger(r)||r<0)throw TypeError("id must be a non-negative integer");if(!n.isString(o))throw TypeError("type must be a string");if(void 0!==a&&!i.test(a=a.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==c&&!n.isString(c))throw TypeError("extend must be a string");"proto3_optional"===a&&(a="optional"),this.rule=a&&"optional"!==a?a:void 0,this.type=o,this.id=r,this.extend=c||void 0,this.repeated="repeated"===a,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!n.Long&&void 0!==s.long[o],this.bytes="bytes"===o,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=u}return o.fromJSON=function(e,t){var r=new o(e,t.id,t.type,t.rule,t.extend,t.options,t.comment);return t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},Object.defineProperty(o.prototype,"required",{get:function(){return"LEGACY_REQUIRED"===this._features.field_presence}}),Object.defineProperty(o.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(o.prototype,"delimited",{get:function(){return this.resolvedType instanceof t&&"DELIMITED"===this._features.message_encoding}}),Object.defineProperty(o.prototype,"packed",{get:function(){return"PACKED"===this._features.repeated_field_encoding}}),Object.defineProperty(o.prototype,"hasPresence",{get:function(){return!this.repeated&&!this.map&&(this.partOf||this.declaringField||this.extensionField||"IMPLICIT"!==this._features.field_presence)}}),o.prototype.setOption=function(t,r,s){return e.prototype.setOption.call(this,t,r,s)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return n.toObject(["edition",this._editionToJSON(),"rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},o.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=s.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof t?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof r&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof r||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=n.Long.fromNumber(this.typeDefault,"uint64"===this.type||"fixed64"===this.type),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"==typeof this.typeDefault){var i;n.base64.test(this.typeDefault)?n.base64.decode(this.typeDefault,i=n.newBuffer(n.base64.length(this.typeDefault)),0):n.utf8.write(this.typeDefault,i=n.newBuffer(n.utf8.length(this.typeDefault)),0),this.typeDefault=i}return this.map?this.defaultValue=n.emptyObject:this.repeated?this.defaultValue=n.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof t&&(this.parent.ctor.prototype[this.name]=this.defaultValue),e.prototype.resolve.call(this)},o.prototype._inferLegacyProtoFeatures=function(e){if("proto2"!==e&&"proto3"!==e)return{};var r={};if("required"===this.rule&&(r.field_presence="LEGACY_REQUIRED"),this.parent&&void 0===s.defaults[this.type]){var n=this.parent.get(this.type.split(".").pop());n&&n instanceof t&&n.group&&(r.message_encoding="DELIMITED")}return!0===this.getOption("packed")?r.repeated_field_encoding="PACKED":!1===this.getOption("packed")&&(r.repeated_field_encoding="EXPANDED"),r},o.prototype._resolveFeatures=function(t){return e.prototype._resolveFeatures.call(this,this._edition||t)},o.d=function(e,t,r,s){return"function"==typeof t?t=n.decorateType(t).name:t&&"object"==typeof t&&(t=n.decorateEnum(t).name),function(i,a){n.decorateType(i.constructor).add(new o(a,e,t,r,{default:s}))}},o._configure=function(e){t=e},Ko}function la(){if(Wo)return Ho;Wo=1,Ho=s;var e=ha();((s.prototype=Object.create(e.prototype)).constructor=s).className="OneOf";var t=ua(),r=ca();function s(t,r,s,n){if(Array.isArray(r)||(s=r,r=void 0),e.call(this,t,s),void 0!==r&&!Array.isArray(r))throw TypeError("fieldNames must be an Array");this.oneof=r||[],this.fieldsArray=[],this.comment=n}function n(e){if(e.parent)for(var t=0;t<e.fieldsArray.length;++t)e.fieldsArray[t].parent||e.parent.add(e.fieldsArray[t])}return s.fromJSON=function(e,t){return new s(e,t.oneof,t.options,t.comment)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["options",this.options,"oneof",this.oneof,"comment",t?this.comment:void 0])},s.prototype.add=function(e){if(!(e instanceof t))throw TypeError("field must be a Field");return e.parent&&e.parent!==this.parent&&e.parent.remove(e),this.oneof.push(e.name),this.fieldsArray.push(e),e.partOf=this,n(this),this},s.prototype.remove=function(e){if(!(e instanceof t))throw TypeError("field must be a Field");var r=this.fieldsArray.indexOf(e);if(r<0)throw Error(e+" is not a member of "+this);return this.fieldsArray.splice(r,1),(r=this.oneof.indexOf(e.name))>-1&&this.oneof.splice(r,1),e.partOf=null,this},s.prototype.onAdd=function(t){e.prototype.onAdd.call(this,t);for(var r=0;r<this.oneof.length;++r){var s=t.get(this.oneof[r]);s&&!s.partOf&&(s.partOf=this,this.fieldsArray.push(s))}n(this)},s.prototype.onRemove=function(t){for(var r,s=0;s<this.fieldsArray.length;++s)(r=this.fieldsArray[s]).parent&&r.parent.remove(r);e.prototype.onRemove.call(this,t)},Object.defineProperty(s.prototype,"isProto3Optional",{get:function(){if(null==this.fieldsArray||1!==this.fieldsArray.length)return!1;var e=this.fieldsArray[0];return null!=e.options&&!0===e.options.proto3_optional}}),s.d=function(){for(var e=new Array(arguments.length),t=0;t<arguments.length;)e[t]=arguments[t++];return function(t,n){r.decorateType(t.constructor).add(new s(n,e)),Object.defineProperty(t,n,{get:r.oneOfGetter(e),set:r.oneOfSetter(e)})}},Ho}function ha(){if(Qo)return Jo;Qo=1,Jo=o,o.className="ReflectionObject";const e=la();var t,r=ca(),s={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},n={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},i={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function o(e,t){if(!r.isString(e))throw TypeError("name must be a string");if(t&&!r.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this._edition=null,this._defaultEdition="proto2",this._features={},this._featuresResolved=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}return Object.defineProperties(o.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),o.prototype.toJSON=function(){throw Error()},o.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var r=e.root;r instanceof t&&r._handleAdd(this)},o.prototype.onRemove=function(e){var r=e.root;r instanceof t&&r._handleRemove(this),this.parent=null,this.resolved=!1},o.prototype.resolve=function(){return this.resolved||this.root instanceof t&&(this.resolved=!0),this},o.prototype._resolveFeaturesRecursive=function(e){return this._resolveFeatures(this._edition||e)},o.prototype._resolveFeatures=function(t){if(!this._featuresResolved){var o={};if(!t)throw new Error("Unknown edition for "+this.fullName);var a=r.merge({},this.options&&this.options.features,this._inferLegacyProtoFeatures(t));if(this._edition){if("proto2"===t)o=Object.assign({},n);else if("proto3"===t)o=Object.assign({},i);else{if("2023"!==t)throw new Error("Unknown edition: "+t);o=Object.assign({},s)}return this._features=r.merge(o,a),void(this._featuresResolved=!0)}if(this.partOf instanceof e){var c=r.merge({},this.partOf._features);this._features=r.merge(c,a)}else if(this.declaringField);else{if(!this.parent)throw new Error("Unable to find a parent for "+this.fullName);var d=r.merge({},this.parent._features);this._features=r.merge(d,a)}this.extensionField&&(this.extensionField._features=this._features),this._featuresResolved=!0}},o.prototype._inferLegacyProtoFeatures=function(){return{}},o.prototype.getOption=function(e){if(this.options)return this.options[e]},o.prototype.setOption=function(e,t,s){return"__proto__"===e||(this.options||(this.options={}),/^features\./.test(e)?r.setProperty(this.options,e,t,s):s&&void 0!==this.options[e]||(this.getOption(e)!==t&&(this.resolved=!1),this.options[e]=t)),this},o.prototype.setParsedOption=function(e,t,s){if("__proto__"===e)return this;this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(s){var i=n.find(function(t){return Object.prototype.hasOwnProperty.call(t,e)});if(i){var o=i[e];r.setProperty(o,s,t)}else(i={})[e]=r.setProperty({},s,t),n.push(i)}else{var a={};a[e]=t,n.push(a)}return this},o.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),s=0;s<r.length;++s)this.setOption(r[s],e[r[s]],t);return this},o.prototype.toString=function(){var e=this.constructor.className,t=this.fullName;return t.length?e+" "+t:e},o.prototype._editionToJSON=function(){if(this._edition&&"proto3"!==this._edition)return this._edition},o._configure=function(e){t=e},Jo}function pa(){if(Yo)return Zo;Yo=1,Zo=s;var e=ha();((s.prototype=Object.create(e.prototype)).constructor=s).className="Enum";var t=Ao(),r=ca();function s(t,r,s,n,i,o){if(e.call(this,t,s),r&&"object"!=typeof r)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=n,this.comments=i||{},this.valuesOptions=o,this._valuesFeatures={},this.reserved=void 0,r)for(var a=Object.keys(r),c=0;c<a.length;++c)"__proto__"!==a[c]&&"number"==typeof r[a[c]]&&(this.valuesById[this.values[a[c]]=r[a[c]]]=a[c])}return s.prototype._resolveFeatures=function(t){return t=this._edition||t,e.prototype._resolveFeatures.call(this,t),Object.keys(this.values).forEach(e=>{var t=r.merge({},this._features);this._valuesFeatures[e]=r.merge(t,this.valuesOptions&&this.valuesOptions[e]&&this.valuesOptions[e].features||{})}),this},s.fromJSON=function(e,t){var r=new s(e,t.values,t.options,t.comment,t.comments);return r.reserved=t.reserved,t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["edition",this._editionToJSON(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",t?this.comment:void 0,"comments",t?this.comments:void 0])},s.prototype.add=function(e,t,s,n){if(!r.isString(e))throw TypeError("name must be a string");if(!r.isInteger(t))throw TypeError("id must be an integer");if("__proto__"===e)return this;if(void 0!==this.values[e])throw Error("duplicate name '"+e+"' in "+this);if(this.isReservedId(t))throw Error("id "+t+" is reserved in "+this);if(this.isReservedName(e))throw Error("name '"+e+"' is reserved in "+this);if(void 0!==this.valuesById[t]){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+t+" in "+this);this.values[e]=t}else this.valuesById[this.values[e]=t]=e;return n&&(void 0===this.valuesOptions&&(this.valuesOptions={}),this.valuesOptions[e]=n||null),this.comments[e]=s||null,this},s.prototype.remove=function(e){if(!r.isString(e))throw TypeError("name must be a string");var t=this.values[e];if(null==t)throw Error("name '"+e+"' does not exist in "+this);return delete this.valuesById[t],delete this.values[e],delete this.comments[e],this.valuesOptions&&delete this.valuesOptions[e],this},s.prototype.isReservedId=function(e){return t.isReservedId(this.reserved,e)},s.prototype.isReservedName=function(e){return t.isReservedName(this.reserved,e)},Zo}function ma(){if(ea)return Xo;ea=1,Xo=function(n){for(var i,o=r.codegen(["m","w","q"],n.name+"$encode")("if(!w)")("w=Writer.create()")("if(q===undefined)q=0")("if(q>util.recursionLimit)")('throw Error("max depth exceeded")'),a=n.fieldsArray.slice().sort(r.compareFieldsById),c=0;c<a.length;++c){var d=a[c].resolve(),u=n._fieldsArray.indexOf(d),l=d.resolvedType instanceof e?"int32":d.type,h=t.basic[l];i="m"+r.safeProp(d.name),d.map?(o("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",i,d.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",i)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(d.id<<3|2)>>>0,8|t.mapKey[d.keyType],d.keyType),void 0===h?o("types[%i].encode(%s[ks[i]],w.uint32(18).fork(),q+1).ldelim().ldelim()",u,i):o(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|h,l,i),o("}")("}")):d.repeated?(o("if(%s!=null&&%s.length){",i,i),d.packed&&void 0!==t.packed[l]?o("w.uint32(%i).fork()",(d.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",i)("w.%s(%s[i])",l,i)("w.ldelim()"):(o("for(var i=0;i<%s.length;++i)",i),void 0===h?s(o,d,u,i+"[i]"):o("w.uint32(%i).%s(%s[i])",(d.id<<3|h)>>>0,l,i)),o("}")):(d.optional&&o("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",i,d.name),void 0===h?s(o,d,u,i):o("w.uint32(%i).%s(%s)",(d.id<<3|h)>>>0,l,i))}return o("return w")};var e=pa(),t=da(),r=ca();function s(e,t,r,s){return t.delimited?e("types[%i].encode(%s,w.uint32(%i),q+1).uint32(%i)",r,s,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork(),q+1).ldelim()",r,s,(t.id<<3|2)>>>0)}return Xo}var fa=sa?ra:(sa=1,ra=function(){if(ta)return di.exports;ta=1;var e=di.exports=Ji();return e.build="light",e.load=function(t,r,s){return"function"==typeof r?(s=r,r=new e.Root):r||(r=new e.Root),r.load(t,s)},e.loadSync=function(t,r){return r||(r=new e.Root),r.loadSync(t)},e.encoder=ma(),e.decoder=Lo(),e.verifier=ko(),e.converter=xo(),e.ReflectionObject=ha(),e.Namespace=Ao(),e.Root=aa(),e.Enum=pa(),e.Type=oa(),e.Field=ua(),e.OneOf=la(),e.MapField=No(),e.Service=Mo(),e.Method=Oo(),e.Message=Uo(),e.wrappers=ia(),e.types=da(),e.util=ca(),e.ReflectionObject._configure(e.Root),e.Namespace._configure(e.Type,e.Service,e.Enum),e.Root._configure(e.Type),e.Field._configure(e.Type),di.exports}());const ga={nested:{easemob:{nested:{pb:{nested:{MessageBody:{fields:{type:{type:"Type",id:1},from:{type:"JID",id:2},to:{type:"JID",id:3},contents:{rule:"repeated",type:"Content",id:4},ext:{rule:"repeated",type:"KeyValue",id:5},ackMessageId:{type:"uint64",id:6},msgConfig:{type:"MessageConfig",id:7},ackContent:{type:"string",id:8},meta:{type:"string",id:9},editMessageId:{type:"uint64",id:11},editScope:{type:"EditScope",id:12},stream:{type:"Stream",id:13},userInfoUpdateTime:{type:"int32",id:14},namecardUpdateTime:{type:"int32",id:15},sendToPeer:{type:"bool",id:16},ackMessageIds:{rule:"repeated",type:"uint64",id:17},clearAllUnreadMessageCount:{type:"bool",id:18}},nested:{Content:{fields:{type:{type:"Type",id:1},text:{type:"string",id:2},latitude:{type:"double",id:3},longitude:{type:"double",id:4},address:{type:"string",id:5},displayName:{type:"string",id:6},remotePath:{type:"string",id:7},secretKey:{type:"string",id:8},fileLength:{type:"int32",id:9},action:{type:"string",id:10},params:{rule:"repeated",type:"KeyValue",id:11},duration:{type:"int32",id:12},size:{type:"Size",id:13},thumbnailRemotePath:{type:"string",id:14},thumbnailSecretKey:{type:"string",id:15},thumbnailDisplayName:{type:"string",id:16},thumbnailFileLength:{type:"int32",id:17},thumbnailSize:{type:"Size",id:18},customEvent:{type:"string",id:19},customExts:{rule:"repeated",type:"KeyValue",id:20},buildingName:{type:"string",id:21},subType:{type:"SubType",id:22},title:{type:"string",id:23},summary:{type:"string",id:24},combineLevel:{type:"int32",id:25},imageType:{type:"int32",id:26}},nested:{Type:{values:{TEXT:0,IMAGE:1,VIDEO:2,LOCATION:3,VOICE:4,FILE:5,COMMAND:6,CUSTOM:7,COMBINE:8}},Size:{fields:{width:{type:"double",id:1},height:{type:"double",id:2}}},SubType:{values:{COMBINE:0,GIF:1,SUB_STREAM:10}}}},Type:{values:{NORMAL:0,CHAT:1,GROUPCHAT:2,CHATROOM:3,READ_ACK:4,DELIVER_ACK:5,RECALL:6,CHANNEL_ACK:7,EDIT:8}},EditScope:{values:{BODY:1,BODY_AND_EXT:2}},MessageConfig:{fields:{allowGroupAck:{type:"bool",id:1}}},Stream:{fields:{streamType:{type:"string",id:1},streamSeq:{type:"uint64",id:2},streamStatus:{type:"StreamStatus",id:3},streamError:{type:"uint32",id:4},streamFinishReason:{type:"int32",id:5}},nested:{StreamStatus:{values:{STREAM_START:0,STREAM_START_COMPLETED:1,STREAM_IN_PROGRESS:2,STREAM_COMPLETED:3,STREAM_FULL:4}}}}}},KeyValue:{oneofs:{value:{oneof:["varintValue","floatValue","doubleValue","stringValue"]}},fields:{key:{type:"string",id:1},type:{type:"ValueType",id:2},varintValue:{type:"int64",id:3},floatValue:{type:"float",id:4},doubleValue:{type:"double",id:5},stringValue:{type:"string",id:6}},nested:{ValueType:{values:{BOOL:1,INT:2,UINT:3,LLINT:4,FLOAT:5,DOUBLE:6,STRING:7,JSON_STRING:8}}}},JID:{fields:{appKey:{type:"string",id:1},name:{type:"string",id:2},domain:{type:"string",id:3},clientResource:{type:"string",id:4}}},ConferenceBody:{fields:{sessionId:{type:"string",id:1},operation:{type:"Operation",id:2},conferenceId:{type:"string",id:3},type:{type:"Type",id:4},content:{type:"string",id:5},network:{type:"string",id:6},version:{type:"string",id:7},identity:{type:"Identity",id:8},duration:{type:"string",id:9},peerName:{type:"string",id:10},endReason:{type:"EndReason",id:11},status:{type:"Status",id:12},isDirect:{type:"bool",id:13},controlType:{type:"StreamControlType",id:14},routeFlag:{type:"int32",id:15},routeKey:{type:"string",id:16}},nested:{Status:{fields:{errorCode:{type:"int32",id:1}}},Operation:{values:{JOIN:0,INITIATE:1,ACCEPT_INITIATE:2,ANSWER:3,TERMINATE:4,REMOVE:5,STREAM_CONTROL:6,MEDIA_REQUEST:7}},Type:{values:{VOICE:0,VIDEO:1}},Identity:{values:{CALLER:0,CALLEE:1}},EndReason:{values:{HANGUP:0,NORESPONSE:1,REJECT:2,BUSY:3,FAIL:4,UNSUPPORTED:5,OFFLINE:6}},StreamControlType:{values:{PAUSE_VOICE:0,RESUME_VOICE:1,PAUSE_VIDEO:2,RESUME_VIDEO:3}}}},MSync:{fields:{version:{type:"Version",id:1,options:{default:"MSYNC_V1"}},guid:{type:"JID",id:2},auth:{type:"string",id:3},compressAlgorimth:{type:"uint32",id:4},crypto:{type:"uint32",id:5},userAgent:{type:"string",id:6},pov:{type:"uint64",id:7},command:{type:"Command",id:8},deviceId:{type:"uint32",id:10},encryptType:{rule:"repeated",type:"EncryptType",id:11,options:{packed:!1}},encryptKey:{type:"string",id:12},payload:{type:"bytes",id:9},traceId:{type:"uint64",id:20}},nested:{Version:{values:{MSYNC_V1:0,MSYNC_V2:1}},Command:{values:{SYNC:0,UNREAD:1,NOTICE:2,PROVISION:3,LOGOUT:4}}}},EncryptType:{values:{ENCRYPT_NONE:0,ENCRYPT_AES_128_CBC:1,ENCRYPT_AES_256_CBC:2}},CommSyncUL:{fields:{meta:{type:"Meta",id:1},key:{type:"uint64",id:2},queue:{type:"JID",id:3},isRoam:{type:"bool",id:4},lastFullRoamKey:{type:"uint64",id:5}}},CommSyncDL:{fields:{status:{type:"Status",id:1},metaId:{type:"uint64",id:2},serverId:{type:"uint64",id:3},metas:{rule:"repeated",type:"Meta",id:4},nextKey:{type:"uint64",id:5},queue:{type:"JID",id:6},isLast:{type:"bool",id:7},timestamp:{type:"uint64",id:8},isRoam:{type:"bool",id:9}}},CommNotice:{fields:{queue:{type:"JID",id:1}}},CommUnreadUL:{fields:{}},CommUnreadDL:{fields:{status:{type:"Status",id:1},unread:{rule:"repeated",type:"MetaQueue",id:2},timestamp:{type:"uint64",id:3}}},MetaQueue:{fields:{queue:{type:"JID",id:1},n:{type:"uint32",id:2}}},Meta:{fields:{id:{type:"uint64",id:1},from:{type:"JID",id:2},to:{type:"JID",id:3},timestamp:{type:"uint64",id:4},ns:{type:"NameSpace",id:5},payload:{type:"bytes",id:6},routetype:{type:"RouteType",id:7},ext:{rule:"repeated",type:"KeyValue",id:8},meta:{type:"bytes",id:9},directedUsers:{rule:"repeated",type:"string",id:10},env:{type:"string",id:13}},nested:{NameSpace:{values:{STATISTIC:0,CHAT:1,MUC:2,ROSTER:3,CONFERENCE:4,NOTIFY:5,QUERY:6}},RouteType:{values:{ROUTE_ALL:0,ROUTE_ONLINE:1,ROUTE_DIRECT:2}}}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},reason:{type:"string",id:2},redirectInfo:{rule:"repeated",type:"RedirectInfo",id:3}},nested:{ErrorCode:{values:{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}}}},RedirectInfo:{fields:{host:{type:"string",id:1},port:{type:"uint32",id:2}}},Provision:{fields:{osType:{type:"OsType",id:1},version:{type:"string",id:2},networkType:{type:"NetworkType",id:3},appSign:{type:"string",id:4},compressType:{rule:"repeated",type:"CompressType",id:5,options:{packed:!1}},encryptType:{rule:"repeated",type:"EncryptType",id:6,options:{packed:!1}},encryptKey:{type:"string",id:7},status:{type:"Status",id:8},deviceUuid:{type:"string",id:9},isManualLogin:{type:"bool",id:10},password:{type:"string",id:11},deviceName:{type:"string",id:12},resource:{type:"string",id:13},auth:{type:"string",id:14},serviceId:{type:"string",id:16},actionVersion:{type:"string",id:17},authToken:{type:"string",id:18},osCustomValue:{type:"uint32",id:19},sessionId:{type:"string",id:20},reason:{type:"string",id:21},protocolCompressType:{rule:"repeated",type:"CompressType",id:22},protocolCompressDirection:{type:"CompressDirection",id:23}},nested:{OsType:{values:{OS_IOS:0,OS_ANDROID:1,OS_LINUX:2,OS_OSX:3,OS_WIN:4,OS_CUSTOM:5,OS_OTHER:16}},NetworkType:{values:{NETWORK_NONE:0,NETWORK_WIFI:1,NETWORK_4G:2,NETWORK_3G:3,NETWORK_2G:4,NETWORK_WIRE:5}},CompressType:{values:{COMPRESS_NONE:0,COMPRESS_ZLIB:1,COMPRESS_LZ4:2}},CompressDirection:{values:{ONLY_UP:0,ONLY_DOWN:1,BI:2}}}},Logout:{fields:{sessionId:{type:"string",id:1},reason:{type:"string",id:2},status:{type:"Status",id:3}}},MUCBody:{fields:{mucId:{type:"JID",id:1},operation:{type:"Operation",id:2},from:{type:"JID",id:3},to:{rule:"repeated",type:"JID",id:4},setting:{type:"Setting",id:5},reason:{type:"string",id:6},isChatroom:{type:"bool",id:7},status:{type:"Status",id:8},isThread:{type:"bool",id:9},mucParentId:{type:"JID",id:10},mucName:{type:"string",id:11},eventInfo:{type:"EventInfo",id:12},mucMemberCount:{type:"int32",id:13},ext:{type:"string",id:14},leaveOtherRooms:{type:"bool",id:15},members:{rule:"repeated",type:"string",id:16}},nested:{Operation:{values:{CREATE:0,DESTROY:1,JOIN:2,LEAVE:3,APPLY:4,APPLY_ACCEPT:5,APPLY_DECLINE:6,INVITE:7,INVITE_ACCEPT:8,INVITE_DECLINE:9,KICK:10,GET_BLACKLIST:11,BAN:12,ALLOW:13,UPDATE:14,BLOCK:15,UNBLOCK:16,PRESENCE:17,ABSENCE:18,DIRECT_JOINED:19,ASSIGN_OWNER:20,ADD_ADMIN:21,REMOVE_ADMIN:22,ADD_MUTE:23,REMOVE_MUTE:24,UPDATE_ANNOUNCEMENT:25,DELETE_ANNOUNCEMENT:26,UPLOAD_FILE:27,DELETE_FILE:28,ADD_USER_WHITE_LIST:29,REMOVE_USER_WHITE_LIST:30,BAN_GROUP:31,REMOVE_BAN_GROUP:32,THREAD_CREATE:33,THREAD_DESTROY:34,THREAD_JOIN:35,THREAD_LEAVE:36,THREAD_KICK:37,THREAD_UPDATE:38,THREAD_PRESENCE:39,THREAD_ABSENCE:40,DISABLE_GROUP:41,ABLE_GROUP:42,SET_METADATA:43,DELETE_METADATA:44,GROUP_MEMBER_METADATA_UPDATE:45}},Setting:{fields:{name:{type:"string",id:1},desc:{type:"string",id:2},type:{type:"Type",id:3},maxUsers:{type:"int32",id:4},owner:{type:"string",id:5}},nested:{Type:{values:{PRIVATE_OWNER_INVITE:0,PRIVATE_MEMBER_INVITE:1,PUBLIC_JOIN_APPROVAL:2,PUBLIC_JOIN_OPEN:3,PUBLIC_ANONYMOUS:4}}}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},description:{type:"string",id:2},chatroomInfo:{type:"string",id:3}},nested:{ErrorCode:{values:{OK:0,PERMISSION_DENIED:1,WRONG_PARAMETER:2,MUC_NOT_EXIST:3,USER_NOT_EXIST:4,UNKNOWN:5}}}},EventInfo:{fields:{eventType:{type:"EventType",id:1,options:{default:"EVENT_NONE"}},ext:{type:"string",id:2}},nested:{EventType:{values:{EVENT_NONE:0,CIRCLE_CHANNEL:1}}}}}},RosterBody:{fields:{operation:{type:"Operation",id:1},status:{type:"Status",id:2},from:{type:"JID",id:3},to:{rule:"repeated",type:"JID",id:4},reason:{type:"string",id:5},rosterVer:{type:"string",id:6},biDirection:{type:"bool",id:7}},nested:{Operation:{values:{GET_ROSTER:0,GET_BLACKLIST:1,ADD:2,REMOVE:3,ACCEPT:4,DECLINE:5,BAN:6,ALLOW:7,REMOTE_ACCEPT:8,REMOTE_DECLINE:9}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},description:{type:"string",id:2}},nested:{ErrorCode:{values:{OK:0,USER_NOT_EXIST:1,USER_ALREADY_FRIEND:2,USER_ALREADY_BLACKLIST:3}}}}}},StatisticsBody:{fields:{operation:{type:"Operation",id:1},os:{type:"OsType",id:2},version:{type:"string",id:3},network:{type:"NetworkType",id:4},imTime:{type:"uint32",id:5},chatTime:{type:"uint32",id:6},location:{type:"string",id:7},reason:{type:"string",id:10}},nested:{Operation:{values:{INFORMATION:0,USER_REMOVED:1,USER_LOGIN_ANOTHER_DEVICE:2,USER_KICKED_BY_CHANGE_PASSWORD:3,USER_KICKED_BY_OTHER_DEVICE:4}},OsType:{values:{OS_IOS:0,OS_ANDROID:1,OS_LINUX:2,OS_OSX:3,OS_WIN:4,OS_CUSTOM:5,OS_OTHER:16}},NetworkType:{values:{NETWORK_NONE:0,NETWORK_WIFI:1,NETWORK_4G:2,NETWORK_3G:3,NETWORK_2G:4,NETWORK_WIRE:5}}}}}}}}}},ya=e=>{if(!e||0===e.trim().length)throw dn("Proto type name is required.",{code:cn,stage:en,retryable:!1,details:{typeName:e}})};class va{constructor(){this.codecMap=new Map}register(e,t){ya(e),this.codecMap.set(e,t)}registerType(e,t){this.register(e,{encode:r=>{const s=((e,t)=>{if("object"==typeof e&&null!==e)return e;throw dn("Proto payload must be an object.",{code:cn,stage:en,retryable:!1,details:{typeName:t,payloadType:typeof e}})})(r,e),n=t.fromObject(s);return t.encode(n).finish()},decode:e=>{const r=t.decode(e);return t.toObject(r,{longs:String,enums:Number,defaults:!1})}})}get(e){return ya(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw dn("Proto codec not found.",{code:cn,stage:en,retryable:!1,details:{typeName:e}})}}const Ia=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ba=e=>{class t extends fa.Message{constructor(e){super(),((e,t)=>{if(t)for(const r of Object.keys(t)){const s=t[r];null!=s&&(e[r]=s)}})(this,e)}}const r=t;return r.$type=e,r.prototype.$type=e,r},_a=e=>Dn.isLong(e),Ta=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"number"==typeof e.byteLength,Ca=e=>Object.prototype.hasOwnProperty.call(fa.types.packed,e),Sa=e=>{const t=e.resolve();return t.resolvedType instanceof fa.Enum||Ca(t.type)},Ea=(e,t)=>t in e?e[t]:void 0,wa=e=>{const t=e.resolve();return t.resolvedType instanceof fa.Enum?0:(r=t.type,Object.prototype.hasOwnProperty.call(fa.types.basic,r)?fa.types.basic[t.type]:2);var r},Ra=(e,t)=>_a(e)||"number"==typeof e||"string"==typeof e?e:Ia(e)&&"number"==typeof e.low&&"number"==typeof e.high?new Dn(e.low,e.high,t):t?Dn.UZERO:Dn.ZERO,Aa=(e,t,r)=>{switch(t){case"double":return e.double(Number(r));case"float":return e.float(Number(r));case"int32":return e.int32(Number(r));case"uint32":return e.uint32(Number(r));case"sint32":return e.sint32(Number(r));case"fixed32":return e.fixed32(Number(r));case"sfixed32":return e.sfixed32(Number(r));case"int64":return e.int64(Ra(r,!1));case"uint64":return e.uint64(Ra(r,!0));case"sint64":return e.sint64(Ra(r,!1));case"fixed64":return e.fixed64(Ra(r,!0));case"sfixed64":return e.sfixed64(Ra(r,!1));case"bool":return e.bool(Boolean(r));case"string":return e.string(String(r));case"bytes":return e.bytes((e=>"string"==typeof e?e:Ta(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)?Uint8Array.from(e.filter(e=>"number"==typeof e)):new Uint8Array)(r));default:throw new TypeError(`Unsupported protobuf field type: ${t}`)}},Na=(e,t,r)=>{if(t<0||e.pos+t>r)throw RangeError(`index out of range: ${e.pos} + ${t} > ${r}`)},Oa=(e,t)=>{const r=e.uint32();return Na(e,r,t),r},Ma=(e,t,r)=>{const s=e.len;e.len=r;try{switch(t){case 0:return void e.skip();case 1:return Na(e,8,r),void e.skip(8);case 2:{const t=Oa(e,r);return void e.skip(t)}case 5:return Na(e,4,r),void e.skip(4);default:throw new Error(`Unsupported protobuf wire type: ${String(t)}`)}}finally{e.len=s}},Ua=(e,t,r)=>{const s=t.resolve(),n=s.resolvedType;if(n instanceof fa.Type){const t=e.fork();return ka(n,Ia(r)?r:{},t),t.ldelim(),e}return n instanceof fa.Enum?(e.int32("number"==typeof r?r:Number(r)),e):Aa(e,s.type,r)},La=(e,t,r)=>{if(0===r.length)return e;const s=t.resolve();if(Ca(s.type)&&t.packed){e.uint32(t.id<<3|2).fork();for(const s of r)Ua(e,t,s);return e.ldelim(),e}const n=wa(t);for(const i of r)e.uint32(t.id<<3|n),Ua(e,t,i);return e},ka=(e,t,r=fa.Writer.create())=>{const s=e.fieldsArray.slice().sort(fa.util.compareFieldsById);for(const n of s){const e=Ea(t,n.name);null!=e&&(n.repeated?La(r,n,Array.isArray(e)?e:[]):(r.uint32(n.id<<3|wa(n)),Ua(r,n,e)))}return r},Da=(e,t,r,s)=>{const n=t.resolve(),i=n.resolvedType;return i instanceof fa.Type?2!==r?void Ma(e,r,s):Pa(i,e,Oa(e,s)):i instanceof fa.Enum?e.int32():((e,t)=>{switch(t){case"double":return e.double();case"float":return e.float();case"int32":return e.int32();case"uint32":return e.uint32();case"sint32":return e.sint32();case"fixed32":return e.fixed32();case"sfixed32":return e.sfixed32();case"int64":return e.int64();case"uint64":return e.uint64();case"sint64":return e.sint64();case"fixed64":return e.fixed64();case"sfixed64":return e.sfixed64();case"bool":return e.bool();case"string":return e.string();case"bytes":return e.bytes();default:throw new TypeError(`Unsupported protobuf field type: ${t}`)}})(e,n.type)},Pa=(e,t,r)=>{const s=t instanceof fa.Reader?t:fa.Reader.create(t),n=void 0===r?s.len:s.pos+r,i=(e=>{const t={};for(const r of e.fieldsArray)r.repeated&&(t[r.name]=[]);return t})(e),o=e.fieldsById;for(;s.pos<n;){const t=s.pos,r=s.uint32(),c=o[r>>>3],d=7&r;try{if(!c){Ma(s,d,n);continue}if(c.repeated){const e=Array.isArray(i[c.name])?i[c.name]:[];if(Sa(c)&&2===d){const t=Oa(s,n)+s.pos;for(;s.pos<t;)e.push(Da(s,c,0,t))}else{const t=Da(s,c,d,n);void 0!==t&&e.push(t)}i[c.name]=e;continue}const e=Da(s,c,d,n);void 0!==e&&(i[c.name]=e)}catch(a){if(a instanceof RangeError){const i=c?`${c.name}#${c.id}`:`unknown#${r>>>3}`;throw new RangeError(`${a.message}; protobufType=${e.fullName}; field=${i}; tag=${r}; wireType=${d}; tagPosition=${t}; readerPosition=${s.pos}; messageEnd=${n}`)}throw a}}return i},xa=(e,t)=>t?.longs===String?e.toString():t?.longs===Number?e.toNumber():e,Fa=(e,t)=>{const r=e.resolve();if(r.resolvedType instanceof fa.Type)return null;if(r.resolvedType instanceof fa.Enum){if(t?.enums===String){return r.resolvedType.valuesById[r.typeDefault]??r.typeDefault}return r.typeDefault}return"bytes"===r.type?t?.bytes===String?"":t?.bytes===Array?[]:new Uint8Array:r.long&&_a(r.typeDefault)?xa(r.typeDefault,t):r.typeDefault},Ba=(e,t,r)=>{const s=e.resolve();if(void 0!==t)return s.resolvedType instanceof fa.Type?Ia(t)?Ga(s.resolvedType,t,r):t:s.resolvedType instanceof fa.Enum?r?.enums===String&&"number"==typeof t?s.resolvedType.valuesById[t]??t:t:s.long&&_a(t)?xa(t,r):"bytes"===s.type&&Ta(t)?((e,t)=>t?.bytes===String?fa.util.base64.encode(e,0,e.length):t?.bytes===Array?Array.prototype.slice.call(e):e)(t,r):t},Ga=(e,t,r)=>{const s={};for(const n of e.fieldsArray.slice().sort(fa.util.compareFieldsById)){const e=Ea(t,n.name);n.repeated?Array.isArray(e)?s[n.name]=e.map(e=>Ba(n,e,r)):(r?.arrays||r?.defaults)&&(s[n.name]=[]):null==e?r?.defaults&&(s[n.name]=Fa(n,r)):s[n.name]=Ba(n,e,r)}return s},qa=e=>{const t=e;t.__reflectionCodecInstalled||(t.__reflectionCodecInstalled=!0,e.encode=(t,r)=>ka(e,Ia(t)?t:{},r),e.decode=(t,r)=>Pa(e,t,r),e.fromObject=e=>Ia(e)?e:{},e.toObject=(t,r)=>Ga(e,Ia(t)?t:{},r),e.create=e=>e?{...e}:{},e.verify=()=>null)},$a=e=>{qa(e);for(const t of e.nestedArray)if(t instanceof fa.Type)$a(t);else if(t instanceof fa.Namespace)for(const e of t.nestedArray)e instanceof fa.Type&&$a(e)},ja=e=>{for(const t of e.nestedArray)t instanceof fa.Type?$a(t):t instanceof fa.Namespace&&ja(t)},Va=()=>{const e=fa.Type;e.__reflectionRuntimeInstalled||(e.generateConstructor=e=>()=>ba(e),fa.Type.prototype.setup=function(){return qa(this),this},fa.Type.prototype.create=function(e){return e?{...e}:{}},fa.Type.prototype.encode=function(e,t){return ka(this,Ia(e)?e:{},t)},fa.Type.prototype.decode=function(e,t){return Pa(this,e,t)},fa.Type.prototype.fromObject=function(e){return Ia(e)?e:{}},fa.Type.prototype.toObject=function(e,t){return Ga(this,Ia(e)?e:{},t)},fa.Type.prototype.verify=function(){return null},e.__reflectionRuntimeInstalled=!0)};let Ka=!1,za=null,Ha=null,Wa=null;const Ja=e=>e.startsWith(".")?e.slice(1):e,Qa=e=>e instanceof fa.Namespace,Za=e=>e instanceof fa.Type,Ya=e=>{for(const t of e.nestedArray)Za(t)?$a(t):Qa(t)&&Ya(t)},Xa=()=>{Ka||(fa.util.Long=Dn,fa.configure(),Ka=!0),Va();const e=fa.Root.fromJSON(ga);return Ya(e),e},ec=(e,t)=>{const r=e.nestedArray;for(const s of r){if(Za(s)){const e=Ja(s.fullName);$a(s),t.registerType(e,s);continue}Qa(s)&&ec(s,t)}},tc=(e,t,r)=>{const s=t instanceof Error?t.message:String(t);return dn(`Static proto ${r} failed.`,{code:cn,stage:en,retryable:!1,details:{typeName:e,operation:r,cause:s}})},rc=()=>za||(za=Xa(),za),sc=()=>{if(Wa)return Wa;const e=(()=>{if(Ha)return Ha;const e=new va,t=rc();return ec(t,e),Ha=e,e})();return Wa={encode(t,r){try{return e.getOrThrow(Ja(t)).encode(r)}catch(s){throw tc(t,s,"encode")}},decode(t,r){try{return e.getOrThrow(Ja(t)).decode(r)}catch(s){throw tc(t,s,"decode")}}},Wa},nc=e=>{const t={};if(!e)return t;if("function"==typeof e.forEach)return e.forEach((e,r)=>{t[r]=e}),t;const r=e.get?.("content-type");return r&&(t["content-type"]=r),t},ic=async(e,t)=>{const r=e;if("function"!=typeof r.text){if("function"!=typeof r.json)return"";const e=await r.json();return t?e:JSON.stringify(e)}const s=await r.text();if(!t||0===s.length)return s;try{return JSON.parse(s)}catch{return s}},oc=e=>{const t=e?.fetchImpl;if("function"==typeof t)return{async request(r){const s=r.method??"GET",n={...r.headers??{}},i=new AbortController,o=r.timeoutMs??e?.timeoutMs??15e3;let a=!1;const c=()=>i.abort(r.signal?.reason);r.signal?.aborted?c():r.signal?.addEventListener("abort",c,{once:!0});const d=setTimeout(()=>{a=!0,i.abort()},o),u=((e,t,r)=>{if(e.body instanceof Uint8Array)return new Uint8Array(e.body).buffer;if("string"==typeof e.body)return e.body;if(e.body&&"GET"!==r)return Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),JSON.stringify(e.body)})(r,n,s);try{const e=await t(r.url,{method:s,headers:n,body:u,signal:i.signal});let o;if("arraybuffer"===r.responseType)o=await e.arrayBuffer();else if("text"===r.responseType)o=await e.text();else if("json"===r.responseType)o=await ic(e,!0);else{const t=e.headers.get("content-type")??"";o=await ic(e,t.includes("application/json"))}return{status:e.status,statusText:e.statusText,headers:nc(e.headers),data:o}}catch(l){const e=((e,t,r)=>t?"timeout":r?.aborted||e instanceof Error&&"AbortError"===e.name?"abort":"network")(l,a,r.signal);throw dn("Request adapter execution failed.",{code:nn,stage:Zs,retryable:"abort"!==e,details:{url:r.url,method:s,reason:e,cause:l instanceof Error?l.message:String(l)}})}finally{clearTimeout(d),r.signal?.removeEventListener("abort",c)}}}},ac=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,cc=e=>"function"==typeof e.on&&"function"==typeof e.off,dc=(e,t,r)=>{if(ac(e))return e.addEventListener(t,r),()=>{e.removeEventListener(t,r)};if(cc(e)){const s=e;return s.on(t,r),()=>{s.off(t,r)}}throw dn("Socket event listener API is unsupported.",{code:an,stage:Xs,retryable:!1,details:{event:t}})},uc=(e,t,r)=>{if(ac(e)){const s=(...n)=>{e.removeEventListener(t,s),r(...n)};return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)}}if(cc(e)){const s=e;if("function"==typeof s.once)return s.once?.(t,r),()=>{s.off(t,r)};let n=()=>{};return n=dc(e,t,(...e)=>{n(),r(...e)}),n}throw dn("Socket one-time listener API is unsupported.",{code:an,stage:Xs,retryable:!1,details:{event:t}})},lc=e=>{return"string"==typeof e||(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))||"undefined"!=typeof Blob&&e instanceof Blob?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:e&&"object"==typeof e&&"data"in e?lc(e.data):null;var t},hc=e=>{const t=new Set,r=new Set,s=new Set,n=new Set;return dc(e,"open",()=>{t.forEach(e=>{e()})}),dc(e,"message",(...e)=>{const t=lc(e[0]);null!==t&&r.forEach(e=>{e(t)})}),dc(e,"error",(...e)=>{const t=e[0];s.forEach(e=>{e(t)})}),dc(e,"close",(...e)=>{const t=(e=>{const[t,r]=e;if(t&&"object"==typeof t){const e=t;return{code:"number"==typeof e.code?e.code:void 0,reason:"string"==typeof e.reason?e.reason:void 0}}return{code:"number"==typeof t?t:void 0,reason:"string"==typeof r?r:ArrayBuffer.isView(r)?(new TextDecoder).decode(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)):void 0}})(e);n.forEach(e=>{e(t)})}),{get readyState(){return e.readyState},send(t){if(e.readyState!==ln)throw dn("Socket is not open.",{code:an,stage:Xs,retryable:!0,details:{readyState:e.readyState}});return e.send(t),Promise.resolve()},close(t,r){e.close(t,r)},onOpen:e=>(t.add(e),()=>{t.delete(e)}),onMessage:e=>(r.add(e),()=>{r.delete(e)}),onError:e=>(s.add(e),()=>{s.delete(e)}),onClose:e=>(n.add(e),()=>{n.delete(e)})}},pc=e=>{const t=e?.webSocketCtor;if(void 0!==t)return{connect:e=>new Promise((r,s)=>{let n;try{n=new t(e.url,e.protocols);try{n.binaryType="arraybuffer"}catch{}}catch(l){return void s(dn("Socket creation failed.",{code:an,stage:Xs,retryable:!0,details:{cause:l instanceof Error?l.message:String(l)}}))}let i,o=()=>{},a=()=>{},c=!1;const d=()=>{void 0!==i&&(clearTimeout(i),i=void 0)},u=()=>{c||(c=!0,o(),a(),d(),n.close(),s(dn("Socket connection timed out.",{code:an,stage:Xs,retryable:!0,details:{url:e.url,reason:"timeout"}})))};o=uc(n,"open",()=>{c||(c=!0,o(),a(),d(),r(hc(n)))}),a=uc(n,"error",e=>{if(c)return;c=!0,o(),a(),d();const t=e&&"object"==typeof e&&"type"in e?String(e.type):void 0;s(dn("Socket connection failed before open.",{code:an,stage:Xs,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(u,e.timeoutMs))})}},mc=(e,t)=>{throw dn("Upload adapter execution failed.",{code:on,stage:Ys,retryable:"abort"!==e,details:{reason:e,url:t.url}})},fc=e=>{const t=new FormData;return Object.entries(e.fields??{}).forEach(([e,r])=>{t.append(e,r)}),((e,t)=>{if("web-file"!==t.source.sourceType)throw dn("Web upload adapter only supports web-file source.",{code:on,stage:Ys,retryable:!1,details:{sourceType:t.source.sourceType}});const r=t.source.file;if(!r)throw dn("Upload source file is required for web-file uploads.",{code:on,stage:Ys,retryable:!1,details:{sourceType:t.source.sourceType}});const s="undefined"!=typeof Blob&&r instanceof Blob,n=t.source.name??"upload.bin",i=t.fileFieldName??"file";s?e.append(i,r,n):e.append(i,r)})(t,e),t},gc=(e,t,r)=>new Promise((s,n)=>{const i=e(),o=r.timeoutMs??t?.timeoutMs??3e4;((e,t)=>{e.upload&&t.onProgress&&e.upload.addEventListener("progress",e=>{if(!e.lengthComputable)return void t.onProgress?.({loaded:e.loaded});const r=e.total>0?e.loaded/e.total*100:void 0;t.onProgress?.({loaded:e.loaded,total:e.total,percent:r})})})(i,r),i.addEventListener("abort",()=>{try{mc("abort",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("timeout",()=>{try{mc("timeout",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("error",()=>{try{mc("network",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("load",()=>{s({status:i.status,body:i.responseText})});try{const e=fc(r);i.timeout=o,i.open(r.method??"POST",r.url),((e,t)=>{Object.entries(t??{}).forEach(([t,r])=>{e.setRequestHeader(t,r)})})(i,r.headers),i.send(e)}catch(a){n(dn("Upload adapter execution failed.",{code:on,stage:Ys,retryable:!1,details:{url:r.url,reason:"invalid-config",cause:a instanceof Error?a.message:String(a)}}))}}),yc=(e,t)=>e?"timeout":"abort",vc=e=>{const t=Boolean(e&&"xhrFactory"in e)?e?.xhrFactory:"undefined"!=typeof XMLHttpRequest?()=>new XMLHttpRequest:void 0,r=e?.fetchImpl;if("function"==typeof t||"function"==typeof r)return{upload(s){if("function"==typeof t)return gc(t,e,s);if("function"==typeof r)return(async(e,t,r)=>{const s=r.timeoutMs??t?.timeoutMs??3e4;let n=!1;const i="undefined"!=typeof AbortController?new AbortController:void 0,o=i&&Number.isFinite(s)?setTimeout(()=>{n=!0,i.abort()},s):void 0,a=((e,t)=>e??t?.signal)(r.signal,i);try{const t=fc(r),s=await e(r.url,{method:r.method??"POST",headers:r.headers,body:t,signal:a}),n=await s.text(),i=r.source.size;return"number"==typeof i&&r.onProgress?.({loaded:i,total:i,percent:i>0?100:void 0}),{status:s.status,body:n}}catch(c){const e=c instanceof Error&&"AbortError"===c.name;throw dn("Upload adapter execution failed.",{code:on,stage:Ys,retryable:!e,details:{reason:e?yc(n):"network",url:r.url,cause:c instanceof Error?c.message:String(c)}})}finally{o&&clearTimeout(o)}})(r,e,s);throw dn("Upload adapter execution failed.",{code:on,stage:Ys,retryable:!1,details:{reason:"missing-upload-runtime",url:s.url}})}}},Ic=(e,t)=>{const r=new e;return Object.entries(t.fields??{}).forEach(([e,t])=>{r.append(e,t)}),r.append(t.fileFieldName??"file",(e=>{const t=e.source;if("rn-uri"!==t.sourceType||!t.uri)throw dn("React Native upload adapter only supports rn-uri source.",{code:on,stage:Ys,retryable:!1,details:{sourceType:t.sourceType}});return{uri:t.uri,name:t.name??"upload.bin",type:t.mimeType??"application/octet-stream"}})(t)),r},bc=e=>{const t=e?.fetchImpl,r=e?.formDataCtor;if("function"==typeof t&&"function"==typeof r)return{async upload(s){const n=s.timeoutMs??e?.timeoutMs??3e4,i="function"==typeof AbortController?new AbortController:void 0;let o=!1;const a=i&&Number.isFinite(n)?setTimeout(()=>{o=!0,i.abort()},n):void 0;try{const e=Ic(r,s),n=await t(s.url,{method:s.method??"POST",headers:s.headers,body:e,signal:s.signal??i?.signal}),o=await n.text(),a=s.source.size;return"number"==typeof a&&s.onProgress?.({loaded:a,total:a,percent:a>0?100:void 0}),{status:n.status,body:o}}catch(c){if((e=>{if("object"!=typeof e||null===e)return!1;const t=e;return t.code===on&&t.stage===Ys})(c))throw c;const e=c instanceof Error&&"AbortError"===c.name;throw dn("React Native upload adapter execution failed.",{code:on,stage:Ys,retryable:!e||o,details:{url:s.url,reason:e?o?"timeout":"abort":"network",cause:c instanceof Error?c.message:String(c)}})}finally{void 0!==a&&clearTimeout(a)}}}},_c=(e,t)=>e+t&4294967295,Tc=(e,t,r,s,n,i)=>{return _c((o=_c(_c(t,e),_c(s,i)))<<(a=n)|o>>>32-a,r);var o,a},Cc=(e,t,r,s,n,i,o)=>Tc(t&r|~t&s,e,t,n,i,o),Sc=(e,t,r,s,n,i,o)=>Tc(t&s|r&~s,e,t,n,i,o),Ec=(e,t,r,s,n,i,o)=>Tc(t^r^s,e,t,n,i,o),wc=(e,t,r,s,n,i,o)=>Tc(r^(t|~s),e,t,n,i,o),Rc=(e,t)=>{let[r,s,n,i]=e;r=Cc(r,s,n,i,t[0]??0,7,-680876936),i=Cc(i,r,s,n,t[1]??0,12,-389564586),n=Cc(n,i,r,s,t[2]??0,17,606105819),s=Cc(s,n,i,r,t[3]??0,22,-1044525330),r=Cc(r,s,n,i,t[4]??0,7,-176418897),i=Cc(i,r,s,n,t[5]??0,12,1200080426),n=Cc(n,i,r,s,t[6]??0,17,-1473231341),s=Cc(s,n,i,r,t[7]??0,22,-45705983),r=Cc(r,s,n,i,t[8]??0,7,1770035416),i=Cc(i,r,s,n,t[9]??0,12,-1958414417),n=Cc(n,i,r,s,t[10]??0,17,-42063),s=Cc(s,n,i,r,t[11]??0,22,-1990404162),r=Cc(r,s,n,i,t[12]??0,7,1804603682),i=Cc(i,r,s,n,t[13]??0,12,-40341101),n=Cc(n,i,r,s,t[14]??0,17,-1502002290),s=Cc(s,n,i,r,t[15]??0,22,1236535329),r=Sc(r,s,n,i,t[1]??0,5,-165796510),i=Sc(i,r,s,n,t[6]??0,9,-1069501632),n=Sc(n,i,r,s,t[11]??0,14,643717713),s=Sc(s,n,i,r,t[0]??0,20,-373897302),r=Sc(r,s,n,i,t[5]??0,5,-701558691),i=Sc(i,r,s,n,t[10]??0,9,38016083),n=Sc(n,i,r,s,t[15]??0,14,-660478335),s=Sc(s,n,i,r,t[4]??0,20,-405537848),r=Sc(r,s,n,i,t[9]??0,5,568446438),i=Sc(i,r,s,n,t[14]??0,9,-1019803690),n=Sc(n,i,r,s,t[3]??0,14,-187363961),s=Sc(s,n,i,r,t[8]??0,20,1163531501),r=Sc(r,s,n,i,t[13]??0,5,-1444681467),i=Sc(i,r,s,n,t[2]??0,9,-51403784),n=Sc(n,i,r,s,t[7]??0,14,1735328473),s=Sc(s,n,i,r,t[12]??0,20,-1926607734),r=Ec(r,s,n,i,t[5]??0,4,-378558),i=Ec(i,r,s,n,t[8]??0,11,-2022574463),n=Ec(n,i,r,s,t[11]??0,16,1839030562),s=Ec(s,n,i,r,t[14]??0,23,-35309556),r=Ec(r,s,n,i,t[1]??0,4,-1530992060),i=Ec(i,r,s,n,t[4]??0,11,1272893353),n=Ec(n,i,r,s,t[7]??0,16,-155497632),s=Ec(s,n,i,r,t[10]??0,23,-1094730640),r=Ec(r,s,n,i,t[13]??0,4,681279174),i=Ec(i,r,s,n,t[0]??0,11,-358537222),n=Ec(n,i,r,s,t[3]??0,16,-722521979),s=Ec(s,n,i,r,t[6]??0,23,76029189),r=Ec(r,s,n,i,t[9]??0,4,-640364487),i=Ec(i,r,s,n,t[12]??0,11,-421815835),n=Ec(n,i,r,s,t[15]??0,16,530742520),s=Ec(s,n,i,r,t[2]??0,23,-995338651),r=wc(r,s,n,i,t[0]??0,6,-198630844),i=wc(i,r,s,n,t[7]??0,10,1126891415),n=wc(n,i,r,s,t[14]??0,15,-1416354905),s=wc(s,n,i,r,t[5]??0,21,-57434055),r=wc(r,s,n,i,t[12]??0,6,1700485571),i=wc(i,r,s,n,t[3]??0,10,-1894986606),n=wc(n,i,r,s,t[10]??0,15,-1051523),s=wc(s,n,i,r,t[1]??0,21,-2054922799),r=wc(r,s,n,i,t[8]??0,6,1873313359),i=wc(i,r,s,n,t[15]??0,10,-30611744),n=wc(n,i,r,s,t[6]??0,15,-1560198380),s=wc(s,n,i,r,t[13]??0,21,1309151649),r=wc(r,s,n,i,t[4]??0,6,-145523070),i=wc(i,r,s,n,t[11]??0,10,-1120210379),n=wc(n,i,r,s,t[2]??0,15,718787259),s=wc(s,n,i,r,t[9]??0,21,-343485551),e[0]=_c(r,e[0]),e[1]=_c(s,e[1]),e[2]=_c(n,e[2]),e[3]=_c(i,e[3])},Ac=(e,t)=>{const r=new Array(16).fill(0);for(let s=0;s<16;s+=1){const n=t+4*s;r[s]=(e[n]??0)|(e[n+1]??0)<<8|(e[n+2]??0)<<16|(e[n+3]??0)<<24}return r},Nc=e=>{let t="";for(let r=0;r<4;r+=1){t+=(e>>8*r&255).toString(16).padStart(2,"0")}return t},Oc=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let r=0;for(;r+64<=e.length;r+=64)Rc(t,Ac(e,r));const s=new Array(16).fill(0);let n=0;for(;r<e.length;r+=1){const t=n>>2;s[t]=(s[t]??0)|(e[r]??0)<<n%4*8,n+=1}const i=n>>2;s[i]=(s[i]??0)|128<<n%4*8,n>55&&(Rc(t,s),s.fill(0));const o=8*e.length;return s[14]=4294967295&o,s[15]=Math.floor(o/4294967296),Rc(t,s),t.map(Nc).join("")},Mc=async e=>{if("function"==typeof createImageBitmap){const t=await createImageBitmap(e);return{image:t,width:t.width,height:t.height,cleanup:()=>{t.close()}}}if("undefined"==typeof Image||"undefined"==typeof URL)throw dn("Image decode capability is missing for current platform",{code:sn,stage:tn,retryable:!1,details:{reason:"image decode unavailable"}});const t=URL.createObjectURL(e);return new Promise((e,r)=>{const s=new Image;s.onload=()=>{e({image:s,width:s.naturalWidth||s.width,height:s.naturalHeight||s.height,cleanup:()=>{URL.revokeObjectURL(t)}})},s.onerror=()=>{URL.revokeObjectURL(t),r(dn("Image decode failed",{code:on,stage:tn,retryable:!1,details:{reason:"image load error"}}))},s.src=t})},Uc=e=>{if(!(e=>"web-file"===e.sourceType&&"undefined"!=typeof Blob&&e.file instanceof Blob)(e))throw dn("Web image processor only supports web file source",{code:sn,stage:tn,retryable:!1,details:{sourceType:e.sourceType}});return e.file},Lc=()=>({async getImageInfo(e){const t=Uc(e),r=await Mc(t);try{return{width:r.width,height:r.height,mimeType:e.mimeType,fileSize:e.size,isGif:"image/gif"===e.mimeType}}finally{r.cleanup()}},async generateBigImage(e,t){const r=Uc(e),s=await Mc(r);try{const r=((e,t,r)=>{const s=Math.min(e,t);if(s<=r)return{width:e,height:t};const n=r/s;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(s.width,s.height,t.maxShortEdge),i=((e,t)=>{if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(e,t);if("undefined"!=typeof document){const r=document.createElement("canvas");return r.width=e,r.height=t,r}throw dn("Canvas capability is missing for current platform",{code:sn,stage:tn,retryable:!1,details:{reason:"canvas unavailable"}})})(r.width,r.height),o=i.getContext("2d");if(!o)throw dn("Canvas 2d context is missing",{code:sn,stage:tn,retryable:!1});o.drawImage(s.image,0,0,r.width,r.height);const a="image/png"===(n=e.mimeType)||"image/webp"===n?n:"image/jpeg",c=await(async(e,t,r)=>{if("convertToBlob"in e&&"function"==typeof e.convertToBlob)return e.convertToBlob({type:t,quality:r});if("toBlob"in e&&"function"==typeof e.toBlob)return new Promise((s,n)=>{e.toBlob(e=>{e?s(e):n(dn("Image encode failed",{code:on,stage:tn,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},t,r)});throw dn("Canvas encode capability is missing for current platform",{code:sn,stage:tn,retryable:!1,details:{reason:"canvas encode unavailable"}})})(i,a,t.quality),d=(e=>e.name??"image")(e),u="undefined"!=typeof File?new File([c],d,{type:a,lastModified:Date.now()}):void 0;return{source:{sourceType:"web-file",file:u??c,name:d,mimeType:a,size:u?.size??c.size},width:r.width,height:r.height,fileName:d,fileType:a,fileSize:u?.size??c.size,webFile:u}}finally{s.cleanup()}var n},async computeMd5(e){const t=Uc(e),r=await(async e=>{if("function"==typeof e.arrayBuffer)return e.arrayBuffer();if("undefined"==typeof FileReader)throw dn("Binary read capability is missing for current platform",{code:sn,stage:tn,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((t,r)=>{const s=new FileReader;s.onerror=()=>{r(dn("Binary read failed",{code:on,stage:tn,retryable:!1}))},s.onload=()=>{s.result instanceof ArrayBuffer?t(s.result):r(dn("Binary read returned invalid result",{code:on,stage:tn,retryable:!1}))},s.readAsArrayBuffer(e)})})(t);return Oc(new Uint8Array(r))}}),kc=e=>{if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"errMsg"in e){const t=e.errMsg;if("string"==typeof t)return t}return String(e)},Dc=e=>{if(!(e=>"miniapp-path"===e.sourceType&&"string"==typeof e.path&&e.path.length>0)(e))throw dn("Miniapp image processor only supports miniapp path source",{code:sn,stage:tn,retryable:!1,details:{sourceType:e.sourceType}});return e.path},Pc=e=>{const t=e.getFileSystemManager?.();if(t)return t;throw dn("Miniapp file system capability is missing",{code:sn,stage:tn,retryable:!1,details:{capability:"getFileSystemManager"}})},xc=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},Fc=async(e,t)=>new Promise((r,s)=>{e.getImageInfo({src:t,success:e=>{r(e)},fail:e=>{s(e instanceof Error?e:new Error(kc(e)))}})}).catch(e=>{throw dn("Miniapp image info read failed",{code:on,stage:tn,retryable:!1,details:{src:t,cause:kc(e)}})}),Bc=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,Gc=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const r=await Fc(e,t);return Bc(t,r)},qc=e=>({async getImageInfo(t){const r=Dc(t),s=await Fc(e,r),n=xc(s.type)??t.mimeType;return{width:s.width,height:s.height,mimeType:n,fileSize:t.size,isGif:"image/gif"===n}},async generateBigImage(t,r){const s=Dc(t);if("function"!=typeof e.compressImage)throw dn("Miniapp image compress capability is missing",{code:sn,stage:tn,retryable:!1,details:{capability:"compressImage"}});const n=await Fc(e,s),i=Bc(s,n),o=((e,t,r)=>{const s=Math.min(e,t);if(s<=r)return{width:e,height:t};const n=r/s;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(n.width,n.height,r.maxShortEdge),a=await new Promise((t,s)=>{e.compressImage?.({src:i,quality:Math.max(0,Math.min(100,Math.round(100*r.quality))),compressedWidth:o.width,compressedHeight:o.height,success:e=>{e.tempFilePath?t(e.tempFilePath):s(new Error("compressImage missing tempFilePath"))},fail:e=>{s(e instanceof Error?e:new Error(kc(e)))}})}).catch(e=>{throw dn("Miniapp image compress failed",{code:on,stage:tn,retryable:!1,details:{src:i,cause:kc(e)}})}),c=await Gc(e,a),d=await Fc(e,c),u=xc(d.type)??t.mimeType,l=await(async(e,t,r)=>{const s=Pc(e);return s.getFileInfo?new Promise((e,r)=>{s.getFileInfo?.({filePath:t,success:t=>{e(t.size)},fail:e=>{r(e instanceof Error?e:new Error(kc(e)))}})}).catch(e=>{throw dn("Miniapp file info read failed",{code:on,stage:tn,retryable:!1,details:{filePath:t,cause:kc(e)}})}):r})(e,c,t.size);return{source:{sourceType:"miniapp-path",path:c,name:t.name,mimeType:u,size:l},width:d.width,height:d.height,fileName:t.name,fileType:u,fileSize:l}},async computeMd5(t){const r=Dc(t),s=await Gc(e,r),n=await(async(e,t)=>{const r=Pc(e),s=await new Promise((e,s)=>{r.readFile({filePath:t,success:t=>{e(t.data)},fail:e=>{s(e instanceof Error?e:new Error(kc(e)))}})}).catch(e=>{throw dn("Miniapp file read failed",{code:on,stage:tn,retryable:!1,details:{filePath:t,cause:kc(e)}})});return s instanceof ArrayBuffer?new Uint8Array(s):"function"==typeof TextEncoder?(new TextEncoder).encode(s):Uint8Array.from(Array.from(s).map(e=>255&e.charCodeAt(0)))})(e,s);return Oc(n)}}),$c=new Set(["quotaexceedederror","ns_error_dom_quota_reached"]),jc=[/\bquota\b/i,/\bexceed(?:ed)?\s+storage\s+max(?:imum)?\s+size\b/i,/\b(?:storage\s+)?max(?:imum)?\s+size\b.*\bexceed(?:ed)?\b/i,/\bstorage\b.*\blimit\b.*\b(?:exceed(?:ed)?|reach(?:ed)?)\b/i],Vc=(e,t)=>{if("object"!=typeof e||null===e)return null;const r=e[t];return"string"==typeof r?r:null},Kc=e=>{if(!e)return!1;const t=Vc(e,"name");if(t&&$c.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,Vc(e,"message"),Vc(e,"errMsg")].some(e=>null!==e&&jc.some(t=>t.test(e)))},zc=e=>{if(e instanceof Error)return e;const t=Vc(e,"message")??Vc(e,"errMsg")??"Storage quota exceeded";return Object.assign(new Error(t),{name:"QuotaExceededError",cause:e})},Hc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Wc=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),Jc=e=>e===Js.ALIPAY_MINIAPP||e===Js.DINGTALK_MINIAPP,Qc=e=>{const t=e.replace(/\s/g,"").replace(/-/g,"+").replace(/_/g,"/"),r=t.endsWith("==")?2:t.endsWith("=")?1:0,s=Math.max(0,Math.floor(3*t.length/4)-r),n=new Uint8Array(s);let i=0;for(let o=0;o<t.length;o+=4){const e=Hc.indexOf(t[o]??""),r=Hc.indexOf(t[o+1]??""),a=t[o+2]??"=",c=t[o+3]??"=",d="="===a?0:Hc.indexOf(a),u="="===c?0:Hc.indexOf(c);if(e<0||r<0||d<0||u<0)return new ArrayBuffer(0);const l=e<<18|r<<12|d<<6|u;for(const t of[16,8,0])i<s&&(n[i]=l>>t&255,i+=1)}return n.buffer},Zc=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Yc=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},Xc=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(Zc(e)||ArrayBuffer.isView(e))return e;const r=e;return"data"in r&&r.data!==e?Xc(r.data,t+1):e},ed=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return Yc(e);if(Zc(e))try{return Yc(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return Yc(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(Array.isArray(e))return e.every(e=>Number.isInteger(e)&&e>=0&&e<=255)?Uint8Array.from(e):void 0;if("object"!=typeof e)return;const r=e;if("data"in r&&r.data!==e){const e=ed(r.data,t+1);if(e)return e}if("buffer"in r&&r.buffer!==e){const e=ed(r.buffer,t+1);if(!e)return;const s="number"==typeof r.byteOffset&&Number.isInteger(r.byteOffset)?r.byteOffset:0,n="number"==typeof r.byteLength&&Number.isInteger(r.byteLength)?r.byteLength:e.byteLength-s;if(s<0||n<0||s+n>e.byteLength)return;return e.slice(s,s+n)}},td=(e,t)=>{if("string"==typeof e)return e;const r=e instanceof Uint8Array?e:new Uint8Array(e);if(Jc(t)){const s=(e=>{let t="";for(let r=0;r<e.length;r+=3){const s=e[r]??0,n=e[r+1],i=e[r+2],o=s<<16|(n??0)<<8|(i??0);t+=Hc[o>>18&63],t+=Hc[o>>12&63],t+=void 0===n?"=":Hc[o>>6&63],t+=void 0===i?"=":Hc[63&o]}return t})(r);return Vs("Mini program socket frame encoded as Base64",{operation:"platform.socket.frame.encode-base64",hostPlatform:t,sourceType:e instanceof Uint8Array?"uint8array":"arraybuffer",sourceBytes:r.byteLength,encodedCharacters:s.length,sourcePrefixHex:Wc(r.subarray(0,8))}),s}const s=new ArrayBuffer(r.byteLength);return new Uint8Array(s).set(r),s},rd=(e,t)=>"string"!=typeof e&&Jc(t),sd=(e,t)=>{const r=Xc(e.data);if("string"==typeof r){if(!Jc(t))return r;const s=Qc(r),n=new Uint8Array(s);return Vs("Mini program socket Base64 frame decoded",{operation:"platform.socket.frame.decode-base64",hostPlatform:t,sourceType:r===e.data?"string":"wrapped-string",sourceCharacters:r.length,decodedBytes:s.byteLength,decodedPrefixHex:Wc(n.subarray(0,8)),decodedSuffixHex:Wc(n.subarray(Math.max(0,n.length-8)))}),s}const s=ed(r);if(!s){const s="object"==typeof e.data&&null!==e.data?e.data:void 0;return void Vs("Mini program socket frame shape is unsupported",{operation:"platform.socket.frame.unsupported-shape",hostPlatform:t,sourceType:typeof r,sourceTag:Object.prototype.toString.call(e.data),sourceKeys:s?Object.keys(s).slice(0,10):[],isBuffer:e.isBuffer})}if(!Jc(t))return s.buffer;const n=(e=>{let t="";for(const s of e){if(9!==s&&10!==s&&13!==s&&32!==s&&!(s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||43===s||45===s||47===s||61===s||95===s))return;t+=String.fromCharCode(s)}const r=t.replace(/\s/g,"");if(0!==r.length&&r.length%4!=1&&/^[A-Za-z0-9+/_-]+={0,2}$/.test(r))return r})(s);if(!n)return Vs("Mini program socket binary frame preserved",{operation:"platform.socket.frame.preserve-binary",hostPlatform:t,sourceType:Object.prototype.toString.call(r),sourceBytes:s.byteLength,sourcePrefixHex:Wc(s.subarray(0,8))}),s.buffer;const i=Qc(n),o=new Uint8Array(i);return Vs("Mini program socket Base64 buffer decoded",{operation:"platform.socket.frame.decode-base64-buffer",hostPlatform:t,sourceType:Object.prototype.toString.call(r),sourceBytes:s.byteLength,decodedBytes:i.byteLength,decodedPrefixHex:Wc(o.subarray(0,8)),decodedSuffixHex:Wc(o.subarray(Math.max(0,o.length-8)))}),i},nd=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),id=(e,t)=>("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e[t],od=e=>e instanceof Error?e.message:nd(e)&&"string"==typeof e.errMsg?e.errMsg:nd(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),ad=e=>e?{...e}:{},cd=e=>"number"==typeof e&&Number.isInteger(e)&&e>=100&&e<=599,ud=e=>cd(e.statusCode)?e.statusCode:cd(e.status)?e.status:void 0,ld=e=>{if(!nd(e))return{};const t={};return Object.entries(e).forEach(([e,r])=>{"string"==typeof r&&(t[e]=r)}),t},hd=e=>({...ld(e.headers),...ld(e.header)}),pd=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const r=()=>{t()};return e.addEventListener("abort",r,{once:!0}),()=>{e.removeEventListener("abort",r)}},md=e=>{try{e.close()}catch{}},fd=(e,t)=>new Promise((r,s)=>{let n=!1,i=()=>{};const o=(e,r,o)=>{n||(n=!0,i(),s(dn(e,{code:nn,stage:Zs,retryable:o,details:{url:t.url,method:"GET",cause:od(r)}})))},a=e.downloadFile?.({url:t.url,header:ad(t.headers),timeout:t.timeoutMs??15e3,success:s=>{const a=s.tempFilePath??s.apFilePath;a?((e,t)=>new Promise((r,s)=>{const n=e.getFileSystemManager?.();n?n.readFile({filePath:t,success:e=>{const t=ed(e.data);t?r(t.buffer):s(new Error("downloaded file response is not binary"))},fail:s}):s(new Error("getFileSystemManager returned no file system manager"))}))(e,a).then(e=>{n||(n=!0,i(),Vs("Mini program binary response read from downloaded file",{operation:"platform.request.arraybuffer.download-file",url:t.url,filePathType:s.apFilePath?"apFilePath":"tempFilePath",status:s.statusCode??200,bytes:e.byteLength}),r({status:s.statusCode??200,headers:s.header??{},data:e}))}).catch(e=>{o("Mini program downloaded file read failed.",e,!1)}):o("Mini program download did not return a file path.",s,!1)},fail:e=>{o("Mini program file download failed.",e,!0)}});i=pd(t.signal,()=>{a?.abort(),o("Mini program file download aborted.","abort",!1)})}),gd=e=>({request:t=>"arraybuffer"!==t.responseType||void 0!==t.method&&"GET"!==t.method||!(e=>"function"==typeof e.downloadFile&&"function"==typeof e.getFileSystemManager)(e)?new Promise((r,s)=>{let n=()=>{};const i=e.request({url:t.url,method:t.method??"GET",header:ad(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{n();const i=ud(e);void 0!==i?r({status:i,headers:hd(e),data:e.data}):s(dn("Mini program request response status is invalid.",{code:nn,stage:Zs,retryable:!1,details:{url:t.url,method:t.method??"GET",statusCode:e.statusCode,status:e.status}}))},fail:e=>{n(),s(dn("Mini program request failed.",{code:nn,stage:Zs,retryable:!0,details:{url:t.url,method:t.method??"GET",cause:od(e)}}))}});n=pd(t.signal,()=>{i.abort(),s(dn("Mini program request aborted.",{code:nn,stage:Zs,retryable:!1,details:{url:t.url,method:t.method??"GET",reason:"abort"}}))})}):fd(e,t)}),yd=(e,t)=>({connect:r=>new Promise((s,n)=>{let i,o,a=!1;const c=()=>{void 0!==o&&(clearTimeout(o),o=void 0)},d=(e,t,s)=>{a||(a=!0,c(),i&&md(i),n(dn(t,{code:an,stage:Xs,retryable:s,details:{url:r.url,cause:od(e)}})))},u=e=>{if(!(id(r=e,"send")&&id(r,"close")&&id(r,"onOpen")&&id(r,"onMessage")&&id(r,"onError")&&id(r,"onClose")))return void d(new Error("returnedType="+typeof e),"Mini program connectSocket did not return a SocketTask.",!1);var r;const n=e;if(a)return void md(n);i=n;const o=()=>{n.offOpen?.(u),n.offError?.(l)},u=()=>{a?md(n):(a=!0,c(),o(),s(((e,t,r=un)=>{const s=new Set,n=new Set,i=new Set,o=new Set;let a=r;return e.onOpen(()=>{a=ln,s.forEach(e=>{e()})}),e.onMessage(e=>{const r=sd(e,t);void 0!==r&&n.forEach(e=>{e(r)})}),e.onError(e=>{i.forEach(t=>{t(e)})}),e.onClose(e=>{a=pn,o.forEach(t=>{t({code:e.code,reason:e.reason})})}),{get readyState(){return a},send(r){if(a!==ln)throw dn("Mini program socket is not open.",{code:an,stage:Xs,retryable:!0,details:{readyState:a}});return new Promise((s,n)=>{e.send({data:td(r,t),...rd(r,t)?{isBuffer:!0}:{},success:s,fail:e=>{n(dn("Mini program socket send failed.",{code:an,stage:Xs,retryable:!0,details:{cause:od(e)}}))}})})},close(t,r){a=hn,e.close({code:t,reason:r})},onOpen:e=>(s.add(e),()=>{s.delete(e)}),onMessage:e=>(n.add(e),()=>{n.delete(e)}),onError:e=>(i.add(e),()=>{i.delete(e)}),onClose:e=>(o.add(e),()=>{o.delete(e)})}})(n,t,ln)))},l=e=>{o(),d(e.errMsg??"socket error","Mini program socket connection failed before open.",!0)};n.onOpen(u),n.onError(l)};let l;"number"==typeof r.timeoutMs&&r.timeoutMs>0&&(o=setTimeout(()=>{d("timeout","Mini program socket connection timed out.",!0)},r.timeoutMs));try{l=e.connectSocket({url:r.url,...t===Js.ALIPAY_MINIAPP?{multiple:!0}:{},protocols:Array.isArray(r.protocols)?[...r.protocols]:"string"==typeof r.protocols?[r.protocols]:void 0,fail:e=>{d(e,"Mini program socket connect failed.",!0)}})}catch(p){return void d(p,"Mini program socket creation failed.",!0)}var h;"object"!=typeof(h=l)||null===h||"function"!=typeof h.then?u(l):Promise.resolve(l).then(e=>u(e),e=>d(e,"Mini program socket connect failed.",!0))})}),vd=e=>({upload(t){const r=t.method??"POST";return"POST"!==r?Promise.reject(dn("Mini program upload only supports POST.",{code:on,stage:Ys,retryable:!1,details:{url:t.url,method:r,reason:"unsupported-method"}})):new Promise((r,s)=>{const n=(e=>{if("miniapp-path"!==e.sourceType||!e.path)throw dn("Mini program upload only supports miniapp-path source.",{code:on,stage:Ys,retryable:!1,details:{sourceType:e.sourceType}});return e})(t.source);let i=()=>{};const o=e.uploadFile({url:t.url,filePath:n.path,name:t.fileFieldName??"file",header:ad(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{i();const o=ud(e);void 0!==o?r({status:o,body:e.data}):s(dn("Mini program upload response status is invalid.",{code:on,stage:Ys,retryable:!1,details:{url:t.url,path:n.path,statusCode:e.statusCode,status:e.status}}))},fail:e=>{i(),s(dn("Mini program upload failed.",{code:on,stage:Ys,retryable:!0,details:{url:t.url,path:n.path,cause:od(e)}}))}});o.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),i=pd(t.signal,()=>{o.abort(),s(dn("Mini program upload aborted.",{code:on,stage:Ys,retryable:!1,details:{url:t.url,path:n.path,reason:"abort"}}))})})}}),Id=(e,t)=>{const r=(e=>e===Js.ALIPAY_MINIAPP||e===Js.DINGTALK_MINIAPP)(t);return{async getItem(t){if(id(e,"getStorageSync"))try{const s=(e=>nd(e)&&"data"in e?e.data:e)(e.getStorageSync(r?{key:t}:t));return"string"==typeof s&&s.length>0?s:null}catch{return null}return id(e,"getStorage")?new Promise(r=>{e.getStorage({key:t,success:e=>{r("string"==typeof e.data&&e.data.length>0?e.data:null)},fail:()=>{r(null)}})}):null},async setItem(t,s){if(id(e,"setStorageSync"))try{r?e.setStorageSync({key:t,data:s}):e.setStorageSync(t,s)}catch(n){if(Kc(n))throw zc(n)}else if(id(e,"setStorage"))return new Promise((r,i)=>{try{e.setStorage({key:t,data:s,success:r,fail:e=>{Kc(e)?i(zc(e)):r()}})}catch(n){if(Kc(n))return void i(zc(n));r()}})},async removeItem(t){if(id(e,"removeStorageSync"))try{e.removeStorageSync(r?{key:t}:t)}catch{}else if(id(e,"removeStorage"))return new Promise(r=>{try{e.removeStorage({key:t,success:r,fail:()=>{r()}})}catch{r()}})}}},bd=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>id(e,"getNetworkType")?new Promise(t=>{e.getNetworkType?.({success:e=>{t(e.networkType??"unknown")},fail:()=>{t("unknown")}})}):Promise.resolve("unknown"),onNetworkChange(t){const r=e=>{t(e.isConnected)};return id(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(r),id(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{id(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(r)}},onAppVisibilityChange(t){const r=()=>{t(!0)},s=()=>{t(!1)};return id(e,"onAppShow")&&e.onAppShow(r),id(e,"onAppHide")&&e.onAppHide(s),t(!0),()=>{id(e,"offAppShow")&&e.offAppShow(r),id(e,"offAppHide")&&e.offAppHide(s)}}}),_d=(e,t=Js.WECHAT_MINIAPP,r=t)=>{const s=(e=>{if(id(e,"request")&&id(e,"connectSocket")&&id(e,"uploadFile"))return e;throw dn("Mini program platform capability is missing.",{code:sn,stage:Qs,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(e),n="function"==typeof s.getImageInfo?qc(s):void 0;return{request:gd(s),socket:yd(s,r),upload:vd(s),runtime:bd(s,t),storage:Id(s,r),imageProcessor:n}},Td=["request","upload","socket"],Cd={request:"request",upload:"upload",socket:"connect"},Sd=[Js.WEB,Js.ELECTRON_RENDERER,Js.REACT_NATIVE],Ed=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},wd=e=>Sd.includes(e),Rd=(e,t)=>e!==Js.UNIAPP?wd(e):!Rn(t)&&!Nd(t)&&Cn(t),Ad=e=>Ed(e,"getImageInfo")&&Ed(e,"getFileSystemManager"),Nd=e=>!Rn(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;return"string"==typeof r?r:void 0}catch{return}})(e),Od=(e,t)=>{if(wd(e)&&e!==Js.REACT_NATIVE)return Lc();if(Mn(e)&&Ad(t))return qc(t);if(e===Js.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(Cn(e))return Lc();if(Ad(e.uni))return qc(e.uni);if(Ad(e.wx))return qc(e.wx)}},Md=e=>{const t=e.localStorage;if(t)return{getItem:e=>Promise.resolve(t.getItem(e)),setItem:(e,r)=>(t.setItem(e,r),Promise.resolve()),removeItem:e=>(t.removeItem(e),Promise.resolve())};const r=new Map;return{getItem(e){const t=r.has(e)?r.get(e)??null:null;return Promise.resolve(t)},setItem:(e,t)=>(r.set(e,t),Promise.resolve()),removeItem:e=>(r.delete(e),Promise.resolve())}},Ud=(e,t,r,s)=>{if(e===Js.UNIAPP&&Nd(r)&&void 0!==r.uni&&vn(r.uni))return{..._d(r.uni,e,t),proto:sc()};if(((e,t)=>!Rd(e,t)&&Mn(e))(e,r)&&vn(s))return{..._d(s,e,t),proto:sc()};const n=r.XMLHttpRequest,i=Rd(e,r),o=i?oc({fetchImpl:r.fetch}):void 0,a=i?pc({webSocketCtor:r.WebSocket}):void 0,c=e===Js.REACT_NATIVE?bc({fetchImpl:r.fetch,formDataCtor:r.FormData}):i?vc({xhrFactory:"function"==typeof n?()=>new n:void 0,fetchImpl:r.fetch}):void 0,d=i&&e!==Js.REACT_NATIVE?(u={platform:e,windowRef:r.window,documentRef:r.document,navigatorRef:r.navigator},{getPlatform:()=>u.platform,getNetworkType:()=>!1===u.navigatorRef?.onLine?Promise.resolve("none"):Promise.resolve(u.navigatorRef?.connection?.type??u.navigatorRef?.connection?.effectiveType??"unknown"),onNetworkChange(e){const t=u.windowRef;if(!t)return()=>{};const r=()=>{e(!0)},s=()=>{e(!1)};return t.addEventListener("online",r),t.addEventListener("offline",s),"boolean"==typeof u.navigatorRef?.onLine&&e(u.navigatorRef.onLine),()=>{t.removeEventListener("online",r),t.removeEventListener("offline",s)}},onAppVisibilityChange(e){const t=u.documentRef;if(!t)return()=>{};const r=()=>{e((e=>"hidden"!==e?.visibilityState)(t))};return t.addEventListener("visibilitychange",r),r(),()=>{t.removeEventListener("visibilitychange",r)}}}):(e=>({getPlatform:()=>e,onNetworkChange:e=>()=>{},onAppVisibilityChange:e=>()=>{}}))(e);var u;return{request:o,upload:c,socket:a,runtime:d,proto:sc(),storage:Md(r),imageProcessor:i&&e!==Js.REACT_NATIVE?Lc():Od(e,s)}},Ld=(e,t,r)=>{if(!t)return{...e,...r};const s=Td.filter(e=>void 0!==r[e]);if(s.length>0)throw dn("Transport adapter conflicts with network overrides.",{code:rn,stage:Qs,retryable:!1,details:{conflictingCapabilities:s}});const n=(e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)))(r);return{...e,request:t.request,upload:t.upload,socket:t.socket,...n}},kd=(e,t)=>{if(void 0!==e)return e;throw dn("Platform adapter initialization failed.",{code:rn,stage:Qs,retryable:!1,details:{capability:t}})},Dd=e=>{(e=>{if(!e)return;const t=Td.flatMap(t=>{const r=Cd[t];return Ed(e[t],r)?[]:[`${t}.${r}`]});if(0!==t.length)throw dn("Transport adapter has invalid capabilities.",{code:rn,stage:Qs,retryable:!1,details:{source:"transportAdapter",invalidCapabilities:t}})})(e?.transportAdapter);const t=fn(e?.runtimeInput),r=On(t,e?.prefer),s=r.platform,n=Ud(s,r.hostPlatform,t,r.global),i=((e,t)=>e?"function"==typeof e?e(t):e:{})(e?.overrides,n),o=Ld(n,e?.transportAdapter,i),a=(e=>({request:void 0!==e.request,upload:void 0!==e.upload,socket:void 0!==e.socket,runtime:void 0!==e.runtime,proto:void 0!==e.proto,storage:void 0!==e.storage,imageProcessor:void 0!==e.imageProcessor}))(o);Ln(a);return{platform:s,platformId:s,capability:a,request:kd(o.request,"request"),upload:kd(o.upload,"upload"),socket:kd(o.socket,"socket"),runtime:kd(o.runtime,"runtime"),proto:kd(o.proto,"proto"),storage:kd(o.storage,"storage"),imageProcessor:o.imageProcessor}},Pd=e=>{if(e instanceof bt)return e;if((e=>"object"==typeof e&&null!==e)(e)){const t=e.details;if(e.code===sn){const r=t?.capability;if(e.stage===tn&&"string"==typeof r&&r.includes("FileSystem")){const r=e instanceof Error?e.message:"Upload failed";return new bt(r,{code:ot.UPLOAD_REQUEST_FAILED,details:t})}return new bt("Upload capability is missing for current platform",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:t})}if(e.stage===Ys)return(e=>{const t=e?.reason;return!("string"!=typeof t||!t.toLowerCase().includes("abort"))})(t)?new bt("Upload canceled",{code:ot.UPLOAD_ABORTED,details:t}):(e=>{const t=e?.reason;return!("string"!=typeof t||!t.toLowerCase().includes("timeout"))})(t)?new bt("Upload timeout",{code:ot.UPLOAD_TIMEOUT,details:t}):new bt("Upload failed",{code:ot.UPLOAD_REQUEST_FAILED,details:t})}const t=e instanceof Error?e.message:"Upload failed";return new bt(t,{code:ot.UPLOAD_REQUEST_FAILED,details:{cause:e}})},xd=e=>{if(e)return e;const t=fn(),r=pc({webSocketCtor:t.WebSocket});if(r)return r;throw dn("Socket capability is missing for current platform.",{code:sn,stage:Xs,retryable:!1,details:{capability:"socket"}})},Fd={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class Bd{constructor(e={}){this.attemptCount=0,this.config={...Fd,...e}}getRetryDelay(){const e=Math.max(this.attemptCount-1,0),t=this.config.initialDelay*Math.pow(this.config.backoffMultiplier,e),r=Math.min(t,this.config.maxDelay);return r/2+r/2*Math.min(1,Math.max(0,this.config.randomSource()))}recordAttempt(){this.attemptCount++}reset(){this.attemptCount=0}shouldRetry(){return this.attemptCount<this.config.maxAttempts}getAttemptCount(){return this.attemptCount}async waitForRetry(){const e=this.getRetryDelay();return js(`Waiting ${e}ms before retry (attempt ${this.attemptCount})`),new Promise(t=>setTimeout(t,e))}}const Gd={interval:3e4,timeout:6e4},qd="function"==typeof TextDecoder?new TextDecoder:null;class $d{constructor(e={}){this.websocket=null,this.heartbeatTimer=null,this.timeoutTimer=null,this.lastPongTime=0,this.onTimeoutCallback=null,this.sendPing=null,this.probeResolvers=[],this.messageDisposer=null,this.handlePong=e=>{const t=this.extractMessageText(e);if(!t)return;const r=this.parseJson(t);if(!$d.isRecord(r))return;"pong"===$d.readString(r.type)&&(this.markAlive(),js("Pong received"))},this.config={...Gd,...e}}start(e,t,r){this.heartbeatTimer&&this.stop(),this.attachWebSocket(e),this.onTimeoutCallback=t||null,this.sendPing=r??null,this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{this.sendPingInternal()},this.config.interval),js("Heartbeat started",{interval:this.config.interval})}stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.timeoutTimer&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null),this.messageDisposer?.(),this.messageDisposer=null,this.websocket=null,this.sendPing=null,this.resolveProbe(!1),js("Heartbeat stopped")}sendPingInternal(){if(this.websocket&&this.websocket.readyState===ln)try{if(this.sendPing)this.sendPing();else{const e=JSON.stringify({type:"ping",timestamp:Date.now()});Promise.resolve(this.websocket.send(e)).catch(e=>{Ks("Failed to send ping:",e),this.resolveProbe(!1)})}this.resetTimeout(),js("Ping sent")}catch(e){Ks("Failed to send ping:",e),this.resolveProbe(!1)}else this.resolveProbe(!1)}extractMessageText(e){if("string"==typeof e)return e;if(e instanceof ArrayBuffer){const t=new Uint8Array(e);return(e=>{for(const t of e)if(32!==t&&9!==t&&10!==t&&13!==t)return 123===t;return!1})(t)?qd?.decode(t)??Hs(t):null}return null}parseJson(e){try{return JSON.parse(e)}catch{return null}}static isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}static readString(e){return"string"==typeof e?e:void 0}resetTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=setTimeout(()=>{Vs("Heartbeat timeout"),this.onTimeoutCallback&&this.onTimeoutCallback()},this.config.timeout)}markAlive(){this.lastPongTime=Date.now(),this.resetTimeout(),this.resolveProbe(!0)}getLastPongTime(){return this.lastPongTime}async probeOnce(e,t){try{if(e.readyState!==ln)return!1;this.attachWebSocket(e);const r=t??this.config.timeout;return await new Promise(e=>{const t=setTimeout(()=>{this.removeProbeResolver(e),e(!1)},r);this.probeResolvers.push(r=>{clearTimeout(t),e(r)}),this.sendPingInternal()})}catch(r){return Vs("Heartbeat probe failed",r),!1}}attachWebSocket(e){this.websocket!==e&&(this.messageDisposer?.(),this.websocket=e,this.messageDisposer=e.onMessage(e=>{this.handlePong(e)}))}resolveProbe(e){if(0===this.probeResolvers.length)return;const t=[...this.probeResolvers];this.probeResolvers=[];for(const r of t)r(e)}removeProbeResolver(e){this.probeResolvers=this.probeResolvers.filter(t=>t!==e)}}let Vd=null;function Kd(){return Vd||(Vd=rc()),Vd}const zd="websdk2:device-info",Hd="webim",Wd="web",Jd=e=>{const t=Date.now(),r=e.deviceId,s=e.customOSPlatform,n=void 0!==s?e.customDeviceName:void 0,i=fn().localStorage,o=()=>{if(!i)return null;try{const t=i.getItem(zd);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},a=e=>{if(i)try{i.setItem(zd,JSON.stringify(e))}catch{}},c=e=>void 0===s?e:{deviceId:`custom${s}_${e.deviceUuid}`,deviceName:n??r,deviceUuid:e.deviceUuid};if(e.useFixedDeviceId){const e=o();if(e)return c(e);if(r===Hd){const e=`${Wd}_${t}`,s=c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e});return a(s),s}if(void 0!==s){const e=c({deviceId:`webim_${Wd}_${r}`,deviceName:r,deviceUuid:`${Wd}_${t}`});return a(e),e}const n={deviceId:`webim_${Wd}_${r}`,deviceName:`webim_${Wd}_${r}`,deviceUuid:`webim_${Wd}_${r}`};return a(n),n}if(r===Hd){const e=`random_${Wd}_${t}`;return c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e})}if(void 0!==s){return c({deviceId:`webim_${Wd}_${r}`,deviceName:r,deviceUuid:`random_${Wd}_${t}`})}return{deviceId:`webim_${Wd}_${r}`,deviceName:`webim_${Wd}_${r}`,deviceUuid:`webim_${Wd}_${r}`}},Qd=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),Zd=e=>{if(/^\d+$/.test(e))return e;const t=Dn.fromString("1099511628211",!0);let r=Dn.fromString("1469598103934665603",!0);for(let s=0;s<e.length;s+=1)r=r.xor(Dn.fromInt(e.charCodeAt(s),!0)).multiply(t).toUnsigned();return r.isZero()?"1":r.toString()},Yd=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 Dn(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},Xd=e=>{const t=[];for(const[r,s]of Object.entries(e))if(void 0!==s)if("boolean"!=typeof s)if("number"!=typeof s)if("string"!=typeof s)try{t.push({key:r,type:kr,stringValue:JSON.stringify(s)})}catch{t.push({key:r,type:Lr,stringValue:Object.prototype.toString.call(s)})}else t.push({key:r,type:Lr,stringValue:s});else Number.isInteger(s)?t.push({key:r,type:Ar,varintValue:s}):t.push({key:r,type:Ur,doubleValue:s});else t.push({key:r,type:Rr,varintValue:s?1:0});return t},eu=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 s="number"==typeof r.type?r.type:Lr;if(s!==Rr)if(s!==Ar&&s!==Nr&&s!==Or)if(s!==Mr)if(s!==Ur){if(s!==kr)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},tu=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,ru="X-Request-Id",su=new Set(["mute"]),nu={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext",mute:"muteAllMembers"},iu=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},ou=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},au=(e,t)=>{const r=e?.map(e=>iu(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},cu=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=ou(t);if(!s)return;const n=s.muteExpire??s.mute_expire??s.expire??s.expired??s.expireAt??s.expiredAt,i=Number(n);return Number.isFinite(i)&&i>0?i:void 0},du=e=>{const t=ou(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=nu[s];if(!e)continue;let t=n;if(su.has(s))t=!0===n||"true"===n;else if("max_users"===s){const e=Number(n);t=Number.isFinite(e)?e:void 0}void 0!==t&&(r[e]=t)}return Object.keys(r).length>0?r:void 0},uu=e=>{const t=ou(e);if(!t)return{attributes:{},keyList:[]};const r=t.result&&"object"==typeof t.result&&!Array.isArray(t.result)?t.result:{},s=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},n=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[];return{attributes:Object.fromEntries(n.map(e=>[e,s[e]]).filter(e=>"string"==typeof e[1])),keyList:n,from:iu(t.operator)??iu(t.username)}},lu=(e,t)=>({eventName:e,payload:t}),hu=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},r=iu(e.from?.name),s=(n=e.to,iu(n?.[0]?.name));var n;switch(e.operation){case 1:return lu(qe,t);case 10:return lu(Ve,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:s??r});case 17:return lu($e,{...t,memberIds:au(e.members,r),ext:e.ext??e.eventExt});case 18:return lu(je,{...t,memberIds:au(e.members,r)});case 20:return lu(Ye,{...t,oldOwnerId:r,newOwnerId:s});case 21:return lu(Qe,{...t,adminId:s??r});case 22:return lu(Ze,{...t,adminId:s??r});case 23:{const r=(e=>{const t=ou(e),r=t?.user_mute_time;if(!r||"object"!=typeof r||Array.isArray(r))return null;const s={};for(const[n,i]of Object.entries(r)){const e=Number(i);n&&Number.isFinite(e)&&(s[n]=e)}return Object.keys(s).length>0?s:null})(e.ext??e.eventExt),n=r?Object.keys(r):au(e.members,s),i=46388736e5;return lu(Ke,{...t,userIds:n,muteMembers:r??Object.fromEntries(n.map(e=>[e,i])),muteExpire:cu(e.reason,e.eventExt)??i})}case 24:return lu(ze,{...t,userIds:au(e.members,s)});case 25:return lu(Xe,{...t,announcement:e.reason??""});case 26:return lu(Xe,{...t,announcement:""});case 29:return lu(He,{...t,userIds:au(e.members,s)});case 30:return lu(We,{...t,userIds:au(e.members,s)});case 31:return lu(Je,{...t,isMuted:!0});case 32:return lu(Je,{...t,isMuted:!1});case 14:return lu(et,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:du(e.eventExt)});case 43:{const s=uu(e.eventExt);return lu(rt,{...t,attributes:s.attributes,from:s.from??r})}case 44:{const s=uu(e.eventExt);return lu(st,{...t,keyList:s.keyList,from:s.from??r})}default:return null}},pu=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),mu=(e,t)=>{if(!e)return t;try{return JSON.parse(e)}catch{return t}},fu=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],gu=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),yu=e=>({userId:e}),vu=(e,t,r)=>{const s={userId:r};for(const n of fu){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},Iu=async(e,t)=>{const r=(e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,gu(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,t)}for(const o of r)s.has(o)||s.set(o,yu(o));return s},bu=e=>pu(e)?e:null,_u=e=>{if("string"==typeof e)return e},Tu=e=>{const t=_u(e)?.trim();return t||void 0},Cu=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isFinite(t)?t:void 0}},Su=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},Eu=e=>{const t=bu(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},wu=e=>{const t=bu(e);return t?bu(t.data)?t.data:t:null},Ru=(e,t)=>{const r=bu(e),s=r&&bu(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return Cu(n[0])},Au=(e,t)=>{const r=(e=>{const t=bu(e);return t?Cu(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},Nu=e=>Tu(e.groupId)??Tu(e.groupid)??Tu(e.id)??"",Ou=e=>_u(e.name)??_u(e.groupname)??_u(e.groupName)??"",Mu=e=>{const t=Eu(e),r=bu(t[0])??wu(e)??{},s=(e=>{const t=bu(e);if(!t)return null;const r=Nu(t);return r?{groupId:r,name:Ou(t),description:_u(t.description),memberCount:Cu(t.memberCount)??Cu(t.affiliations_count),public:Su(t.public),joinApprovalRequired:Su(t.joinApprovalRequired)??Su(t.approval)??Su(t.membersonly)??Su(t.members_only),allowInvites:Su(t.allowInvites)??Su(t.allowinvites)??Su(t.allow_user_invites),maxMembers:Cu(t.maxMembers)??Cu(t.maxusers),role:Tu(t.role)??Tu(t.permission),disabled:Su(t.disabled)}:null})(r)??{groupId:Nu(r),name:Ou(r)},n=Tu(r.owner)??Tu(r.admin)??Tu(r.member),i=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>bu(e)).filter(e=>null!==e).map(e=>Cu(e.joined_time)).find(e=>void 0!==e);return{...s,owner:n?yu(n):void 0,inviteNeedConfirm:Su(r.inviteNeedConfirm)??Su(r.invite_need_confirm),muteAllMembers:Su(r.mute),ext:_u(r.ext)??_u(r.custom),createdAt:Cu(r.createdAt)??Cu(r.created),joinedAt:i,avatarUrl:_u(r.avatar),messageBlocked:Su(r.messageBlocked)??Su(r.isMessageBlocked)??Su(r.shieldgroup)}},Uu=e=>yu(e),Lu=e=>Eu(e).map(e=>Tu(e)).filter(e=>Boolean(e)).map(e=>Uu(e)),ku=e=>{const t=bu(e);if(!t)return null;const r=Tu(t.fileId)??Tu(t.file_id);if(!r)return null;const s=_u(t.fileName)??_u(t.file_name)??r,n=Tu(t.fileOwner)??Tu(t.file_owner);return{fileId:r,fileName:s,fileOwner:n?Uu(n):void 0,fileSize:Cu(t.fileSize)??Cu(t.file_size),createdAt:Cu(t.createdAt)??Cu(t.created)}},Du=new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),Pu={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},xu=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Fu=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Bu=(e,t)=>{const r=e?.map(e=>xu(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},Gu=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=Fu(t);if(!s)return;const n=s.muteExpire??s.mute_expire??s.expire??s.expired??s.expireAt??s.expiredAt,i=Number(n);return Number.isFinite(i)&&i>0?i:void 0},qu=e=>{const t=Fu(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=Pu[s];if(!e)continue;let t=n;if(Du.has(s))t=!0===n||"true"===n;else if("max_users"===s){const e=Number(n);t=Number.isFinite(e)?e:void 0}void 0!==t&&(r[e]=t)}return Object.keys(r).length>0?r:void 0},$u=(e,t)=>{const r=Fu(t)??Fu(e);return ku(r??void 0)??void 0},ju=(e,t)=>{const r=Fu(t)??Fu(e);return xu(r?.fileId)??xu(r?.file_id)??xu(e)??""},Vu=(e,t)=>({eventName:e,payload:t}),Ku=e=>{const t={groupId:e.groupId,groupName:e.groupName},r=xu(e.from?.name),s=(n=e.to,xu(n?.[0]?.name));var n;switch(e.operation){case 4:return Vu(X,{...t,applicantId:r,reason:e.reason});case 5:return Vu(ee,{...t,accepterId:r});case 6:return Vu(te,{...t,declinerId:r,applicantId:s,reason:e.reason});case 7:return Vu(Y,{...t,inviterId:r,reason:e.reason});case 8:return Vu(re,{...t,inviteeId:r,reason:e.reason});case 9:return Vu(se,{...t,inviteeId:r,reason:e.reason});case 10:return Vu(ne,t);case 1:return Vu(ie,t);case 19:return Vu(oe,{...t,inviterId:r,reason:e.reason});case 23:{const r=(e=>{const t=Fu(e),r=t?.user_mute_time;if(!r||"object"!=typeof r||Array.isArray(r))return null;const s={};for(const[n,i]of Object.entries(r)){const e=xu(n),t=Number(i);e&&Number.isFinite(t)&&t>0&&(s[e]=t)}return Object.keys(s).length>0?s:null})(e.ext),n=r?Object.keys(r):Bu(e.members,s);return Vu(ae,{...t,userIds:n,muteExpire:n.map(e=>r?.[e]).find(e=>void 0!==e)??Gu(e.reason,e.eventExt)})}case 24:return Vu(ce,{...t,userIds:Bu(e.members,s)});case 29:return Vu(de,{...t,userIds:Bu(e.members,s)});case 30:return Vu(ue,{...t,userIds:Bu(e.members,s)});case 31:return Vu(le,{...t,isMuted:!0});case 32:return Vu(le,{...t,isMuted:!1});case 21:return Vu(he,{...t,administratorId:s??r});case 22:return Vu(pe,{...t,administratorId:s??r});case 20:return Vu(me,{...t,oldOwnerId:r,newOwnerId:s});case 17:{const s=Bu(e.members,r);return Vu(fe,{...t,memberIds:s})}case 18:{const s=Bu(e.members,r);return Vu(ge,{...t,memberIds:s})}case 25:return Vu(ye,{...t,announcement:e.reason??""});case 26:return Vu(ye,{...t,announcement:""});case 27:return Vu(ve,{...t,sharedFile:$u(e.reason,e.eventExt)});case 28:return Vu(Ie,{...t,fileId:ju(e.reason,e.eventExt)});case 14:return Vu(be,{...t,shouldFetchGroupDetail:!0,groupPatch:qu(e.eventExt)});case 41:return Vu(_e,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return Vu(_e,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const s=(e=>{const t=Fu(e);if(!t)return{attribute:{}};const r=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},s=Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]));return{userId:xu(t.username),attribute:s}})(e.eventExt);return Vu(Te,{...t,userId:s.userId,attribute:s.attribute,from:r,source:e.source??"direct"})}default:return null}},zu=new WeakMap,Hu=(e,t)=>{zu.set(e,t)},Wu=e=>zu.get(e)??null,Ju=(e,t)=>{const r=Wu(e);r&&Hu(t,r)},Qu=new WeakMap,Zu=e=>Qu.get(e),Yu=new WeakMap,Xu=e=>Yu.get(e),el=(e,t)=>{const r=Yu.get(e);r&&Yu.set(t,r)},tl="singleChat",rl="groupChat",sl=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},nl=e=>{if("number"==typeof e)return Number.isFinite(e)?e:void 0;if("string"==typeof e&&e.trim().length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}},il=e=>{if(!Array.isArray(e))return;const t=e.map(e=>sl(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},ol=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),al=(...e)=>{for(const t of e){const e=sl(t);if(e)return e}},cl=(e,t)=>Boolean(e&&t&&e===t),dl=(e,t,r)=>Boolean(e&&e===r.userId&&t&&r.clientResource&&t!==r.clientResource),ul=(e,t,r)=>{const s=il(e);if(s&&s.length>0)return s;const n=(t??[]).map(e=>sl(e.name)).filter(e=>"string"==typeof e);if(n.length>0)return n;const i=sl(r?.name);return i?[i]:[]},ll=e=>{const t=nl(e);if(void 0!==t)return t;if("string"==typeof e){const t=e.match(/(\d+)/);if(t){const e=Number(t[1]);return Number.isFinite(e)?e:void 0}}},hl=(e,t)=>{const r=al(e.to?.[0]?.clientResource);if(1!==e.to?.length||sl(e.to[0]?.name)!==t.userId||!dl(t.userId,r,t))return null;const s=(n=e.from,sl(n?.name)??"");var n;if(!s)return Vs("Discarded MultiDevice contact event without target user",{operation:e.operation}),null;const i=(e=>{switch(e){case 3:return"CONTACT_REMOVE";case 4:case 8:return"CONTACT_ACCEPT";case 5:case 9:return"CONTACT_DECLINE";case 6:return"CONTACT_BAN";case 7:return"CONTACT_ALLOW";default:return Vs("Discarded unknown MultiDevice contact operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===i?null:{category:"contact",operation:i,targetUserId:s,rosterVersion:e.rosterVersion,ext:e.ext,deviceId:r,timestamp:e.timestamp,raw:e.raw}},pl=(e,t)=>{if(!e.groupId)return Vs("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const r=al(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!dl(sl(e.from?.name),r,t))return null;const s=(e=>{switch(e){case 0:return"GROUP_CREATE";case 1:return"GROUP_DESTROY";case 2:return"GROUP_JOIN";case 3:return"GROUP_LEAVE";case 4:return"GROUP_APPLY";case 5:return"GROUP_APPLY_ACCEPT";case 6:return"GROUP_APPLY_DECLINE";case 7:return"GROUP_INVITE";case 8:return"GROUP_INVITE_ACCEPT";case 9:return"GROUP_INVITE_DECLINE";case 10:return"GROUP_KICK";case 12:return"GROUP_BAN";case 13:return"GROUP_ALLOW";case 15:return"GROUP_BLOCK";case 16:return"GROUP_UNBLOCK";case 20:return"GROUP_ASSIGN_OWNER";case 21:return"GROUP_ADD_ADMIN";case 22:return"GROUP_REMOVE_ADMIN";case 23:return"GROUP_ADD_MUTE";case 24:return"GROUP_REMOVE_MUTE";case 29:return"GROUP_ADD_USER_WHITE_LIST";case 30:return"GROUP_REMOVE_USER_WHITE_LIST";case 31:return"GROUP_ALL_BAN";case 32:return"GROUP_REMOVE_ALL_BAN";case 45:return"GROUP_MEMBER_METADATA_CHANGED";case 14:return"GROUP_UPDATED";default:return Vs("Discarded unknown MultiDevice group operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===s)return null;const n=ul(e.members,e.to,e.from);return{category:"group",operation:s,groupId:e.groupId,userIds:n.length>0?n:void 0,operatorId:sl(e.from?.name),groupName:e.groupName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},ml=(e,t)=>{if(!e.threadId)return Vs("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const r=al(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!dl(sl(e.from?.name),r,t))return null;const s=(e=>{switch(e){case 33:return"THREAD_CREATE";case 35:return"THREAD_JOIN";case 38:return"THREAD_UPDATE";case 36:return"THREAD_LEAVE";case 34:return"THREAD_DESTROY";case 37:return"THREAD_KICK";default:return Vs("Discarded unknown MultiDevice thread operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===s)return null;const n=ul(e.members,e.to,e.from);return{category:"thread",operation:s,threadId:e.threadId,parentId:e.parentId,userIds:n.length>0?n:void 0,operatorId:sl(e.from?.name),threadName:e.threadName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},fl=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const r=al(e.res,e.raw?.resource,e.raw?.clientResource);if(cl(r,t.clientResource))return js("Discarded same-device MultiDevice conversation echo",{operation:e.operation,conversationId:e.id}),null;const s="chat"===(n=e.type)||"singleChat"===n?tl:rl;var n;const i=sl(e.id)??(s===tl?sl(e.from):void 0);if(!i)return Vs("Discarded MultiDevice conversation event without conversationId",{operation:e.operation}),null;const o=(e=>{switch(e){case"del":return"CONVERSATION_DELETED";case"top":return"CONVERSATION_PINNED";case"not_top":return"CONVERSATION_UNPINNED";case"mark":case"mark_delete":return"CONVERSATION_MARK";case"setSilentModeForConversation":case"removeSilentModeForConversation":return"CONVERSATION_MUTE_INFO_CHANGED";default:return Vs("Discarded unknown MultiDevice conversation operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===o?null:{category:"conversation",operation:o,conversationId:i,conversationType:s,mark:"mark"===e.operation||"mark_delete"===e.operation?ll(e.ext):void 0,operatorId:sl(e.from),deviceId:r,timestamp:nl(e.ts),raw:e.raw}},gl=(e,t)=>{const r=al(e.resource,e.raw?.resource,e.raw?.clientResource);if(cl(r,t.clientResource))return js("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const s=sl(e.to);if(!s)return Vs("Discarded MultiDevice roaming delete event without conversationId",{}),null;const n=sl(e.lastMsgId),i=il(e.msgIdList)??(n?[n]:void 0),o=nl(e.deleteTime);if(!i&&void 0===o)return Vs("Discarded MultiDevice roaming delete event without messageIds or beforeTimestamp",{conversationId:s}),null;const a=(e=>e&&"deleteRoaming"!==e&&"MESSAGE_REMOVED"!==e?(Vs("Discarded unknown MultiDevice message-removed operation",{operation:e}),"UNKNOWN"):"MESSAGE_REMOVED")(e.messageRoamingType);return"UNKNOWN"===a?null:{category:"messageRemoved",operation:a,conversationId:s,conversationType:"groupchat"===e.chatType||"groupChat"===e.chatType?rl:tl,messageIds:i,beforeTimestamp:o,deviceId:r,raw:e.raw}},yl=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}},vl=2147483647,Il=e=>{const t=Number(e);if(!Number.isFinite(t)||t<=0)return;const r=Math.floor(t);return r<=0||r>vl?void 0:r},bl=e=>{if("number"!=typeof e||!Number.isFinite(e)||e<=0)return;const t=e>vl?Math.floor(e/1e3):Math.floor(e);return Il(t)};var _l=4096,Tl=65547,Cl=15,Sl=2113929216,El=65536,wl=65536,Rl=10485760,Al={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},Nl={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function Ol(e){if(!(e>0))return wl;if(e<=wl)return wl;if(e>1073741823)return e;for(var t=wl;t<e;)t*=2;return t}var Ml={byU16:0,byU32:1},Ul=0,Ll=1,kl=2,Dl=0,Pl=1;function xl(e,t){return e[t]|e[t+1]<<8}function Fl(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function Bl(e,t,r){e[t]=255&r,e[t+1]=r>>>8&255}var Gl="fast";function ql(e){return 2654435761*(e>>>0)>>>20&4095}function $l(e){return 2654435761*(e>>>0)>>>19&8191}function jl(e,t,r){if("fast"===Gl){var s=Fl(e,t);return r===Ml.byU16?$l(s):ql(s)}throw new Error("Unsupported hash strategy: "+Gl)}function Vl(e,t,r,s,n){r[t]=e-n}function Kl(e,t,r,s,n){Vl(t,jl(e,t,s),r,0,n)}function zl(e,t,r,s){return t[e]+s}function Hl(e,t,r,s,n){return zl(jl(e,t,s),r,0,n)}function Wl(e,t,r,s){for(var n=t;t<s-3;){if(Fl(e,t)!==Fl(e,r)){for(;t<s&&e[t]===e[r];)t++,r++;return t-n}t+=4,r+=4}for(;t<s&&e[t]===e[r];)t++,r++;return t-n}function Jl(e,t,r,s,n,i,o,a,c,d){var u,l,h,p=e.hashTable,m=s,f=m-e.dictSize,g=e.dictionary,y=e.dictionaryStart,v=y+e.dictSize,I=e.dictSize>0?v-s:0,b=s,_=s+n,T=_-12,C=_-5,S=0,E=i>0?i:r.length,w=0;if(n>Sl)return 0;switch(c){case Ul:default:u=s,l=s;break;case Ll:u=s-e.currentOffset,l=s-e.dictSize;break;case kl:u=s-e.currentOffset,l=s}if(a===Ml.byU16&&n>=Tl)return 0;if(n<13)return Yl(t,r,b,_,S,E,o);Kl(t,m,p,a,u),h=jl(t,++m,a);e:for(;;){var R,A,N=m,O=1,M=64;do{var U=h;if(m=N,N+=O,O=M++>>>6,N>T)return Yl(t,r,b,_,S,E,o);R=zl(U,p,0,u),c===kl&&(R<s?(w=I,l=y):(w=0,l=s)),h=jl(t,N,a),Vl(m,U,p,0,u)}while(d===Pl&&R<f||a!==Ml.byU16&&R+65535<m||!Ql(t,g,m,R,w,c,s));for(;m>b&&R+w>l;){var L=R+w-1;if(t[m-1]!==(c===kl&&R<s?g[L-y+e.dictionaryStart]:t[L]))break;m--,R--}var k=m-b;if(A=S++,o&&S+k+8+Math.floor(k/255)>E)return 0;if(k>=Cl){var D=k-Cl;for(r[A]=240;D>=255;)r[S++]=255,D-=255;r[S++]=D}else r[A]=k<<4;if(k>=16&&r.set&&t.subarray)r.set(t.subarray(b,b+k),S),S+=k;else for(var P=0;P<k;P++)r[S++]=t[b+P];t:for(;;){var x;if(Bl(r,S,m-R),S+=2,c===kl&&R<s){var F=m+(v-(R+w));if(F>C&&(F=C),(m+=4+(x=Zl(t,g,m+4,R+w+4-y+e.dictionaryStart,F,v-y)))===F&&F<C){var B=Wl(t,m,s,C);x+=B,m+=B}}else m+=4+(x=Wl(t,m+4,R+4,C));if(o&&S+6+(x>>>8)>E)return 0;if(x>=15){for(r[A]+=15,x-=15;x>=510;)r[S++]=255,r[S++]=255,x-=510;x>=255&&(x-=255,r[S++]=255),r[S++]=x}else r[A]+=x;if(b=m,m>T)break e;if(Kl(t,m-2,p,a,u),R=Hl(t,m,p,a,u),c===kl&&(R<s?(w=I,l=y):(w=0,l=s)),Kl(t,m,p,a,u),!((d!==Pl||R>=f)&&R+65535>=m&&Ql(t,g,m,R,w,c,s)))break t;r[A=S++]=0}h=jl(t,++m,a)}return Yl(t,r,b,_,S,E,o)}function Ql(e,t,r,s,n,i,o){var a,c=Fl(e,r);i===kl&&s+n<o?a=Fl(t,s+n):a=Fl(e,s+n);return c===a}function Zl(e,t,r,s,n,i,o){for(var a=r;s<i&&r<n&&t[s]===e[r];)s++,r++;return r-a}function Yl(e,t,r,s,n,i,o){var a=s-r;if(o&&n+a+1+Math.floor((a+255-Cl)/255)>i)return 0;if(a>=Cl){for(t[n++]=240,a-=Cl;a>=255;)t[n++]=255,a-=255;t[n++]=a}else t[n++]=a<<4;var c=r,d=s,u=d-c;if(u>=16&&t.set&&e.subarray)t.set(e.subarray(c,d),n),n+=u;else for(var l=c;l<d;l++)t[n++]=e[l];return n}function Xl(e,t,r,s){var n,i=0;if(s&&t.ip>=r)return-1;do{if(i+=n=e[t.ip++],t.ip>r)return-1;if(i>2147483647)return-1}while(255===n);return i}function eh(e,t,r,s,n,i,o,a,c,d,u,l,h){if(null==e)return-1;if(i<0)return-1;var p=r,m=r+s,f=n,g=n+i,y=u-h,v=l+h,I=h<65536;if(0===i)return 1===s&&0===e[p]?0:-1;if(0===s)return-1;for(;;){var b,_,T,C;if(p>=m)return-(p-r)-1;if((_=(b=e[p++])>>>4)===Cl){var S=Xl(e,R={ip:p},m-Cl,!0);if(p=R.ip,-1===S)return-(p-r)-1;if(f+(_+=S)<f)return-(p-r)-1;if(p+_<p)return-(p-r)-1}if(T=f+_,o&&(T>g-12||p+_>m-8)||!o&&T>g-8){if(!o&&T!==g)return-(p-r)-1;if(o&&(p+_!==m||T>g))return-(p-r)-1;if(_>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+_),f);else for(var E=0;E<_;E++)t[f+E]=e[p+E];p+=_,f+=_;break}if(_>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+_),f);else for(E=0;E<_;E++)t[f+E]=e[p+E];if(f=T,(p+=_)+2>m)return-(p-r)-1;var w=xl(e,p);if(p+=2,C=T-w,I&&C+h<u)return-(p-r)-1;if(0===w)return-(p-r)-1;if(15===(_=15&b)){var R;S=Xl(e,R={ip:p},m-5+1,!1);if(p=R.ip,-1===S)return-(p-r)-1;if(f+(_+=S)<f)return-(p-r)-1}if(_+=4,d===kl&&C<u){if(f+_>g-5)return-(p-r)-1;if(_<=u-C){var A=v-(u-C);for(E=0;E<_;E++)t[f+E]=t[A+E];f+=_}else{var N=u-C;for(A=v-N,E=0;E<N;E++)t[f+E]=t[A+E];var O=_-N;if(O>(f+=N)-u)for(var M=u,U=f+O;f<U;)t[f++]=t[M++];else{for(E=0;E<O;E++)t[f+E]=t[u+E];f+=O}}}else{if(C<y)return-(p-r)-1;if(T=f+_,f-C<8)for(t[f]=t[C],t[f+1]=t[C+1],t[f+2]=t[C+2],t[f+3]=t[C+3],f+=4,C+=4;f<T;)t[f++]=t[C++];else for(;f<T;)t[f++]=t[C++]}}return o?f-n:p-r}function th(){return{hashTable:new Uint32Array(_l),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function rh(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function sh(e,t,r,s,n,i,o,a){s=s||0;var c=e.dictionaryStart+e.dictSize,d=s;if(e.initCheck)return 0;e.dictSize>0&&d>c&&(d=c),function(e){if(e.currentOffset>2147483648){for(var t=e.currentOffset-65536,r=e.dictionaryStart+e.dictSize,s=0;s<e.hashTable.length;s++)e.hashTable[s]<t?e.hashTable[s]=0:e.hashTable[s]-=t;e.currentOffset=65536,e.dictSize>65536&&(e.dictSize=65536),e.dictionaryStart=r-e.dictSize}}(e);var u,l=s+n;e.dictionary&&l>e.dictionaryStart&&l<c&&(e.dictSize=c-l,e.dictSize>65536&&(e.dictSize=65536),e.dictSize<4&&(e.dictSize=0),e.dictionaryStart=c-e.dictSize);var h=e.dictSize<65536&&e.dictSize<e.currentOffset?Pl:Dl;return e.dictionary&&c===s?(u=Jl(e,t,r,s,n,o||0,a||!1,Ml.byU32,Ll,h),e.dictSize+=n,e.currentOffset+=n,u):(u=Jl(e,t,r,s,n,o||0,a||!1,Ml.byU32,kl,h),e.dictionary=t,e.dictionaryStart=s,e.dictSize=n,e.currentOffset+=n,u)}function nh(e,t,r,s){var n=e.dictionaryStart+e.dictSize;s>65536&&(s=65536),s>e.dictSize&&(s=e.dictSize);var i=n-s;if(t.set&&e.dictionary.subarray)t.set(e.dictionary.subarray(i,i+s),r);else for(var o=0;o<s;o++)t[r+o]=e.dictionary[i+o];return e.dictionary=t,e.dictionaryStart=r,e.dictSize=s,s}function ih(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function oh(e,t,r,s){return e.prefixSize=s,e.prefixEnd=r+s,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function ah(e,t,r,s,n,i,o){var a;if(e.prefixEnd===i){if((a=eh(t,r,s,n,i,o,!0,0,0,kl,e.prefixEnd-e.prefixSize,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize+=a,e.prefixEnd+=a}else{if(e.extDictSize=e.prefixSize,e.extDictStart=e.prefixEnd-e.extDictSize,(a=eh(t,r,s,n,i,o,!0,0,0,kl,i,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=i+a}return a}function ch(e){var t=(e=e||{}).minWorkArea||wl,r=e.maxWorkArea||Rl,s=e.shrinkThreshold||t;t<wl&&(t=wl),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=El+t,this.maxBufferSize=El+r,this.shrinkThreshold=El+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Al.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=th()}function dh(e){var t=(e=e||{}).minWorkArea||wl,r=e.maxWorkArea||Rl,s=e.shrinkThreshold||t;t<wl&&(t=wl),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=El+t,this.maxBufferSize=El+r,this.shrinkThreshold=El+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Al.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}ch.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<El?this.offset:El,n=this.offset>El?this.offset-El:0;t.set(this.ringBuffer.subarray(n,n+s),0),nh(this.stream,t,0,s),r=s}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},ch.prototype.compress=function(e,t){var r=e.length;if(r<=0)return Nl.PARAM_ERROR;if(r>this.maxBufferSize-El)return Nl.PARAM_ERROR;if(r>this.ringBufferSize-El){var s=Ol(r),n=El+s;if(n>this.maxBufferSize&&(n=this.maxBufferSize),!this._resizeBuffer(n))return Nl.BUFFER_RESIZE_FAILED}this.offset+r>this.ringBufferSize&&(nh(this.stream,this.ringBuffer,0,El),this.offset=El);var i=this.offset;this.ringBuffer.set(e,i);var o=sh(this.stream,this.ringBuffer,t,i,r,0,t.length,!0);return o<=0?Nl.COMPRESS_FAILED:(this.offset+=r,this._tryAutoShrink(),o)},ch.prototype.reset=function(){this.offset=0,rh(this.stream)},ch.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},ch.prototype._tryAutoShrink=function(){this.shrinkMode!==Al.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Al.AUTO_IMMEDIATE||this.shrinkMode===Al.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},ch.prototype.getWorkArea=function(){return this.ringBufferSize-El},ch.prototype.getRingBufferSize=function(){return this.ringBufferSize},ch.prototype.getBaseBufferSize=function(){return this.minBufferSize},ch.prototype.getMaxBufferSize=function(){return this.maxBufferSize},ch.prototype.getCurrentOffset=function(){return this.offset},ch.prototype.getShrinkMode=function(){return this.shrinkMode},ch.prototype.setShrinkMode=function(e){this.shrinkMode=e},ch.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},ch.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-El,r=this.maxBufferSize-El;if(e<t||e>r)return Nl.PARAM_ERROR;this.shrinkThreshold=El+e},dh.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<El?this.offset:El,n=this.offset>El?this.offset-El:0;t.set(this.ringBuffer.subarray(n,n+s),0),r=s,oh(this.streamDecode,0,0,s)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},dh.prototype.decompress=function(e,t,r){var s=e.length;if(s<=0||r<=0)return Nl.PARAM_ERROR;if(r>this.maxBufferSize-El)return Nl.PARAM_ERROR;if(r>this.ringBufferSize-El){var n=Ol(r),i=El+n;if(i>this.maxBufferSize&&(i=this.maxBufferSize),!this._resizeBuffer(i))return Nl.BUFFER_RESIZE_FAILED}if(this.offset+r>this.ringBufferSize){var o=this.offset-El;o>0&&this.ringBuffer.set(this.ringBuffer.subarray(o,o+El),0),oh(this.streamDecode,this.ringBuffer,0,El),this.offset=El}var a=ah(this.streamDecode,e,this.ringBuffer,0,s,this.offset,r);return a<=0?Nl.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},dh.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},dh.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},dh.prototype._tryAutoShrink=function(){this.shrinkMode!==Al.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Al.AUTO_IMMEDIATE||this.shrinkMode===Al.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},dh.prototype.getWorkArea=function(){return this.ringBufferSize-El},dh.prototype.getRingBufferSize=function(){return this.ringBufferSize},dh.prototype.getBaseBufferSize=function(){return this.minBufferSize},dh.prototype.getMaxBufferSize=function(){return this.maxBufferSize},dh.prototype.getCurrentOffset=function(){return this.offset},dh.prototype.getShrinkMode=function(){return this.shrinkMode},dh.prototype.setShrinkMode=function(e){this.shrinkMode=e},dh.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},dh.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-El,r=this.maxBufferSize-El;if(e<t||e>r)return Nl.PARAM_ERROR;this.shrinkThreshold=El+e};const uh={LZ4_MAX_INPUT_SIZE:Sl,BLOCK_MAX_SIZE:65536,DICT_SIZE:El,DEFAULT_WORK_AREA:wl,DEFAULT_MAX_WORK:Rl,SHRINK_MODE:Al,LZ4_ERROR:Nl,alignToPowerOf2:Ol,calcDefaultBufferSize:function(){return 131072},calcDefaultMaxBufferSize:function(){return 10551296},setHashStrategy:function(e){if("fast"!==e&&"compatible"!==e)throw new Error("Invalid hash strategy: "+e+'. Use "fast" or "compatible".');Gl=e},getHashStrategy:function(){return Gl},compress:function(e,t,r,s,n){if(null==e)return 0;if(null==t)return 0;if(r=r||0,s=void 0===s?e.length:s,n=n||0,r<0||n<0)return 0;if(s<0)return 0;if(r+s>e.length)return 0;if(s>Sl)return 0;if(0===s)return t.length>n?(t[n]=0,1):0;var i=s<Tl?Ml.byU16:Ml.byU32;return Jl({hashTable:new Uint32Array(i===Ml.byU16?8192:_l),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,0,!1,i,Ul,Dl)},compressLimited:function(e,t,r,s,n,i){if(null==e)return 0;if(null==t)return 0;if(r=r||0,s=void 0===s?e.length:s,n=n||0,r<0||n<0)return 0;if(s<0||i<0)return 0;if(r+s>e.length)return 0;if(s>Sl)return 0;if(i<1)return 0;if(0===s)return t[n]=0,1;var o=s<Tl?Ml.byU16:Ml.byU32;return Jl({hashTable:new Uint32Array(o===Ml.byU16?8192:_l),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,i,!0,o,Ul,Dl)},compressBound:function(e){return e<0||e>Sl?0:e+Math.floor(e/255)+16},decompressSafe:function(e,t,r,s,n,i){return null==e||null==t?-1:(n=n||0,(r=r||0)<0||n<0||s<0||i<0||r+s>e.length||n+i>t.length?-1:eh(e,t,r,s,n,i,!0,0,0,Ul,n,null,0))},decompressFast:function(e,t,r,s,n){return eh(e,t,r=r||0,0,s=s||0,n,!1,0,0,Ll,s-65536,0,65536)},createStream:th,resetStream:rh,loadDict:function(e,t,r,s){if(e.initCheck&&rh(e),s<4)return e.dictionary=null,e.dictSize=0,0;s>65536&&(r=r+s-65536,s=65536);var n=r-e.currentOffset;e.dictionary=t,e.dictionaryStart=r,e.dictSize=s,e.currentOffset+=s;for(var i=r,o=r+s;i<=o-4;)Kl(t,i,e.hashTable,Ml.byU32,n),i+=3;return s},compressContinue:sh,saveDict:nh,createStreamDecode:ih,setStreamDecode:oh,decompressSafeContinue:ah,RingBufferEncoder:ch,RingBufferDecoder:dh,_hashU16:$l,_hashU32:ql,_TABLE_TYPE:Ml},lh=268435455,hh=new Uint32Array(256);let ph=!1;function mh(e){!function(){if(!ph){for(let e=0;e<256;e+=1){let t=e;for(let e=0;e<8;e+=1)t=1&t?3988292384^t>>>1:t>>>1;hh[e]=t>>>0}ph=!0}}();let t=4294967295;for(let r=0;r<e.length;r+=1){const s=e[r]??0;t=t>>>8^(hh[255&(t^255&s)]??0)}return(4294967295^t)>>>0}var fh=(e=>(e[e.NONE=-1]="NONE",e[e.UPLINK_ONLY=0]="UPLINK_ONLY",e[e.DOWNLINK_ONLY=1]="DOWNLINK_ONLY",e[e.BIDIRECTIONAL=2]="BIDIRECTIONAL",e))(fh||{});const gh=268435455;class yh{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:uh.DEFAULT_WORK_AREA,maxWorkArea:uh.DEFAULT_MAX_WORK,shrinkMode:uh.SHRINK_MODE.MANUAL};this.encoder=new uh.RingBufferEncoder(e),this.decoder=new uh.RingBufferDecoder(e)}compress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length>gh)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const r=uh.compressBound(t.length),s=new Uint8Array(r),n=this.encoder.compress(t,s);if(n<0)throw new Error(`LZ4 compression failed with error code: ${n}`);const i=s.subarray(0,n),o=function(e){if(e<0)throw new Error("encodeLength: Length must be non-negative");if(e>lh)throw new Error("encodeLength: Length exceeds maximum: 268435455");if(0===e)return new Uint8Array([0]);const t=[];let r=e;for(;r>0;){let e=127&r;r>>>=7,r>0&&(e|=128),t.push(e)}return new Uint8Array(t)}(t.length),a=mh(t),c=new Uint8Array(o.length+4+n);let d=0;c.set(o,d),d+=o.length;return new DataView(c.buffer).setUint32(d,a,!1),d+=4,c.set(i,d),c}decompress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length<5)throw new Error("Compressed data is too short: must contain at least length and CRC32");const r={offset:0},s=function(e,t){if(t.offset>=e.length)throw new Error("decodeLength: No data to decode: offset beyond data length");let r=0,s=0;for(;t.offset<e.length;){const n=e[t.offset]??0;if(t.offset+=1,r|=(127&n)<<s,!(128&n))return r>>>0;if(s+=7,s>=28)throw new Error("decodeLength: Invalid length encoding: exceeds 4 bytes")}throw new Error("decodeLength: Incomplete length encoding: missing terminator byte")}(t,r);if(s>gh)throw new Error(`Original size exceeds maximum allowed: ${s}`);if(t.length<r.offset+4)throw new Error("Compressed data is too short: missing CRC32 checksum");const n=new DataView(t.buffer,t.byteOffset+r.offset,4).getUint32(0,!1);r.offset+=4;const i=t.subarray(r.offset),o=new Uint8Array(s),a=this.decoder.decompress(i,o,s);if(a<0||a!==s)throw new Error(`LZ4 decompression failed: expected ${s}, got ${a}`);const c=mh(o);if(c!==n)throw new Error(`CRC32 checksum mismatch: expected ${n}, got ${c}`);return o}reset(){this.encoder.reset(),this.decoder.reset()}}const vh=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ih=(e,t)=>ka(e,t).finish();class bh{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=Jd({useFixedDeviceId:e.useFixedDeviceId??!0,deviceId:e.deviceId??"webim",customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform}),r=`${Date.now()}:`;return{appKey:e.appKey,userId:e.userId,token:e.token,domain:e.domain??"easemob.com",version:e.version??"4.11.0",uiKitVersion:e.uiKitVersion,osType:void 0!==e.customOSPlatform?5:e.osType??16,deviceId:t.deviceId,deviceName:t.deviceName,deviceUuid:t.deviceUuid,clientResource:t.deviceId,customOSPlatform:e.customOSPlatform,loginExtensionInfo:e.loginExtensionInfo,encryptType:[sr],compressType:[nr],sessionId:r,serviceId:e.serviceId}})(e),this.useReplacedMessageContents=e.useReplacedMessageContents??!1,this.useCustomAttachmentUpload=e.useCustomAttachmentUpload??!1}updateToken(e){this.context.token=e}updateResource(e){e&&(this.context.clientResource=e)}getContext(){return{...this.context}}encodeProvision(){const e=Kd(),t=e.lookupType("easemob.pb.Provision"),r=e.lookupType("easemob.pb.MSync"),s={osType:this.context.osType,version:this.context.uiKitVersion??this.context.version,compressType:[nr],encryptType:[sr],protocolCompressType:this.getRequestedCompressTypes(),deviceUuid:this.context.deviceUuid,deviceName:this.context.deviceName,resource:this.context.deviceId,actionVersion:"v6.0",authToken:`{"token":"$t$${this.context.token}"}`,sessionId:this.context.sessionId,...this.context.serviceId?{serviceId:this.context.serviceId}:{},...void 0!==this.context.customOSPlatform?{osCustomValue:this.context.customOSPlatform}:{},...this.context.loginExtensionInfo?{reason:this.context.loginExtensionInfo}:{}},n=Ih(t,s),i={version:0,guid:Qd({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),command:St,deviceId:0,encryptType:[sr],payload:n,traceId:tu()};return Ih(r,i)}encodeHeartbeat(){const e=Kd(),t=e.lookupType("easemob.pb.CommUnreadUL"),r=e.lookupType("easemob.pb.MSync"),s=Ih(t,{}),n={version:0,encryptType:[sr],command:Tt,payload:s,traceId:tu()};return Ih(r,n)}encodeStatisticRebuild(){const e=Kd(),t=e.lookupType("easemob.pb.StatisticsBody"),r=e.lookupType("easemob.pb.Meta"),s=e.lookupType("easemob.pb.CommSyncUL"),n=e.lookupType("easemob.pb.MSync"),i=Ih(t,{operation:0}),o=r.decode(new Uint8Array);o.id=Date.now(),o.ns=Jt,o.payload=i;const a=s.decode(new Uint8Array);a.meta=o;const c=Ih(s,a);return Ih(n,{version:0,encryptType:[sr],command:_t,payload:c,traceId:tu()})}decodeProvision(e){const t=Kd().lookupType("easemob.pb.Provision").decode(e),r=t.status??{},s="number"==typeof r.errorCode?r.errorCode:ar,n="string"==typeof r.reason?r.reason:void 0,i="string"==typeof t.resource?t.resource:void 0,o="string"==typeof t.authToken?t.authToken:void 0,a=Array.isArray(t.protocolCompressType)?t.protocolCompressType:void 0,c="number"==typeof t.protocolCompressDirection?t.protocolCompressDirection:void 0;return this.configureCompression(a,c),{ok:s===or,statusCode:s,reason:n,resource:i,authToken:o,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=Kd().lookupType("easemob.pb.Logout").decode(e),r=t.status&&"object"==typeof t.status?t.status:void 0;return{sessionId:"string"==typeof t.sessionId?t.sessionId:void 0,reason:"string"==typeof t.reason?t.reason:void 0,statusCode:"number"==typeof r?.errorCode?r.errorCode:void 0}}decodeSyncStatisticOperations(e){const t=Kd().lookupType("easemob.pb.CommSyncDL").decode(e),r=Array.isArray(t.metas)?t.metas:[],s=[];for(const n of r){const e=this.decodeStatisticMeta(n);e&&s.push(e)}return s}decodeMsync(e){const t=Kd().lookupType("easemob.pb.MSync").decode(e);return{command:"number"==typeof t.command?t.command:-1,payload:this.normalizeBinaryPayload(t.payload)}}normalizeBinaryPayload(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)?Uint8Array.from(e.filter(e=>"number"==typeof e)):new Uint8Array}decodeSync(e){const t=Kd(),r=t.lookupType("easemob.pb.CommSyncDL"),s=t.lookupType("easemob.pb.MessageBody"),n=r.decode(e);js("decodeSync commSyncDl",{hasMetas:Array.isArray(n.metas)});const i=Array.isArray(n.metas)?n.metas:[],o=this.decodeAck(n);o?.ok&&(o.chatRoomInfo=this.decodeChatRoomJoinInfo(i));const a=Yd(n.metaId),c=Yd(n.nextKey),d=n.queue??void 0,u="boolean"==typeof n.isLast?n.isLast:void 0,l=[],h=[];if(a&&"0"!==a){const e=this.useReplacedMessageContents?this.decodeReplacedMessage(i,s):void 0;for(const t of i){const e=this.decodeNotifyMeta(t);e.length>0&&h.push(...e)}return{ack:o,messages:l,notifies:h.length>0?h:void 0,metaId:a,queue:d,nextKey:c,isLast:u,replacedMessage:e}}for(const p of i){const e=this.decodeChatMeta(p,s);e&&l.push(e);const t=this.decodeChatActionMeta(p,s);t&&h.push(t);const r=this.decodeNotifyMeta(p);r.length>0&&h.push(...r)}return{ack:o,messages:l,notifies:h.length>0?h:void 0,metaId:a,queue:d,nextKey:c,isLast:u}}decodeReplacedMessage(e,t){for(const r of e){const e=this.decodeChatMeta(r,t);if(e)return e}}decodeChatMeta(e,t){if(!e||"object"!=typeof e)return null;const r=e,s=r.payload;let n=null;if(s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!n)return null;if(("number"==typeof r.ns?r.ns:void 0)!==Qt)return null;try{const e=t.decode(n);if(!e||"object"!=typeof e)return null;const s=e;return this.decodeMessage(r,s)}catch{return null}}decodeChatActionMeta(e,t){if(!e||"object"!=typeof e)return null;const r=e,s=r.payload;let n=null;if(s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!n)return null;if(("number"==typeof r.ns?r.ns:void 0)!==Qt)return null;try{const e=t.decode(n);if(!e||"object"!=typeof e)return null;const s=e,i="number"==typeof s.type?s.type:wt;if(i!==Ot&&i!==Ut&&i!==Lt&&i!==kt&&i!==Mt)return null;const o=this.readJid(r.to),a=Number(Yd(r.timestamp))||Date.now(),c=this.resolveActionConversationType(o.domain,s.meta,s),{senderId:d,receiverId:u}=this.resolveIncomingMessageParties(r,s,c),l=this.resolveActionConversationId(d,u,c);if(i===Lt)return!0===s.clearAllUnreadMessageCount?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"ALL_CONVERSATIONS_UNREAD_MESSAGE_COUNT_CLEARED",timestamp:a}}:l?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"CONVERSATION_UNREAD_MESSAGE_COUNT_CLEARED",conversationId:l,conversationType:"groupChat"===c?"groupChat":"singleChat",timestamp:a}}:null;if(i===Ot){js("Received READ_ACK MessageBody",s);const e=(Array.isArray(s.ackMessageIds)?s.ackMessageIds:[]).map(e=>Yd(e)).filter(e=>Boolean(e)),t=Yd(s.ackMessageId);if(0===e.length&&t&&e.push(t),0===e.length||!l)return null;const r=eu(Array.isArray(s.ext)?s.ext.filter(vh):void 0),n=vh(r.group_ack_count)?r.group_ack_count:{},i=e.flatMap(e=>{const t=n[e];return"number"==typeof t&&Number.isInteger(t)&&t>=0?[{messageId:e,count:t}]:[]});return{type:"message_receipts",data:{messageIds:e,conversationId:l,conversationType:"groupChat"===c?"groupChat":"singleChat",timestamp:a,..."groupChat"===c?{receiptDetails:i}:{}}}}if(i===Mt){const e=Yd(s.ackMessageId);return e&&l?{type:"message_delivered",data:{messageId:e,from:d,to:u,conversationId:l,conversationType:"singleChat"}}:null}if(i===Ut){const e=Yd(s.ackMessageId);return e&&l?{type:"message_recalled",data:{messageId:e,conversationId:l,conversationType:c,timestamp:a}}:null}const h=Yd(s.editMessageId),p=(Array.isArray(s.contents)?s.contents:[])[0],m=p?this.decodeContent(p):null;if(!h||!l||!m)return null;const f=this.resolveModifiedInfo(s.meta);return{type:"message_updated",data:{messageId:h,conversationId:l,conversationType:c,timestamp:a,message:{type:m.type,body:m.body,ext:eu(s.ext),...f?{modifiedInfo:f}:{}}}}}catch{return null}}decodeNotifyMeta(e){if(!e||"object"!=typeof e)return[];const t=e,r="number"==typeof t.ns?t.ns:void 0;if(r!==Xt&&r!==Yt&&r!==Zt&&r!==Jt)return[];const s=t.payload;let n=null;return s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),n?r===Yt?this.decodeRosterMeta(t,n):r===Zt?this.decodeMucMeta(t,n):r===Jt?this.decodeStatisticGroupReceiptNotifies(t,n):this.decodeNotifyPayload(n):[]}decodeStatisticGroupReceiptNotifies(e,t){try{const r=Kd(),s=r.lookupType("easemob.pb.StatisticsBody").decode(t);if("string"!=typeof s.location||0===s.location.length)return[];const n=JSON.parse(s.location);if(!vh(n)||!Array.isArray(n.group_ack))return[];const i=this.readMetaTimestamp(e)??Date.now(),o=new Map;for(const e of n.group_ack){if(!vh(e))continue;const t="string"==typeof e.groupId&&e.groupId.length>0?e.groupId:"";for(const[r,s]of Object.entries(e)){if("groupId"===r)continue;const e="number"==typeof s?s:"string"==typeof s&&s.trim().length>0?Number(s):Number.NaN;!r||!Number.isInteger(e)||e<0||o.set(r,{conversationId:t,count:e})}}return js("Decoded MSync statistic group read receipts",{receiptDetails:Array.from(o,([e,{conversationId:t,count:r}])=>({messageId:e,conversationId:t,count:r}))}),Array.from(o,([e,{conversationId:t,count:r}])=>({type:"message_receipts",data:{messageIds:[e],conversationId:t,conversationType:"groupChat",timestamp:i,receiptDetails:[{messageId:e,count:r}]}}))}catch{return[]}}decodeStatisticMeta(e){if(!e||"object"!=typeof e)return null;const t=e;if(t.ns!==Jt)return null;const r=t.payload;let s=null;if(r instanceof Uint8Array?s=r:r instanceof ArrayBuffer?s=new Uint8Array(r):ArrayBuffer.isView(r)&&(s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),!s)return null;try{const e=Kd(),t=e.lookupType("easemob.pb.StatisticsBody").decode(s);return{operation:"number"==typeof t.operation?t.operation:-1,reason:"string"==typeof t.reason?t.reason:void 0}}catch{return null}}decodeRosterMeta(e,t){try{const r=Kd(),s=r.lookupType("easemob.pb.RosterBody").decode(t),n="number"==typeof s.operation?s.operation:-1,i=this.readRosterJid(s.from),o=this.readRosterJidList(s.to),a="string"==typeof s.reason?s.reason:"",c="string"==typeof s.rosterVer&&s.rosterVer.trim().length>0?s.rosterVer:void 0,d=i.name??"",u=o[0]?.name??"";if(!d&&!u)return[];const l=hl({operation:n,from:i,to:o,rosterVersion:c,ext:a,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(l)return[this.createMultiDeviceNotify(l)];const h=this.mapRosterOperationToEvent(n,{from:d,to:u,message:a,rosterVersion:c});return h?[{type:"contact",eventName:h.eventName,data:h.payload}]:[]}catch{return[]}}readRosterJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0}}readRosterJidList(e){return Array.isArray(e)&&0!==e.length?e.map(e=>this.readRosterJid(e)):[]}readJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0,domain:"string"==typeof t.domain?t.domain:void 0}}decodeMucMeta(e,t){try{const r=Kd(),s=r.lookupType("easemob.pb.MUCBody").decode(t),n="number"==typeof s.operation?s.operation:-1,i=!0===s.isChatroom,o=!0===s.isThread,a=this.readJid(s.from),c=Array.isArray(s.to)?s.to.map(e=>this.readJid(e)):[],d=s.eventInfo&&"object"==typeof s.eventInfo?s.eventInfo:void 0,u=Array.isArray(s.members)?s.members.filter(e=>"string"==typeof e):[],l=a.name===this.context.userId&&a.clientResource&&a.clientResource!==this.context.clientResource?"multiDevice":"direct";if(o){const t=ml({operation:n,threadId:this.readJid(s.mucId).name??"",threadName:"string"==typeof s.mucName?s.mucName:void 0,parentId:this.readJid(s.mucParentId).name??void 0,from:a,to:c,members:u,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)];const r=37===n&&c.some(e=>e.name===this.context.userId),i=this.readJid(s.mucId).name??"",o=this.readJid(s.mucParentId).name??"";return r&&i&&o?[{type:"thread",eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:{id:i,name:"string"==typeof s.mucName?s.mucName:void 0,muc_parent_id:o,timestamp:this.readMetaTimestamp(e),from:a.name,userIds:[this.context.userId],operation:"kick"}}}]:[]}if(!i){const t=pl({operation:n,groupId:this.readJid(s.mucId).name??"",groupName:"string"==typeof s.mucName?s.mucName:void 0,from:a,to:c,reason:"string"==typeof s.reason?s.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,members:u,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)]}const h=i?hu({operation:n,chatRoomId:this.readJid(s.mucId).name??"",chatRoomName:"string"==typeof s.mucName?s.mucName:void 0,from:a,to:c,reason:"string"==typeof s.reason?s.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof s.ext?s.ext:void 0,members:u}):Ku({operation:n,groupId:this.readJid(s.mucId).name??"",groupName:"string"==typeof s.mucName?s.mucName:void 0,from:a,to:c,reason:"string"==typeof s.reason?s.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof s.ext?s.ext:void 0,members:u,source:l});return h?[{type:i?"chatroom":"group",eventName:i?"onChatRoomNotify":"onGroupNotify",data:h}]:[]}catch{return[]}}mapRosterOperationToEvent(e,t){const r={from:t.from,to:t.to,message:t.message,userInfo:{userId:t.from||t.to}};switch(((e,t)=>{t&&Qu.set(e,t)})(r,t.rosterVersion),e){case 2:return{eventName:"onContactInvited",payload:r};case 3:return{eventName:"onContactDeleted",payload:r};case 4:return{eventName:"onContactAdded",payload:r};case 5:case 9:return{eventName:"onContactRefuse",payload:r};case 8:return{eventName:"onContactAgreed",payload:r};default:return null}}decodeNotifyPayload(e){try{let t="";for(let i=0;i<e.length;i+=1){const r=e[i];if(void 0===r)return[];t+=`%${r.toString(16)}`}const r=decodeURIComponent(t),s=JSON.parse(r);js("Decoded MSync notify payload",{payload:s});const n="string"==typeof s.type?s.type:"";if(!n)return[];if("thread"===n){return[{type:n,eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:vh(s.data)?s.data:s}}]}if("conv"===n){const e=vh(s.data)?s.data:s,t=[],r="string"==typeof e.op?e.op:"";if("pin"===r||"pin_delete"===r)return[{type:n,eventName:"onPinnedMessageChanged",data:e}];const i=fl({operation:r,id:"string"==typeof e.id?e.id:"",type:"string"==typeof e.type?e.type:void 0,from:"string"==typeof e.from?e.from:void 0,res:"string"==typeof e.res?e.res:void 0,ts:e.ts,ext:"string"==typeof e.ext?e.ext:void 0,raw:e},this.msyncCodecContext());return i&&t.push(this.createMultiDeviceNotify(i)),t}if("roaming_delete"===n){const e=vh(s.data)?s.data:s,t=gl({chatType:"string"==typeof e.chatType?e.chatType:void 0,to:"string"==typeof e.to?e.to:void 0,resource:"string"==typeof e.resource?e.resource:void 0,msgIdList:Array.isArray(e.msgIdList)?e.msgIdList.filter(e=>"string"==typeof e):void 0,deleteTime:e.deleteTime,lastMsgId:"string"==typeof e.lastMsgId?e.lastMsgId:void 0,messageRoamingType:"string"==typeof e.messageRoamingType?e.messageRoamingType:void 0,raw:e},this.msyncCodecContext());return t?[this.createMultiDeviceNotify(t)]:[]}if("user_notification_mute"===n){return((e,t)=>{if(!Array.isArray(e)||0===e.length)return[];const r=[];for(const s of e){if(!ol(s))continue;const e=al(s.operator_resource,s.resource,s.clientResource);if(cl(e,t.clientResource))continue;const n=sl(s.group)??sl(s.user);if(!n||!ol(s.data))continue;const i=sl(s.group)?rl:tl,o=s.data;r.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:n,conversationType:i,remindType:sl(o.type),silentMode:o,deviceId:e,raw:s})}return r})(vh(s.data)&&Array.isArray(s.data.values)?s.data.values:Array.isArray(s.values)?s.values:[],this.msyncCodecContext()).map(e=>this.createMultiDeviceNotify(e))}return[{type:n,data:s.data??s}]}catch{return[]}}readMetaTimestamp(e){const t=e.timestamp,r=Number(Yd(t));if(Number.isFinite(r)&&r>0)return r}msyncCodecContext(){return{userId:this.context.userId,clientResource:this.context.clientResource}}createMultiDeviceNotify(e){return{type:"multiDevice",eventName:yl(e.category),data:e}}decodeNotice(e){const t=Kd().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=Kd().lookupType("easemob.pb.CommUnreadDL").decode(e);return{queues:(Array.isArray(t.unread)?t.unread:[]).map(e=>e&&"object"==typeof e?e:null).map(e=>e?.queue&&"object"==typeof e.queue?e.queue:null).filter(e=>Boolean(e))}}encodeBackQueue(e){const t=Kd(),r=t.lookupType("easemob.pb.CommSyncUL"),s=t.lookupType("easemob.pb.MSync"),n=Ih(r,{queue:e}),i={version:0,encryptType:[sr],command:_t,payload:n,traceId:tu()};return Ih(s,i)}encodeLastSession(e,t){const r=Kd(),s=r.lookupType("easemob.pb.CommSyncUL"),n=r.lookupType("easemob.pb.MSync"),i=Ih(s,{queue:e,key:t}),o={version:0,encryptType:[sr],command:_t,payload:i,traceId:tu()};return Ih(n,o)}encodeChatMessage(e,t){const r=Kd(),s=r.lookupType("easemob.pb.CommSyncUL"),n=r.lookupType("easemob.pb.MSync"),i=this.buildChatMeta(e,t),o=Ih(s,{meta:i}),a={version:0,encryptType:[sr],command:_t,payload:o,traceId:tu()};return Ih(n,a)}encodeCombineMessageMeta(e){const t=Kd().lookupType("easemob.pb.Meta"),r=Zd(e.msgServerId||e.msgLocalId),s=this.buildChatMeta(e,r,!0);return Ih(t,s)}buildChatMeta(e,t,r=!1){const s=Kd().lookupType("easemob.pb.MessageBody"),n=this.buildContent(e),i=this.resolveMessageProfileVersionFields(e),o=this.buildMessageMeta(e),a=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),c=r?e.from||e.sender.userId:this.context.userId,d=r&&e.to||a.name,u={type:this.resolveChatType(e),from:{name:c},to:{name:d},contents:[n],ext:Xd(e.ext??{}),...o?{meta:o}:{},...i,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},l=Ih(s,u),h="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",p=this.resolveDirectedUsers(e),m=this.resolveMetaExt(e);return{id:t,to:Qd({appKey:this.context.appKey,name:d,domain:h,clientResource:r?void 0:a.clientResource}),...r?{timestamp:e.timestamp}:{},ns:Qt,payload:l,routetype:this.resolveRouteType(e),directedUsers:p,ext:m,...void 0!==e.webhookEnv?{env:e.webhookEnv}:{}}}encodeActionMessage(e,t){const r=Kd(),s=r.lookupType("easemob.pb.MessageBody"),n=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),o=r.lookupEnum("easemob.pb.MessageBody.EditScope"),a=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),c=e.body&&e.messageType?[this.buildContent({msgServerId:e.messageId??"",msgLocalId:t,from:this.context.userId,to:e.conversationId,sender:{userId:this.context.userId},conversationId:e.conversationId,conversationType:e.conversationType,type:e.messageType,sendStatus:"sending",ext:e.ext??{},timestamp:Date.now(),body:e.body})]:[],d={type:this.resolveActionMessageType(e),from:{name:this.context.userId},to:{name:a.name},contents:c,ext:Xd(e.ext??{})};"recall"!==e.kind&&"deliveryAck"!==e.kind||(d.ackMessageId=e.messageId),"sendMessageReadReceipts"===e.kind&&(d.ackMessageIds=e.messageIds,"groupChat"===e.conversationType&&(d.msgConfig={allowGroupAck:!0})),"clearConversationUnreadMessageCount"===e.kind&&(d.sendToPeer=e.sendToPeer??!1),"clearAllConversationUnreadMessageCount"===e.kind&&(d.sendToPeer=e.sendToPeer??!1,d.clearAllUnreadMessageCount=e.clearAllUnreadMessageCount??!0),"update"===e.kind&&(d.editMessageId=e.messageId,d.editScope=e.ext&&Object.keys(e.ext).length>0?o.values.BODY_AND_EXT:o.values.BODY);const u=Ih(s,d);if("clearAllConversationUnreadMessageCount"===e.kind){const e=s.decode(u),r=s.fields.clearAllUnreadMessageCount;js("Clear-all unread MessageBody wire encoded",{operation:"msync.action.clear-all-unread.wire",protocolId:t,messageType:d.type,fieldId:r?.id,requestedValue:d.clearAllUnreadMessageCount,decodedHasField:Object.prototype.hasOwnProperty.call(e,"clearAllUnreadMessageCount"),decodedValue:e.clearAllUnreadMessageCount,messageBodyBytes:u.byteLength,wireTailHex:Array.from(u.slice(-16),e=>e.toString(16).padStart(2,"0")).join(" ")})}const l={id:t,to:Qd({appKey:this.context.appKey,name:a.name,domain:"singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",clientResource:a.clientResource}),ns:Qt,payload:u,routetype:er,directedUsers:[],ext:[]},h=Ih(n,{meta:l}),p={version:0,encryptType:[sr],command:_t,payload:h,traceId:tu()};return Ih(i,p)}encodeChatRoomOperation(e,t){const r=Kd(),s=r.lookupType("easemob.pb.MUCBody"),n=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),o={mucId:Qd({appKey:this.context.appKey,name:e.chatRoomId,domain:"conference.easemob.com"}),operation:"join"===e.operation?2:3,from:{name:this.context.userId},isChatroom:!0};"join"===e.operation&&(void 0!==e.ext&&(o.ext=e.ext),void 0!==e.leaveOtherRooms&&(o.leaveOtherRooms=e.leaveOtherRooms));const a=Ih(s,o),c={id:t,from:Qd({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:Zt,payload:a},d=Ih(n,{meta:c}),u={version:0,encryptType:[sr],command:_t,payload:d,traceId:tu()};return Ih(i,u)}decodeServerMessageMeta(e){const t=Kd(),r=t.lookupType("easemob.pb.Meta"),s=t.lookupType("easemob.pb.MessageBody");try{const t=r.decode(e);return this.decodeChatMeta(t,s)}catch{return null}}async normalizeIncoming(e){if(e instanceof Uint8Array)return e;if(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))return new Uint8Array(e);var t;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if((e=>"undefined"!=typeof Blob&&e instanceof Blob||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(e)){const t=await e.arrayBuffer();return new Uint8Array(t)}return"string"==typeof e?zs(e):e&&"object"==typeof e&&"data"in e?this.normalizeIncoming(e.data):new Uint8Array}decompressIncoming(e){if(!this.compressor||!this.compressor.enableDownlinkCompression)return e;try{return this.compressor.decompress(e)}catch{return this.compressionFailureCount+=1,null}}prepareOutgoing(e){if(!this.compressor||!this.compressor.enableUplinkCompression)return e;try{return this.compressor.compress(e)}catch{throw this.compressionFailureCount+=1,new Error("compress outgoing message failed")}}resetCompressionNegotiation(){this.compressor?.reset(),this.disableCompression()}toProtocolId(e){return Zd(e)}decodeChatRoomJoinInfo(e){const t=Kd().lookupType("easemob.pb.MUCBody");for(const s of e){if(!vh(s)||s.ns!==Zt)continue;const e=s.payload,n=e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0;if(n)try{const e=t.decode(n);if(!vh(e)||!vh(e.status))continue;const r=e.status.chatroomInfo;if("string"!=typeof r||""===r)continue;const s=JSON.parse(r);if(!vh(s))continue;const i=s[this.context.userId];if(!vh(i))continue;const o=i;return{..."boolean"==typeof o.is_all_mute?{isAllMembersMuted:o.is_all_mute}:{},..."number"==typeof o.create_timestamp?{createTimestamp:o.create_timestamp}:{},..."boolean"==typeof o.is_in_white_list?{isInAllowlist:o.is_in_white_list}:{},..."number"==typeof o.member_count?{memberCount:o.member_count}:{},muteExpireTimestamp:"number"==typeof o.mute_duration&&0!==o.mute_duration?o.mute_duration:-1}}catch(r){Ks("Failed to decode chat room info from ACK",r)}}}decodeAck(e){const t=Yd(e.metaId);if(!t||"0"===t)return;const r=e.status??{},s="number"==typeof r.errorCode?r.errorCode:ar,n="string"==typeof r.reason?r.reason:void 0;return{protocolId:t,serverId:Yd(e.serverId),ok:s===or,statusCode:s,reason:n}}decodeMessage(e,t){const r="number"==typeof t.type?t.type:Rt;if(!this.isPublicMessageType(r))return null;const s=(Array.isArray(t.contents)?t.contents:[])[0];if(!s)return null;const n=this.resolveConversationType(r),{senderUserId:i,senderId:o,receiverId:a}=this.resolveIncomingMessageParties(e,t,n),c=o===this.context.userId?"SEND":"RECEIVE",d="singleChat"===n?"SEND"===c?a:o:a,u=this.decodeContent(s);if(!u)return null;const l=eu(t.ext),h=eu(e.ext),p=Number(Yd(e.timestamp))||Date.now(),m=Yd(e.id),f=this.resolveBroadcast(h),g=this.resolvePriority(h),y=this.resolveMessageMetaPayload(t.meta,e.meta),v=this.resolveContentReplaced(y),I=this.resolveReactions(y),b=this.resolveModifiedInfo(y),_=this.resolveChatThreadMessageContext(y),T=this.resolveChatThreadOverview(y),C=this.resolveProfileVersionTime(t.userInfoUpdateTime),S=this.resolveProfileVersionTime(t.namecardUpdateTime),E={msgServerId:m,msgLocalId:"",from:o,to:a,sender:{userId:i},conversationId:d,conversationType:n,type:u.type,sendStatus:"sent",ext:l,timestamp:p,body:u.body,direct:c,isOnline:this.resolveMessageIsOnline(r,h)};Hu(E,{userInfoUpdateTime:C,namecardUpdateTime:S});const w=this.decodeStreamMeta(t.stream,s);w&&(E.type="text",E.body={content:w.fullText},E.stream=w),void 0!==f&&(E.isBroadcast=f),void 0!==g&&(E.priority=g),void 0!==v&&(E.isContentReplaced=v),I&&(E.reactions=I),b&&(E.modifiedInfo=b),_&&(E.isChatThread=!0,E.chatThread=_);const R=this.resolvePeerRead(y,n,c);void 0!==R&&(E.isPeerRead=R);const A=this.resolveGroupReadCount(y,n);void 0!==A&&(E.groupReadCount=A),T&&(E.chatThreadOverview=T);const N=t.msgConfig;return N?.allowGroupAck&&(E.needReadReceipt=!0),E}resolveMessageProfileVersionFields(e){const t=Wu(e),r={};return"number"==typeof t?.userInfoUpdateTime&&(r.userInfoUpdateTime=t.userInfoUpdateTime),"groupChat"===e.conversationType&&"number"==typeof t?.namecardUpdateTime&&(r.namecardUpdateTime=t.namecardUpdateTime),r}buildMessageMeta(e){const t={};return e.isChatThread&&(t.thread={}),Object.keys(t).length>0?JSON.stringify(t):""}resolveProfileVersionTime(e){return Il(Yd(e))}isPublicMessageType(e){return e===Rt||e===At||e===Nt}resolveMessageIsOnline(e,t){if(e===Nt)return!0;const r=t.is_online;return"boolean"==typeof r?r:"number"==typeof r?0!==r:"string"!=typeof r||"0"!==r}decodeStreamMeta(e,t){if(!e||"object"!=typeof e)return;const r=e,s=Number(Yd(r.streamSeq));if(!Number.isFinite(s))return;const n="number"==typeof r.streamStatus?r.streamStatus:zt,i="number"==typeof r.streamError?r.streamError:0,o="number"==typeof r.streamFinishReason?r.streamFinishReason:void 0,a=this.resolveContentText(t),c=a;return{customType:"string"==typeof r.streamType?r.streamType:void 0,seq:s,status:this.mapStreamStatus(n,i),errorType:i,finishReason:o,deltaText:a,fullText:c}}mapStreamStatus(e,t){return t>0?nt.ERROR:e===Vt?nt.START:e===Kt?nt.START_COMPLETED:e===Ht?nt.COMPLETED:e===Wt?nt.FULL:nt.IN_PROGRESS}resolveContentText(e){return e&&"string"==typeof e.text?e.text:e&&"string"==typeof e.customEvent?e.customEvent:""}buildContent(e){if("text"===e.type){const t=e.body;return{type:Dt,text:t.content}}if("cmd"===e.type){const t=e.body;return{type:qt,action:t.action}}if("custom"===e.type){const t=e.body;return{type:$t,customEvent:t.event,customExts:Xd(t.params??{})}}if("location"===e.type){const t=e.body;return{type:Ft,latitude:t.latitude,longitude:t.longitude,address:t.address,buildingName:t.buildingName}}if("image"===e.type){const r=e.body,s=r.isGif||r.isOriginalImage?"original":"large";return{type:Pt,displayName:r.filename,remotePath:r.originalImageUrl??"",imageType:(t=s,t===hs?1:2),secretKey:r.secret,fileLength:r.fileLength,size:{width:r.width,height:r.height},subType:r.isGif?1:void 0,thumbnailRemotePath:r.thumbnailUrl,thumbnailDisplayName:r.filename}}var t;if("video"===e.type){const t=e.body;return{type:xt,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,duration:t.duration,size:t.width&&t.height?{width:t.width,height:t.height}:void 0,thumbnailRemotePath:t.thumbnailUrl,thumbnailSecretKey:t.secret,thumbnailDisplayName:t.filename}}if("voice"===e.type){const t=e.body;return{type:Bt,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,duration:t.duration,thumbnailDisplayName:t.filename}}if("combine"===e.type){const t=e.body;return{type:Dt,subType:0,text:Xu(e)??"版本过低",displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,title:t.title,summary:t.summary,combineLevel:t.combineLevel}}const r=e.body;return{type:Gt,displayName:r.filename,remotePath:r.url,secretKey:r.secret,fileLength:r.fileLength,thumbnailDisplayName:r.filename}}decodeContent(e){const t="number"==typeof e.type?e.type:Dt,r="string"==typeof e.remotePath&&e.remotePath.length>0||"string"==typeof e.title&&e.title.length>0||"string"==typeof e.summary&&e.summary.length>0||"number"==typeof e.combineLevel&&e.combineLevel>0,s=Object.prototype.hasOwnProperty.call(e,"subType")&&0===e.subType;if(t===jt||t===Dt&&(s||r)){return{type:"combine",body:{title:"string"==typeof e.title?e.title:"",summary:"string"==typeof e.summary?e.summary:"",filename:"string"==typeof e.displayName?e.displayName:"combine",filetype:"application/octet-stream",url:"string"==typeof e.remotePath?e.remotePath:void 0,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,combineLevel:"number"==typeof e.combineLevel?e.combineLevel:0}}}if(t===Dt)return{type:"text",body:{content:"string"==typeof e.text?e.text:""}};if(t===qt)return{type:"cmd",body:{action:"string"==typeof e.action?e.action:""}};if(t===$t){const t=eu(e.customExts);return{type:"custom",body:{event:"string"==typeof e.customEvent?e.customEvent:"",params:t}}}if(t===Ft)return{type:"location",body:{latitude:"number"==typeof e.latitude?e.latitude:0,longitude:"number"==typeof e.longitude?e.longitude:0,address:"string"==typeof e.address?e.address:void 0,buildingName:"string"==typeof e.buildingName?e.buildingName:void 0}};if(t===Pt){const t=e.size??{},r="number"==typeof t.width?t.width:0,s="number"==typeof t.height?t.height:0,n=Ss(e.imageType)===hs,i="string"==typeof e.remotePath?e.remotePath:"",o=Ts(i,{deriveVariants:!this.useCustomAttachmentUpload}),a="string"==typeof e.thumbnailRemotePath&&e.thumbnailRemotePath.length>0?e.thumbnailRemotePath:void 0;return{type:"image",body:{localUrl:"",filename:"string"==typeof e.displayName?e.displayName:"image",filetype:"application/octet-stream",width:r,height:s,isGif:1===e.subType,isOriginalImage:n,originalImageUrl:o.originalImageUrl,bigImageUrl:o.bigImageUrl,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:a??o.thumbnailUrl}}}if(t===xt){const t=e.size??{},r="number"==typeof t.width?t.width:void 0,s="number"==typeof t.height?t.height:void 0,n="string"==typeof e.thumbnailRemotePath?e.thumbnailRemotePath:void 0;return{type:"video",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"video",filetype:"application/octet-stream",duration:"number"==typeof e.duration?e.duration:0,width:r,height:s,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:n}}}if(t===Bt){return{type:"voice",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"voice",filetype:"application/octet-stream",duration:"number"==typeof e.duration?e.duration:0,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0}}}if(t===Gt){return{type:"file",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"file",filetype:"application/octet-stream",secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0}}}return null}resolveChatType(e){switch(e.conversationType){case"groupChat":return At;case"chatRoom":return Nt;default:return Rt}}resolveActionConversationType(e,t,r){const s=this.resolveConversationTypeFromMeta(t);if(s)return s;const n=r?.msgConfig&&"object"==typeof r.msgConfig?r.msgConfig:null;return!0===n?.allowGroupAck||"conference.easemob.com"===e?"groupChat":"singleChat"}resolveConversationTypeFromMeta(e){if("string"!=typeof e||0===e.length)return null;try{const t=JSON.parse(e),r=t.edit_msg&&"object"==typeof t.edit_msg?t.edit_msg:void 0,s=("string"==typeof t.chat_type?t.chat_type:void 0)??("string"==typeof t.chatType?t.chatType:void 0)??("string"==typeof t.type?t.type:void 0)??("string"==typeof r?.chat_type?r.chat_type:void 0);if("chat:user"===s||"singleChat"===s)return"singleChat";if("chat:group"===s||"groupChat"===s)return"groupChat";if("chat:room"===s||"chatRoom"===s)return"chatRoom"}catch{}return null}resolveActionConversationId(e,t,r){return"singleChat"===r?e===this.context.userId?t:e:t}resolveOutboundMessageTarget(e,t){if("singleChat"!==t)return{name:e};const r=`${this.context.userId}/`;if(!e.startsWith(r))return{name:e};const s=e.slice(r.length);return s?{name:this.context.userId,clientResource:s}:{name:e}}resolveIncomingMessageParties(e,t,r){const s=this.readJid(e.from),n=this.readJid(e.to),i=this.readJid(t.from),o=this.readJid(t.to),a=i.name??s.name??"",c=o.name??n.name??"";if(!("singleChat"===r&&a===this.context.userId&&c===this.context.userId))return{senderUserId:a,senderId:a,receiverId:c};return{senderUserId:a,senderId:s.clientResource&&s.clientResource!==this.context.clientResource?`${a}/${s.clientResource}`:a,receiverId:n.clientResource?`${c}/${n.clientResource}`:c}}resolveActionMessageType(e){switch(e.kind){case"clearConversationUnreadMessageCount":case"clearAllConversationUnreadMessageCount":return Lt;case"sendMessageReadReceipts":return Ot;case"deliveryAck":return Mt;case"recall":return Ut;case"update":return kt;default:return Rt}}resolveConversationType(e){return e===At?"groupChat":e===Nt?"chatRoom":"singleChat"}resolveDirectedUsers(e){return"singleChat"===e.conversationType?[]:Array.isArray(e.receiverList)?e.receiverList:[]}resolveDeliverOnlineOnly(e){if("boolean"==typeof e.deliverOnlineOnly)return e.deliverOnlineOnly;if("cmd"===e.type){const t=e.body;return Boolean(t.deliverOnlineOnly)}return!1}resolveMetaExt(e){return"chatRoom"!==e.conversationType?[]:e.priority?Xd({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?rr:this.resolveDeliverOnlineOnly(e)?tr:er}resolveBroadcast(e){if(!Object.prototype.hasOwnProperty.call(e,"is_broadcast"))return;const t=e.is_broadcast;return"boolean"==typeof t?t:"number"==typeof t?0!==t:"string"==typeof t?"1"===t||"true"===t.toLowerCase():Boolean(t)}resolvePriority(e){if(!Object.prototype.hasOwnProperty.call(e,"chatroom_msg_tag"))return;const t=Number(e.chatroom_msg_tag);return 0===t?"high":2===t?"low":"normal"}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),s=this.parseMetaPayload(t);return r&&s?{...s,...r}:r??s??e??t}resolvePeerRead(e,t,r){if("singleChat"!==t||"SEND"!==r)return;const s=this.parseMetaPayload(e);return"boolean"==typeof s?.isRead?s.isRead:void 0}resolveGroupReadCount(e,t){if("groupChat"!==t)return;const r=this.parseMetaPayload(e),s=r?.group_read_ack;return"number"==typeof s&&Number.isInteger(s)&&s>=0?s:void 0}resolveModifiedInfo(e){const t=this.parseMetaPayload(e),r=t?.edit_msg;if(!vh(r))return;const s="string"==typeof r.operator?r.operator:"",n=this.toFiniteNumber(r.count),i=this.toFiniteNumber(r.edit_time);return s&&void 0!==n&&void 0!==i?{operatorId:s,operationCount:n,operationTime:i}:void 0}resolveChatThreadMessageContext(e){const t=this.parseMetaPayload(e),r=t?.thread;if(!vh(r)||0===Object.keys(r).length)return;const s=this.readString(r.msg_parent_id??r.messageId),n=this.readString(r.muc_parent_id??r.parentId);if(!s||!n)return;const i=this.readString(r.thread_name??r.chatThreadName);return{messageId:s,parentId:n,...i?{chatThreadName:i}:{}}}resolveChatThreadOverview(e){const t=this.parseMetaPayload(e),r=t?.thread_overview??t?.threadOverview;if(!vh(r)||0===Object.keys(r).length)return;const s=this.readString(r.id??r.thread_id??r.chatThreadId),n=this.readString(r.muc_parent_id??r.parentId);if(!s||!n)return;const i=this.readString(r.name),o=this.resolveChatThreadOverviewLastMessage(r.last_message??r.lastMessage,s);return{chatThreadId:s,parentId:n,...i?{name:i}:{},...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(!vh(e)||0===Object.keys(e).length)return null;const r=this.readString(e.msgId??e.msg_id??e.id);if(!r)return null;const s=this.toFiniteNumber(e.timestamp)??0,n=this.resolveThreadLastMessagePayload(e),i=this.readString(n?.from)??this.readString(e.from)??"",o=this.readString(n?.to)??this.readString(e.to)??t,a=Array.isArray(n?.bodies)?n.bodies:[],c=vh(a[0])?a[0]:null,d=this.readString(c?.type)??this.readString(e.type),u=this.mapThreadMessageType(d),l=this.normalizeThreadLastMessageBody(u,c,e),h=t,p=i===this.context.userId?"SEND":"RECEIVE";return{msgServerId:r,msgLocalId:"",from:i,to:o,sender:{userId:i},conversationId:h,conversationType:"groupChat",type:u,sendStatus:"sent",ext:vh(n?.ext)?n.ext:{},timestamp:s,body:l,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(vh(t))return t;if("string"==typeof t){const e=this.parseMetaPayload(t);if(e)return e}return 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(e,t,r){if(!t){return{content:this.readString(r.msg??r.content??r.text)??""}}switch(e){case"text":default:return{content:this.readString(t.msg??t.content??t.text)??""};case"image":{const e=this.readString(t.url)??"",r=Ts(e,{deriveVariants:!this.useCustomAttachmentUpload});return{localUrl:"",filename:this.readString(t.filename)??"image",filetype:this.readString(t.filetype)??"application/octet-stream",width:this.toFiniteNumber(t.width)??0,height:this.toFiniteNumber(t.height)??0,isGif:!0===t.isGif,isOriginalImage:!1,originalImageUrl:r.originalImageUrl,bigImageUrl:r.bigImageUrl,thumbnailUrl:this.readString(t.thumb)??r.thumbnailUrl,secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)}}case"voice":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"voice",filetype:this.readString(t.filetype)??"application/octet-stream",duration:this.toFiniteNumber(t.duration??t.length)??0,secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"video":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"video",filetype:this.readString(t.filetype)??"application/octet-stream",duration:this.toFiniteNumber(t.duration??t.length)??0,width:this.toFiniteNumber(t.width),height:this.toFiniteNumber(t.height),thumbnailUrl:this.readString(t.thumb),secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"file":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"file",filetype:this.readString(t.filetype)??"application/octet-stream",secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"location":return{latitude:this.toFiniteNumber(t.lat??t.latitude)??0,longitude:this.toFiniteNumber(t.lng??t.longitude)??0,address:this.readString(t.addr??t.address),buildingName:this.readString(t.buildingName)};case"cmd":return{action:this.readString(t.action)??""};case"custom":return{event:this.readString(t.event??t.customEvent)??"",params:vh(t.params??t.customExts)?t.params??t.customExts:{}};case"combine":return{title:this.readString(t.title)??"",summary:this.readString(t.summary)??"",filename:this.readString(t.filename)??"combine",filetype:"application/octet-stream",url:this.readString(t.url),secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength),combineLevel:this.toFiniteNumber(t.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(Hs(t));return vh(e)?e:null}catch{return null}}if(vh(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return vh(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(vh).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}mapPriorityToTag(e){return"high"===e?0:"low"===e?2:1}getRequestedCompressTypes(){return this.compressionFailureCount>=this.maxCompressionFailures?[]:[ir]}configureCompression(e,t){if(!e||!e.includes(ir))return void this.disableCompression();this.compressor||(this.compressor=new yh);const r=this.resolveCompressionMode(t);this.compressor.mode=r,this.compressor.enableUplinkCompression=r===fh.UPLINK_ONLY||r===fh.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=r===fh.DOWNLINK_ONLY||r===fh.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?fh.UPLINK_ONLY:1===e?fh.DOWNLINK_ONLY:2===e?fh.BIDIRECTIONAL:fh.NONE}disableCompression(){this.compressor&&(this.compressor.mode=fh.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}const _h=1e3,Th="direct";class Ch{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 r=0;r<this.events.length;r+=1){const s=this.events[r];s&&s.appKey===e&&(this.events[r]={appKey:t,wire:{...s.wire,body:{...s.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 r=0;r<this.events.length&&t.length<this.batchSize;){const s=this.events[r];s?.appKey===e.appKey?(t.push(s.wire),this.events.splice(r,1)):r+=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 Sh{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 r=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});(r.status<200||r.status>=300)&&this.onFailure?.({reason:"non-success-response",status:r.status})}catch(r){this.onFailure?.({reason:"transport-error",message:r instanceof Error?r.message:String(r)})}else this.onFailure?.({reason:"request-adapter-unavailable",eventCount:t.length})}}const Eh={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},wh=()=>{const e=fn(),t=e.crypto?.randomUUID;return("function"==typeof t?t.call(e.crypto):void 0)??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class Rh{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??wh;const t=new Sh({requestAdapter:e.requestAdapter,debug:e.debug,now:this.now,onFailure:t=>{e.onDiagnostic?.("DataReport transport failed",t)}}),r=e.send??((e,r)=>t.send(e,r));this.queue=new Ch({send:r,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:Eh[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 r=`opr_${this.randomId()}`,s=this.now();let n=!1,i=!1,o=`req_${this.randomId()}`,a=0,c="";const d=()=>!n&&!i&&this.session?.sessionId===t,u=(t,s,n,i,o)=>{d()&&(a=o.success?0:o.code,c=o.success?"":o.description??"",this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:r,requestid:s,operationName:e.operationName,operationType:e.operationType,requestName:t.requestName??e.operationName,subrequestid:String(n),requestMethod:t.method??"",requestUrl:t.url??"",requestElapse:Math.max(0,this.now()-i),code:o.code,codeDesc:o.description??"",isLastApi:0,isSuccess:o.success?1:0,accessChannel:this.session?.accessChannel??Th,msgId:e.msgId,messageType:e.messageType,resultCount:o.resultCount}))},l=(e,t,r,s)=>{const n=this.now();let i=!1;return{retry:()=>(s.next+=1,l(e,t,s.next,s)),finish:s=>{i||(i=!0,u(e,t,r,n,s))}}};return{startRequest:(e={})=>(o=`req_${this.randomId()}`,l(e,o,1,{next:1})),finish:t=>{d()&&(n=!0,this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:r,requestid:o,operationName:e.operationName,operationType:e.operationType,requestName:"",subrequestid:"0",requestMethod:"",requestUrl:"",requestElapse:Math.max(0,this.now()-s),code:t.success?0:t.code??a,codeDesc:t.success?"":t.description??c,isLastApi:1,isSuccess:t.success?1:0,accessChannel:this.session?.accessChannel??Th,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 r=this.session;if(!r||"disabled"===this.currentState)return;const s={lts:this.now(),net:this.networkType,appkey:r.appKey,sdkServiceId:r.serviceId,sdkProduct:0,uikitVersion:r.uikitVersion??"",...t},n={eventId:e,body:Object.fromEntries(Object.entries(s).filter(([,e])=>void 0!==e))};this.queue.enqueue({appKey:r.appKey,wire:n})}createNoopOperation(){const e={retry:()=>e,finish:()=>{}};return{startRequest:()=>e,finish:()=>{},discard:()=>{}}}}let Ah;const Nh=e=>{Ah?.updateSession(e)},Oh=e=>{Ah?.applyDnsSwitch(e)},Mh=e=>{Ah?.updateNetworkType(e)},Uh=e=>{if("disabled"!==Ah?.state)return Ah?.startOperation(e)},Lh=()=>{Ah?.reset(),Ah=void 0},kh=e=>new ht("Connection attempt cancelled",{code:ot.CONNECTION_CANCELLED,details:{stage:e,cancelled:!0,retryable:!0}}),Dh=e=>e instanceof ht&&e.code===ot.CONNECTION_CANCELLED&&!0===e.details?.cancelled;class Ph{constructor(e,r){this.serverUrlIndex=0,this.websocket=null,this.provisionTimeoutId=null,this.reconnectAttempts=0,this.messageReceiver=null,this.provisionPromise=null,this.provisionResolve=null,this.provisionReject=null,this.queues=[],this.currentQueueId=null,this.currentQueue=null,this.nextKey=null,this.offlineMessageSyncing=!1,this.offlineMessageSyncLifecycleDispatched=!1,this.offlineMessageSyncLifecycleActive=!1,this.offlineMessageQueueNames=new Set,this.offlineMessageQueueReports=new Map,this.offlineMessageQueueCounts=new Map,this.offlineMessageTotalCount=0,this.reconnectTimerId=null,this.reconnectDelayReject=null,this.reconnectTask=null,this.pendingReconnectReason=null,this.reconnectInProgress=!1,this.reconnectPaused=!1,this.terminalDisconnectError=null,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.hasEverConnected=!1,this.isOnline=!0,this.internalHandlerId="__internal:connection-manager",this.suppressNextCloseEvent=!1,this.socketDisposers=[],this.inboundMessageQueue=Promise.resolve(),this.socketGeneration=0,this.connectionAttemptGeneration=0,this.activeConnectionAttemptCancel=null,this.activeLoginDeadline=null,this.tokenLifecycle=null,this.tokenWillExpireTimerId=null,this.tokenExpiredTimerId=null,this.config={heartBeatWait:3e4,autoReconnectNumMax:10,connectTimeout:1e4,...e},this.eventHub=r,this.msyncCodec=new bh({appKey:e.appKey,useCustomAttachmentUpload:e.useCustomAttachmentUpload,userId:e.userId,token:e.token,useReplacedMessageContents:e.useReplacedMessageContents,useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,serviceId:e.serviceId}),this.serverUrls=this.normalizeServerUrls(e),this.config.serverUrl=this.serverUrls[0]??this.config.serverUrl,this.connection={status:t,serverUrl:this.config.serverUrl,userId:e.userId,token:e.token,reconnectAttempts:0},this.connectionRetry=new Bd({maxAttempts:this.config.autoReconnectNumMax,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2}),this.heartbeatManager=new $d({interval:this.config.heartBeatWait,timeout:6e4}),this.connectionEventNormalizer=new Ws,this.socketAdapter=this.resolveSocketAdapter(e),this.isOnline="undefined"==typeof navigator||navigator.onLine,this.eventHub.addEventHandler(this.internalHandlerId,{[m]:e=>{this.handleSendTimeout(e)}})}getConnectionStatus(){return this.connection.status}getWebSocket(){return this.websocket}getMsyncCodec(){return this.msyncCodec}getClientResource(){return this.msyncCodec.getContext().clientResource}setMessageReceiver(e){this.messageReceiver=e}renewToken(e,t){const r=Date.now();if(t<=r)throw new ht("Token is expired",{code:ot.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});return this.config.token=e,this.connection.token=e,this.msyncCodec.updateToken(e),this.setupTokenLifecycle(e,t,r),Vs("Connection token renewed",{userId:this.config.userId,expireAt:t}),{token:e,expireAt:t}}handleOnline(){if(Vs("Network online event received",this.getReconnectDiagnostic()),this.isOnline=!0,this.terminalDisconnectError)return void Vs("Network online recovery skipped",{guard:"terminal-disconnect",...this.getReconnectDiagnostic()});const e=this.offlineRecoverPending?C:T;this.offlineRecoverPending=!1,this.resumeReconnect(e)}handleOffline(){Vs("Network offline event received",this.getReconnectDiagnostic()),this.isOnline=!1,this.offlineRecoverPending=!0,this.reconnectPaused=!0,this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.stopHeartbeat(),this.closeWebSocket(N,!0),Vs("Network offline state applied",this.getReconnectDiagnostic())}async handleForeground(){if(this.terminalDisconnectError)return void Vs("Foreground recovery skipped",{guard:"terminal-disconnect",...this.getReconnectDiagnostic()});if(!this.isLoggedIn)return;if(!this.isOnline)return;if(this.reconnectInProgress)return void Vs("Foreground recovery skipped",{guard:"reconnect-in-progress",...this.getReconnectDiagnostic()});const e=this.websocket;try{if(!(await this.checkHeartbeatOnce())){if(this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(S,!0,!0),this.resumeReconnect(S)}}catch(t){if(Vs("Foreground heartbeat check failed",t),this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(S,!0,!0),this.resumeReconnect(S)}}resumeReconnect(e){if(this.terminalDisconnectError)Vs("Reconnect recovery skipped",{guard:"terminal-disconnect",reason:e,...this.getReconnectDiagnostic()});else if(this.isLoggedIn)return this.reconnectTask||this.reconnectInProgress?(this.pendingReconnectReason=e,void Vs("Reconnect recovery queued",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()})):void(this.connection.status===s&&this.websocket||(this.reconnectPaused=!1,this.resetReconnectState(),Vs("Reconnect recovery requested",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e)))}handleSendTimeout(e){this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||e.reason===E&&Vs("Message send timeout received without reconnect",e))}resetReconnectState(){this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connectionRetry.reset()}getReconnectDiagnostic(){return{status:this.connection.status,isOnline:this.isOnline,isLoggedIn:this.isLoggedIn,isLoginPhase:this.isLoginPhase,reconnectInProgress:this.reconnectInProgress,reconnectPaused:this.reconnectPaused,terminalDisconnectCode:this.terminalDisconnectError?.code,offlineRecoverPending:this.offlineRecoverPending,reconnectAttempts:this.reconnectAttempts,hasWebSocket:null!==this.websocket,hasReconnectTimer:null!==this.reconnectTimerId,hasReconnectTask:null!==this.reconnectTask,hasActiveConnectionAttempt:null!==this.activeConnectionAttemptCancel}}normalizeServerUrls(e){const t=(e.serverUrls??[]).filter(e=>"string"==typeof e&&e.length>0);return t.length>0?[...t]:[e.serverUrl]}pickNextServerUrl(){if(0===this.serverUrls.length)return this.config.serverUrl;const e=this.serverUrlIndex%this.serverUrls.length,t=this.serverUrls[e]??this.config.serverUrl;return this.serverUrlIndex=(e+1)%this.serverUrls.length,this.config.serverUrl=t,this.connection.serverUrl=t,t}resolveEffectiveMaxAttempts(){return this.isLoginPhase&&0===this.config.autoReconnectNumMax?1:this.config.autoReconnectNumMax}isNonRetryableError(e){if(!(e instanceof ht))return!1;const t=e.details;if(!t||"object"!=typeof t)return!1;return!1===t.retryable}isServerNormalClosePayload(e){if(e.length>64)return!1;let t;try{t=JSON.parse(Hs(e))}catch{return!1}return!(!Array.isArray(t)||t.length<2)&&(3e3===t[0]&&"normal closed"===t[1])}clearReconnectTimer(){const e=this.reconnectDelayReject;this.reconnectDelayReject=null,this.reconnectTimerId&&(clearTimeout(this.reconnectTimerId),this.reconnectTimerId=null),e?.(kh("retry-delay"))}resolveLoginStageTimeout(e){return this.isLoginPhase&&this.activeLoginDeadline?this.activeLoginDeadline.clamp(e):e}isLoginDeadlineExpired(){return Boolean(this.isLoginPhase&&this.activeLoginDeadline&&this.activeLoginDeadline.remainingMs()<=0)}requireLoginTimeoutError(){const e=this.activeLoginDeadline;return e?(e.expire(),e.createTimeoutError()):new ht("Login timeout",{code:ot.CONNECTION_LOGIN_TIMEOUT,details:{stage:"login",retryable:!0}})}async waitForReconnectDelay(){const e=this.connectionRetry.getRetryDelay(),t=this.resolveLoginStageTimeout(e);if(t<=0)throw this.requireLoginTimeoutError();Vs("Reconnect retry scheduled",{delayMs:Math.round(t),...this.getReconnectDiagnostic()}),this.clearReconnectTimer(),await new Promise((e,r)=>{this.reconnectDelayReject=e=>{this.reconnectDelayReject=null,r(e)},this.reconnectTimerId=setTimeout(()=>{this.reconnectTimerId=null,this.reconnectDelayReject=null,e()},t)})}buildConnectionEventPayload(e,t){const r=this.connection.error instanceof ht?this.connection.error:void 0;return{state:e,reason:t,attempt:this.reconnectAttempts,maxAttempts:this.resolveEffectiveMaxAttempts(),isLoginPhase:this.isLoginPhase,isOnline:this.isOnline,errorCode:r?.code,errorMessage:r?.message,timestamp:Date.now()}}dispatchConnectionEvent(e,r){if(e===t&&!this.hasEverConnected)return;if(e===i&&!this.isLoggedIn)return;if(this.isLoginPhase&&(e===t||e===i))return;const s=this.buildConnectionEventPayload(e,r),n=this.connectionEventNormalizer.normalize(e,s);n&&this.eventHub.dispatch(n.eventName,n.payload)}updateStatus(e,t,r,n=!1){const i=this.connection.status!==e;(i||n)&&(i&&(this.connection.status=e,this.connection.lastConnectedAt=e===s?Date.now():void 0),r&&this.dispatchConnectionEvent(e,t),js("Connection status updated",{status:e,reason:t,attempt:this.reconnectAttempts,forceEmit:n}))}clampTimerDelay(e){return e<=0?0:Math.min(e,2**31-1)}clearTokenTimers(){this.tokenWillExpireTimerId&&(clearTimeout(this.tokenWillExpireTimerId),this.tokenWillExpireTimerId=null),this.tokenExpiredTimerId&&(clearTimeout(this.tokenExpiredTimerId),this.tokenExpiredTimerId=null)}setupTokenLifecycle(e,t,r=Date.now()){this.clearTokenTimers();const s=Math.max(t-r,0),n=r+Math.floor(.8*s);this.tokenLifecycle={token:e,issuedAt:r,expireAt:t,willExpireAt:n,willExpireEmitted:!1,expiredEmitted:!1},this.tokenWillExpireTimerId=setTimeout(()=>{this.emitTokenWillExpire()},this.clampTimerDelay(n-Date.now())),this.tokenExpiredTimerId=setTimeout(()=>{this.handleTokenExpiredDisconnect("timer")},this.clampTimerDelay(t-Date.now()))}setupTokenLifecycleFromProvision(e){if(e&&!this.tokenWillExpireTimerId&&!this.tokenExpiredTimerId)try{const t=JSON.parse(e);if(!t||"object"!=typeof t)return void Vs("Provision auth token has invalid payload");const r=Number(t.expires_in);if(!Number.isFinite(r))return void Vs("Provision auth token has invalid expires_in");this.setupTokenLifecycle(this.connection.token??this.config.token,r)}catch(t){Vs("Failed to parse provision auth token expiration",t)}}emitTokenWillExpire(){this.tokenLifecycle&&!this.tokenLifecycle.willExpireEmitted&&(this.tokenLifecycle.willExpireEmitted=!0,Vs("Token will expire"),this.eventHub.dispatch(u,void 0))}emitTokenExpired(){this.tokenLifecycle||(this.tokenLifecycle={token:this.connection.token??"",issuedAt:Date.now(),expireAt:Date.now(),willExpireAt:Date.now(),willExpireEmitted:!0,expiredEmitted:!1});const e=this.tokenLifecycle;e.expiredEmitted||(e.expiredEmitted=!0,Vs("Token expired"),this.eventHub.dispatch(l,void 0))}isTokenExpiredConnectionError(e){return e instanceof ht&&e.code===ot.AUTH_TOKEN_EXPIRED}handleTokenExpiredDisconnect(e){Vs("Connection closing because token expired",{source:e}),this.connection.error=new ht("Token expired",{code:ot.AUTH_TOKEN_EXPIRED,details:{stage:"token",source:e,retryable:!1}}),this.emitTokenExpired(),this.clearTokenTimers(),this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.closeWebSocket(O,!0,!0),this.updateStatus(t,O,!0)}startHeartbeat(e){this.heartbeatManager.start(e,()=>{this.triggerReconnect(S)},()=>{this.sendHeartbeatPing()})}stopHeartbeat(){this.heartbeatManager.stop()}async checkHeartbeatOnce(){return!!this.websocket&&this.heartbeatManager.probeOnce(this.websocket,6e4)}sendHeartbeatPing(){const e=this.msyncCodec.encodeHeartbeat();this.sendMsyncPayload(e)}async connect(e){if(!this.reconnectInProgress)if(this.connection.status!==s&&this.connection.status!==r){this.isLoginPhase=!0,this.activeLoginDeadline=e??null,this.terminalDisconnectError=null,this.reconnectPaused=!1,this.resetReconnectState(),this.connectionEventNormalizer.reset();try{await this.connectWithRetry(b,!0),this.isLoggedIn=!0}catch(n){throw this.isLoggedIn=!1,n instanceof ht&&n.code===ot.CONNECTION_LOGIN_TIMEOUT&&"login"===n.details?.stage&&(this.cancelActiveConnectionAttempt(),this.closeWebSocket(R,!1,!1),this.updateStatus(t,R,!1)),n}finally{this.isLoginPhase=!1,this.activeLoginDeadline=null}}else Vs("Connection already established or connecting")}async connectWithRetry(e,o){if(Vs("Reconnect flow requested",{reason:e,throwOnFailure:o,...this.getReconnectDiagnostic()}),this.reconnectInProgress)return void Vs("Reconnect flow skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()});if(this.connection.status===s&&this.websocket)return;if(this.reconnectPaused)return void Vs("Reconnect flow skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()});if(!this.isLoginPhase&&0===this.config.autoReconnectNumMax)return;if(!this.isOnline&&!this.isLoginPhase)return;this.reconnectInProgress=!0;let a=null,c=null,d=null;const u=this.resolveEffectiveMaxAttempts();this.connectionRetry.reset(),Vs("Reconnect flow started",{reason:e,throwOnFailure:o,maxAttempts:u,...this.getReconnectDiagnostic()});try{for(;this.connectionRetry.getAttemptCount()<u;){if(this.isLoginDeadlineExpired())throw this.requireLoginTimeoutError();if(!this.isLoginPhase&&(this.reconnectPaused||!this.isOnline||!this.isLoggedIn)){d=kh("ws");break}this.connectionRetry.recordAttempt(),this.reconnectAttempts=this.connectionRetry.getAttemptCount(),this.connection.reconnectAttempts=this.reconnectAttempts;const t=this.isLoginPhase?r:n;Vs("Reconnect attempt started",{attempt:this.reconnectAttempts,maxAttempts:u,reason:e,nextStatus:t,...this.getReconnectDiagnostic()}),this.updateStatus(t,e,!0,!0),this.prepareForConnectAttempt();try{return await this.connectOnce(),void this.handleConnectSuccess(e)}catch(l){if(a=l,this.isLoginDeadlineExpired())throw this.requireLoginTimeoutError();if(Dh(l)){d=l,Vs("Reconnect attempt cancelled",{attempt:this.reconnectAttempts,reason:e,...this.getReconnectDiagnostic()});break}if(Vs("Connection attempt failed",{attempt:this.reconnectAttempts,reason:e,error:a}),!this.isLoginPhase&&this.isTokenExpiredConnectionError(a))return void this.handleTokenExpiredDisconnect("server");if(this.isNonRetryableError(a)){c=a;break}}if(this.connectionRetry.getAttemptCount()>=u)break;if(this.reconnectPaused||!this.isOnline&&!this.isLoginPhase){Vs("Reconnect retry loop interrupted",{reason:e,attempt:this.reconnectAttempts,maxAttempts:u,...this.getReconnectDiagnostic()});break}try{await this.waitForReconnectDelay()}catch(l){if(!Dh(l))throw l;d=l,Vs("Reconnect retry delay cancelled",{reason:e,attempt:this.reconnectAttempts,...this.getReconnectDiagnostic()});break}}if(d){if(o)throw d;return}if(c){if(this.connection.error=c,o)throw this.updateStatus(t,R,!1),c;return this.reconnectPaused=!0,void this.updateStatus(t,R,!0)}if(o)throw this.updateStatus(t,R,!1),a??new ht("Connection failed",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.reconnectPaused=!0,Vs("Reconnect attempts exhausted",{reason:e,attempt:this.reconnectAttempts,maxAttempts:u,lastError:a,...this.getReconnectDiagnostic()}),this.updateStatus(i,A,!0)}finally{this.reconnectInProgress=!1,Vs("Reconnect flow finished",{reason:e,...this.getReconnectDiagnostic()})}}async connectOnce(){await this.createWebSocketConnection()}prepareForConnectAttempt(){this.cancelActiveConnectionAttempt(),this.clearReconnectTimer(),this.stopHeartbeat(),this.resetProvisionHandlers(),this.resetSyncState(),this.websocket&&this.closeWebSocket(_,!1,!1),this.msyncCodec.resetCompressionNegotiation()}handleConnectSuccess(e){this.updateStatus(s,e,!0),this.hasEverConnected=!0,this.connection.error=void 0,this.resetReconnectState(),this.offlineRecoverPending=!1,this.reconnectPaused=!1,this.sendPostProvisionInitialSync(),this.websocket&&this.startHeartbeat(this.websocket),Vs("Connection established successfully")}sendPostProvisionInitialSync(){this.sendMsyncPayload(this.msyncCodec.encodeHeartbeat()),this.sendMsyncPayload(this.msyncCodec.encodeStatisticRebuild())}triggerReconnect(e){if(Vs("Reconnect trigger received",{reason:e,...this.getReconnectDiagnostic()}),this.terminalDisconnectError)return Vs("Reconnect trigger skipped",{guard:"terminal-disconnect",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(!this.isLoggedIn)return Vs("Reconnect trigger skipped",{guard:"not-logged-in",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(this.reconnectTask)return Vs("Reconnect task reused",{reason:e,...this.getReconnectDiagnostic()}),this.reconnectTask;if(this.reconnectInProgress)return Vs("Reconnect trigger skipped",{guard:"reconnect-in-progress-without-task",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(this.reconnectPaused)return Vs("Reconnect trigger skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();this.connection.status===s&&this.websocket&&this.closeWebSocket(e,!0,!0);const t=this.connectWithRetry(e,!1).finally(()=>(this.reconnectTask===t&&(this.reconnectTask=null),this.startPendingReconnectIfNeeded()??void 0));return this.reconnectTask=t,t}recoverConnectionForSend(){return this.connection.status===s&&this.websocket?Promise.resolve():this.terminalDisconnectError||!this.isLoggedIn||!this.isOnline||this.isLoginPhase||0===this.config.autoReconnectNumMax?(Vs("Send connection recovery skipped",{guard:"connection-not-recoverable",...this.getReconnectDiagnostic()}),Promise.resolve()):this.reconnectTask?(Vs("Send connection recovery reused",this.getReconnectDiagnostic()),this.reconnectTask):(this.reconnectPaused=!1,this.resetReconnectState(),Vs("Send connection recovery requested",this.getReconnectDiagnostic()),this.triggerReconnect(_))}startPendingReconnectIfNeeded(){const e=this.pendingReconnectReason;return this.pendingReconnectReason=null,!e||null!==this.terminalDisconnectError||!this.isLoggedIn||!this.isOnline||this.connection.status===s&&this.websocket?null:(this.reconnectPaused=!1,this.resetReconnectState(),Vs("Queued reconnect recovery started",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e))}handleDisconnection(e){Vs("Connection disconnection handled",{reason:e,...this.getReconnectDiagnostic()}),this.stopHeartbeat(),this.updateStatus(t,e,!0),e!==O&&this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||this.triggerReconnect(e))}closeWebSocket(e,r,s=!0){this.websocket?(this.suppressNextCloseEvent=!0,this.websocket.close(),this.websocket=null,this.stopHeartbeat(),s&&this.updateStatus(t,e,r)):s&&this.updateStatus(t,e,r)}createWebSocketConnection(){const e=this.resolveLoginStageTimeout(this.config.connectTimeout);return e<=0?Promise.reject(this.requireLoginTimeoutError()):new Promise((t,r)=>{const s=++this.connectionAttemptGeneration,n=this.pickNextServerUrl();js("WebSocket connecting",{url:n}),this.clearSocketListeners();let i=!1,o=!1,a=null;const c=()=>{this.connectionAttemptGeneration===s&&(this.activeConnectionAttemptCancel=null)},d=e=>{i||(i=!0,a&&(clearTimeout(a),a=null),c(),r(e))};this.activeConnectionAttemptCancel=()=>{const e=kh(o?"provision":"ws");this.rejectPendingProvision(e),d(e)},a=setTimeout(()=>{Vs("WebSocket connection attempt timed out",{url:n,connectTimeout:e,...this.getReconnectDiagnostic()}),d(this.isLoginDeadlineExpired()?this.requireLoginTimeoutError():new ht("Connection timeout",{code:ot.CONNECTION_TIMEOUT,details:{stage:"ws"}}))},e),this.socketAdapter.connect({url:n,timeoutMs:e}).then(e=>{if(i||s!==this.connectionAttemptGeneration||this.reconnectPaused)return Vs("WebSocket connection result discarded",{url:n,cancelled:i||s!==this.connectionAttemptGeneration,reconnectPaused:this.reconnectPaused,...this.getReconnectDiagnostic()}),e.close(),void d(kh("ws"));a&&(clearTimeout(a),a=null),this.websocket=e,this.socketGeneration+=1,this.inboundMessageQueue=Promise.resolve(),this.attachSocketListeners(e,this.socketGeneration),o=!0,this.startProvision().then(()=>{if(this.resetProvisionHandlers(),i||s!==this.connectionAttemptGeneration||this.reconnectPaused)return Vs("Provision result discarded",{url:n,cancelled:i||s!==this.connectionAttemptGeneration,reconnectPaused:this.reconnectPaused,...this.getReconnectDiagnostic()}),this.closeWebSocket(R,!1,!1),void d(kh("provision"));i||(i=!0,a&&(clearTimeout(a),a=null),c(),t())}).catch(e=>{this.resetProvisionHandlers(),this.closeWebSocket(R,!1,!1),d(e instanceof Error?e:new Error(String(e)))})}).catch(e=>{if(i)return;const t=e instanceof ht?e:new ht("Failed to create WebSocket",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:e instanceof Error?e.message:String(e)}});this.handleConnectionError(t,R),d(t)})}).catch(e=>{if(e instanceof ht)throw e;const t=new ht("Failed to create WebSocket",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:e instanceof Error?e.message:String(e)}});throw this.handleConnectionError(t,R),t})}cancelActiveConnectionAttempt(){this.activeConnectionAttemptCancel?.()}handleWebSocketClose(e){this.suppressNextCloseEvent?this.suppressNextCloseEvent=!1:(Vs("WebSocket closed",{code:e.code,reason:e.reason}),this.provisionReject&&this.rejectProvisionAfterQueuedMessages(),this.websocket=null,this.clearSocketListeners(),this.stopHeartbeat(),this.handleDisconnection(w))}async rejectProvisionAfterQueuedMessages(){try{await this.inboundMessageQueue}catch{}this.provisionReject&&(this.provisionReject(new ht("Provision interrupted",{code:ot.CONNECTION_PROVISION_CLOSED,details:{stage:"provision"}})),this.resetProvisionHandlers())}handleConnectionError(e,t){Ks("Connection error:",e),this.connection.error=e,this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null);const r=e instanceof ht?e:new ht(e.message,{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",retryable:!0}});if(this.rejectPendingProvision(r)||this.resetProvisionHandlers(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.handleDisconnection(t)}handleTerminalConnectionError(e,r){if(Vs("Terminal connection error received",{code:e.code,message:e.message,details:e.details}),this.connection.error=e,this.terminalDisconnectError=e,this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.pendingReconnectReason=null,this.isLoggedIn=!1,this.cancelActiveConnectionAttempt(),this.resetProvisionHandlers(),this.clearReconnectTimer(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.updateStatus(t,r,!0,!0)}async handleWebSocketMessage(e,t){try{if(t!==this.socketGeneration)return;js("WebSocket message received",{dataType:typeof e});const s=await this.msyncCodec.normalizeIncoming(e);if(t!==this.socketGeneration)return;if(js("handleWebSocketMessage data",{length:s.length}),!s.length)return;const n=this.msyncCodec.decompressIncoming(s);if(!n){const e=null!==this.provisionReject;return Ks("Failed to decompress mSync payload, closing connection",{stage:e?"provision":"connected"}),void(e?(this.rejectPendingProvision(new ht("Failed to decompress Provision payload",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",cause:"decompression-failed",retryable:!0}})),this.closeWebSocket(R,!1,!1)):this.websocket?.close())}if(this.isServerNormalClosePayload(n))return void js("Ignore server normal close payload",{length:n.length});let i=null;try{i=this.msyncCodec.decodeMsync(n)}catch(r){const e=r instanceof Error?r:new Error("Failed to decode mSync payload");if(e instanceof RangeError)return void Vs("Discard invalid mSync payload",{length:n.length,message:e.message,prefixHex:Array.from(n.subarray(0,16),e=>e.toString(16).padStart(2,"0")).join(""),suffixHex:Array.from(n.subarray(Math.max(0,n.length-16)),e=>e.toString(16).padStart(2,"0")).join("")});throw Vs("Invalid mSync payload signature",{length:n.length,prefixHex:Array.from(n.subarray(0,8),e=>e.toString(16).padStart(2,"0")).join("")}),e}switch(this.heartbeatManager.markAlive(),js("handleWebSocketMessage decoded",{command:i.command}),i.command){case St:this.handleProvisionMessage(i.payload);break;case Et:this.handleLogoutMessage(i.payload);break;case Ct:this.handleNoticeMessage(i.payload);break;case Tt:this.handleUnreadMessage(i.payload);break;case _t:this.handleSyncMessage(i.payload)}}catch(r){const e=r instanceof Error?r:new Error("Failed to handle mSync payload");Ks("Failed to handle mSync payload",e),this.handleConnectionError(e,R)}}startProvision(){const e=this.resolveLoginStageTimeout(1e4);if(e<=0)return Promise.reject(this.requireLoginTimeoutError());this.provisionPromise=new Promise((e,t)=>{this.provisionResolve=e,this.provisionReject=t}),this.provisionTimeoutId&&clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=setTimeout(()=>{this.rejectPendingProvision(this.isLoginDeadlineExpired()?this.requireLoginTimeoutError():new ht("Provision timeout",{code:ot.CONNECTION_PROVISION_TIMEOUT,details:{stage:"provision",retryable:!0}}))},e);try{const e=this.msyncCodec.encodeProvision();js("startProvision provision",{length:e.length}),this.sendMsyncPayload(e)}catch{this.provisionReject?.(new ht("Provision send failed",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision"}})),this.resetProvisionHandlers()}return this.provisionPromise}handleProvisionMessage(e){const t=this.msyncCodec.decodeProvision(e);if(this.isLoginPhase&&this.activeLoginDeadline?.markProvisionReceived(),this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t.ok)this.msyncCodec.updateResource(t.resource),this.setupTokenLifecycleFromProvision(t.authToken),this.provisionResolve?.();else{Vs("Provision rejected",{statusCode:t.statusCode,reason:t.reason});const e=Wr(t.statusCode,t.reason),r=e.code===ot.UNKNOWN?ot.CONNECTION_PROVISION_REJECTED:e.code;this.provisionReject?.(new ht("Provision rejected",{code:r,details:{stage:"provision",reason:t.reason,statusCode:t.statusCode,retryable:e.retryable}}))}}handleNoticeMessage(e){const{queue:t}=this.msyncCodec.decodeNotice(e),r=t?this.getQueueId(t):null,s=!!t&&this.isSelfQueue(t),n=!!t&&this.isQueueInList(t);t&&r&&(s||n||(this.queues.push(t),1===this.queues.length&&this.sendBackqueue(t)))}handleUnreadMessage(e){const{queues:t}=this.msyncCodec.decodeUnread(e),r=t.filter(e=>this.getQueueId(e));if(r.length){r.length!==t.length&&Vs("Unread queues without usable identity were ignored",{ignoredCount:t.length-r.length}),this.startOfflineMessageSync(r);for(const e of r)this.isQueueInList(e)||this.queues.push(e);if(this.queues.length>0&&!this.currentQueue){const e=this.queues[0];e&&this.sendBackqueue(e)}}}handleSyncMessage(e){const t=this.resolveStatisticDisconnectError(this.msyncCodec.decodeSyncStatisticOperations(e));if(t)return void this.handleTerminalConnectionError(t,R);if(!this.messageReceiver)return;const r=this.messageReceiver.handleSyncPayload(e);if(js("handleSyncMessage result",{result:r}),!r)return;(void 0!==r.queue||void 0!==r.nextKey||void 0!==r.isLast)&&this.handleSyncQueueState(r)}handleSyncQueueState(e){js("[QueueSync] handleSyncQueueState",{isLast:e.isLast,nextKey:e.nextKey,queueName:e.queue?this.getQueueName(e.queue):null,queueId:e.queue?this.getQueueId(e.queue):null,queuesLength:this.queues.length});const t=this.resolveSyncQueueState(e);if(!t)return e.queue&&e.isLast?(this.queues=this.queues.filter(e=>null!==this.getQueueId(e)),void this.sendNextQueue()):e.queue&&e.nextKey?void this.sendLastSession(e.queue,e.nextKey):void 0;const{queue:r,queueId:s}=t;if(this.offlineMessageSyncing&&this.offlineMessageQueueNames.has(s)){const t=this.offlineMessageQueueCounts.get(s)??0;this.offlineMessageQueueCounts.set(s,t+e.messages.length),this.offlineMessageTotalCount+=e.messages.length}const n=e.nextKey;if(e.isLast)return this.finishOfflineMessageQueue(s),this.removeQueueEntry(r),this.nextKey=null,this.currentQueueId=null,this.currentQueue=null,void this.sendNextQueue();if(n){if(n!==this.nextKey||!this.isSameQueue(r,this.currentQueue))return this.nextKey=n,this.currentQueueId=s,this.currentQueue=r,void this.sendLastSession(r,n);this.removeQueueEntry(r),this.sendNextQueue()}}resolveSyncQueueState(e){const t=e.queue&&"object"==typeof e.queue?e.queue:void 0,r=t?this.getQueueName(t):null,s=t?this.getQueueId(t):null,n=void 0!==t&&null!==s&&(0===this.queues.length||this.queues.some(e=>this.isSameQueue(e,t)));if(t&&s&&n)return{queue:t,queueId:s};const i=this.currentQueue&&this.queues.some(e=>this.isSameQueue(e,this.currentQueue))?this.currentQueue:void 0,o=this.currentQueueId?this.queues.find(e=>this.getQueueId(e)===this.currentQueueId):void 0,a=i??o??this.queues[0],c=a?this.getQueueName(a):null,d=a?this.getQueueId(a):null;return a&&d?(Vs("Sync queue response did not match a tracked queue, fallback to local queue",{responseQueueName:r,responseQueueId:s,fallbackQueueName:c,fallbackQueueId:d,currentQueueId:this.currentQueueId,firstQueueName:this.getQueueName(this.queues[0]??{}),firstQueueId:this.getQueueId(this.queues[0]??{}),isLast:e.isLast,hasNextKey:Boolean(e.nextKey)}),{queue:a,queueId:d}):null}handleLogoutMessage(e){const t=this.msyncCodec.decodeLogout(e);Vs("Logout message received",t)}resolveStatisticDisconnectError(e){for(const t of e)switch(t.operation){case 1:return new ht("User has been removed",{code:ot.USER_REMOVED,details:{stage:"statistics",operation:t.operation,retryable:!1}});case 2:return new ht("The user is already logged on another device",{code:ot.USER_LOGIN_ANOTHER_DEVICE,details:{stage:"statistics",operation:t.operation,retryable:!1,...t.reason?{loginInfoCustomExt:t.reason}:{}}});case 3:return new ht("The user was kicked by changing password",{code:ot.USER_KICKED_BY_CHANGE_PASSWORD,details:{stage:"statistics",operation:t.operation,retryable:!1}});case 4:return new ht("The user was kicked by other device",{code:ot.USER_KICKED_BY_OTHER_DEVICE,details:{stage:"statistics",operation:t.operation,retryable:!1}})}return null}resetProvisionHandlers(){this.provisionResolve=null,this.provisionReject=null,this.provisionPromise=null}rejectPendingProvision(e){const t=this.provisionReject;return!!t&&(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t(e),this.resetProvisionHandlers(),!0)}disconnect(){return this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.clearTokenTimers(),this.tokenLifecycle=null,this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.terminalDisconnectError=null,this.offlineRecoverPending=!1,this.closeWebSocket(w,!0,!0),this.updateStatus(t,w,!0),this.resetSyncState(),this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connection.error=void 0,this.hasEverConnected=!1,this.connectionEventNormalizer.reset(),Vs("Connection disconnected"),Promise.resolve()}destroy(){this.disconnect(),this.eventHub.removeEventHandler(this.internalHandlerId)}resolveSocketAdapter(e){return xd(e.socketAdapter)}attachSocketListeners(e,t){this.clearSocketListeners(),this.socketDisposers=[e.onMessage(r=>{this.websocket===e&&(this.inboundMessageQueue=this.inboundMessageQueue.catch(()=>{}).then(()=>this.handleWebSocketMessage(r,t)))}),e.onError(()=>{if(this.websocket!==e)return;Vs("WebSocket error",{stage:"ws"});const t=new ht("WebSocket connection error",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.handleConnectionError(t,R)}),e.onClose(t=>{this.websocket===e&&this.handleWebSocketClose(t)})]}clearSocketListeners(){for(const e of this.socketDisposers)e();this.socketDisposers=[]}sendMsyncPayload(e){if(this.websocket&&this.websocket.readyState===ln)try{const t=this.msyncCodec.prepareOutgoing(e);js("WebSocket send payload",{length:t.length}),Promise.resolve(this.websocket.send(t)).catch(e=>{Ks("Failed to send mSync payload",e),this.websocket?.close()})}catch(t){Ks("Failed to send mSync payload",t),this.websocket?.close()}}sendBackqueue(e){this.currentQueue=e,this.currentQueueId=this.getQueueId(e),this.nextKey=null;const t=this.msyncCodec.encodeBackQueue(e);js("sendBackqueue payload",{length:t.length}),this.sendMsyncPayload(t)}sendLastSession(e,t){js("sendLastSession queue",{queueName:this.getQueueName(e),nextKey:t});const r=this.msyncCodec.encodeLastSession(e,t);this.sendMsyncPayload(r)}sendNextQueue(){js("sendNextQueue queues",{size:this.queues.length});const e=this.queues[0];e&&this.sendBackqueue(e)}removeQueueEntry(e){const t=this.queues.findIndex(t=>this.isSameQueue(t,e));t>=0&&this.queues.splice(t,1)}startOfflineMessageSync(e){const t=new Set;for(const r of e){const e=this.getQueueId(r);e&&t.add(e)}if(0!==t.size){for(const e of t)this.offlineMessageQueueNames.add(e);if(!this.offlineMessageSyncing){this.offlineMessageSyncing=!0,this.offlineMessageSyncLifecycleActive=!this.offlineMessageSyncLifecycleDispatched,this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleDispatched=!0),this.offlineMessageTotalCount=0,this.offlineMessageQueueCounts.clear(),this.offlineMessageQueueReports.clear(),this.offlineMessageReport=Uh({operationName:"MSYNC_SYNCOFFLINEMESSAGE",operationType:"MESSAGE"});for(const e of t){this.offlineMessageQueueCounts.set(e,0);const t=this.offlineMessageReport?.startRequest({requestName:"MSYNC_SYNCOFFLINEMESSAGE",method:"WS",url:e});t&&this.offlineMessageQueueReports.set(e,t)}this.offlineMessageSyncLifecycleActive&&this.eventHub.dispatch(h,void 0)}}}finishOfflineMessageQueue(e){if(!this.offlineMessageSyncing)return;const t=this.offlineMessageQueueCounts.get(e)??0;this.offlineMessageQueueReports.get(e)?.finish({code:200,success:!0,resultCount:t}),this.offlineMessageQueueReports.delete(e),this.offlineMessageQueueNames.delete(e),this.offlineMessageQueueNames.size>0||(this.offlineMessageSyncing=!1,this.offlineMessageReport?.finish({code:0,success:!0,resultCount:this.offlineMessageTotalCount}),this.offlineMessageReport=void 0,this.offlineMessageQueueReports.clear(),this.offlineMessageQueueCounts.clear(),this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleActive=!1,this.eventHub.dispatch(p,void 0)))}isQueueInList(e){return this.queues.some(t=>this.isSameQueue(t,e))}isSelfQueue(e){const t=this.getQueueName(e),r=this.getQueueResource(e),s=this.msyncCodec.getContext();return t===s.userId&&r===s.clientResource}getQueueName(e){return"string"==typeof e.name&&e.name.trim().length>0?e.name:null}getQueueResource(e){return this.getQueueField(e,"clientResource")}getQueueId(e){const t=this.getQueueName(e);if(t)return`name:${t}`;const r=this.getQueueField(e,"domain"),s=this.getQueueResource(e);if(r)return`domain:${r}|resource:${s??""}`;if(s)return`resource:${s}`;const n=this.getQueueField(e,"appKey");return n?`appKey:${n}`:null}getQueueField(e,t){const r=e[t];return"string"==typeof r&&r.trim().length>0?r:null}isSameQueue(e,t){if(!e||!t)return!1;const r=this.getQueueId(e),s=this.getQueueId(t);return null!==r&&r===s}resetSyncState(){this.queues=[],this.currentQueueId=null,this.currentQueue=null,this.nextKey=null,this.offlineMessageSyncing=!1,this.offlineMessageSyncLifecycleDispatched=!1,this.offlineMessageSyncLifecycleActive=!1,this.offlineMessageQueueNames.clear(),this.offlineMessageReport?.discard(),this.offlineMessageReport=void 0,this.offlineMessageQueueReports.clear(),this.offlineMessageQueueCounts.clear(),this.offlineMessageTotalCount=0}}const xh=new class{constructor(){this.store=new Map}set(e,t){e&&this.store.set(e,t)}get(e){if(e)return this.store.get(e)}consume(e){const t=this.get(e);return t&&this.store.delete(e),t}delete(e){e&&this.store.delete(e)}clear(){this.store.clear()}},Fh=e=>{if((e=>"undefined"!=typeof File&&e instanceof File)(e)){if("undefined"==typeof URL||"function"!=typeof URL.createObjectURL)return;return URL.createObjectURL(e)}return(e=>"object"==typeof e&&null!==e&&"path"in e&&"string"==typeof e.path)(e)?e.path:(e=>"object"==typeof e&&null!==e&&"uri"in e&&"string"==typeof e.uri)(e)?e.uri:void 0},Bh=()=>{const e=fn().crypto;return e&&"function"==typeof e.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},Gh=new Uint8Array([99,109]),qh=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),$h=e=>Array.isArray(e)&&e.every(qh),jh=e=>"string"==typeof e?e:void 0,Vh=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Kh=e=>{const t=new Uint8Array(4);return t[0]=e>>>24&255,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=255&e,t},zh=(e,t)=>{const r=e[t],s=e[t+1],n=e[t+2],i=e[t+3];if("number"!=typeof r||"number"!=typeof s||"number"!=typeof n||"number"!=typeof i)throw new gt("Combine payload length header is invalid",{code:ot.COMBINE_PARSE_FAILED});return r<<24|s<<16|n<<8|i},Hh=e=>{let t=0;for(let r=2;r<e.length;r+=1)r%2==1&&(t^=e[r]??0);return t},Wh=(e,t)=>{const r=Kd().lookupType(e).decode(t);if(!qh(r))throw new Error(`${e} decoded result is invalid`);return r},Jh=e=>qh(e)&&"string"==typeof e.name?e.name:"",Qh=(e,t,r)=>{const s=($h(e.contents)?e.contents:[])[0];if(!s)throw new Error("MessageBody contents is empty");const n=(e=>{const t=Vh(e.type)??Dt,r=Boolean(jh(e.remotePath))||Boolean(jh(e.title))||Boolean(jh(e.summary))||(Vh(e.combineLevel)??0)>0,s=t===Dt&&0===e.subType&&r;if(t===jt||s){const t=Vh(e.combineLevel)??0;return{type:"combine",body:{title:jh(e.title)??"",summary:jh(e.summary)??"",filename:jh(e.displayName)??"combine",filetype:"application/octet-stream",url:jh(e.remotePath),secret:jh(e.secretKey),fileLength:Vh(e.fileLength),combineLevel:t},combineLevel:t}}if(t===Dt)return{type:"text",body:{content:jh(e.text)??""}};if(t===qt)return{type:"cmd",body:{action:jh(e.action)??""}};if(t===$t){const t=eu($h(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:jh(e.customEvent)??"",params:t}}}if(t===Ft)return{type:"location",body:{latitude:Vh(e.latitude)??0,longitude:Vh(e.longitude)??0,address:jh(e.address),buildingName:jh(e.buildingName)}};if(t===Pt){const t=qh(e.size)?e.size:{},r=jh(e.remotePath)??"",s=Ts(r),n=jh(e.thumbnailRemotePath),i=Ss(e.imageType)===hs;return{type:"image",body:{localUrl:"",filename:jh(e.displayName)??"image",filetype:"application/octet-stream",width:Vh(t.width)??0,height:Vh(t.height)??0,isGif:1===e.subType,isOriginalImage:i,originalImageUrl:s.originalImageUrl,bigImageUrl:s.bigImageUrl,secret:jh(e.secretKey),fileLength:Vh(e.fileLength),thumbnailUrl:n??s.thumbnailUrl}}}if(t===xt){const t=qh(e.size)?e.size:{};return{type:"video",body:{url:jh(e.remotePath)??"",filename:jh(e.displayName)??"video",filetype:"application/octet-stream",duration:Vh(e.duration)??0,width:Vh(t.width),height:Vh(t.height),secret:jh(e.secretKey),fileLength:Vh(e.fileLength),thumbnailUrl:jh(e.thumbnailRemotePath)}}}if(t===Bt)return{type:"voice",body:{url:jh(e.remotePath)??"",filename:jh(e.displayName)??"voice",filetype:"application/octet-stream",duration:Vh(e.duration)??0,secret:jh(e.secretKey),fileLength:Vh(e.fileLength)}};if(t===Gt)return{type:"file",body:{url:jh(e.remotePath)??"",filename:jh(e.displayName)??"file",filetype:"application/octet-stream",secret:jh(e.secretKey),fileLength:Vh(e.fileLength)}};return null})(s);if(!n)throw new Error("MessageBody content type is unsupported");const i=Jh(e.from)||Jh(r?.from)||`unknown-${t}`,o=Jh(e.to)||Jh(r?.to)||`unknown-${t}`,a=(c=e.type)===At?"groupChat":c===Nt?"chatRoom":"singleChat";var c;const d=o||i,u=Number(Yd(r?.timestamp))||Date.now(),l=eu($h(e.ext)?e.ext:void 0),h={msgServerId:Yd(r?.id),msgLocalId:"",type:n.type,sender:{userId:i},conversationId:d,conversationType:a,timestamp:u,body:n.body,ext:l};return"number"==typeof n.combineLevel&&(h.body.combineLevel=n.combineLevel),h},Zh=(e,t)=>{const r=[];try{const n=Wh("easemob.pb.Meta",e),i=(s=n.payload)instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):ArrayBuffer.isView(s)?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):void 0;if(i&&i.length>0){const e=Wh("easemob.pb.MessageBody",i);return Qh(e,t,n)}r.push("Meta payload is empty")}catch(n){r.push(n instanceof Error?n.message:String(n))}var s;try{const r=Wh("easemob.pb.MessageBody",e);return Qh(r,t)}catch(n){r.push(n instanceof Error?n.message:String(n))}try{const r=Wh("easemob.pb.MessageBody.Content",e);return Qh({type:Rt,from:{name:`unknown-${t}`},to:{name:`unknown-${t}`},contents:[r],ext:[]},t)}catch(n){r.push(n instanceof Error?n.message:String(n))}throw new Error(r.join("; "))},Yh=(e,t)=>{const r=Hs(e);try{const e=JSON.parse(r);if(!qh(e))throw new gt("Combine payload item is invalid",{code:ot.COMBINE_PARSE_FAILED,details:{index:t}});return e}catch(s){if(s instanceof gt)throw s;try{return Zh(e,t)}catch(n){throw new gt("Combine payload item parse failed",{code:ot.COMBINE_PARSE_FAILED,details:{index:t,cause:s instanceof Error?s.message:String(s),protobufCause:n instanceof Error?n.message:String(n)}})}}},Xh=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ep=(e,t,r)=>{throw new mt(e,{code:r,details:{fields:[{path:t,message:e,rule:"invalid_format"}]}})},tp=e=>{if("combine"!==e.type)return 0;const t=e.combineLevel;return"number"==typeof t?t:Xh(e.body)&&"number"==typeof e.body.combineLevel?e.body.combineLevel:0},rp=(e,t)=>{if(e.sender.userId||ep(`messageList[${t}] sender.userId is required`,`messageList[${t}].sender.userId`,ot.COMBINE_INVALID_INPUT),e.conversationId&&["singleChat","groupChat","chatRoom"].includes(e.conversationType)||ep(`messageList[${t}] conversation is invalid`,`messageList[${t}].conversationId`,ot.COMBINE_INVALID_INPUT),(!Number.isInteger(e.timestamp)||e.timestamp<=0)&&ep(`messageList[${t}] timestamp must be positive integer`,`messageList[${t}].timestamp`,ot.COMBINE_INVALID_INPUT),Xh(e.body)||ep(`messageList[${t}] body must be object`,`messageList[${t}].body`,ot.COMBINE_INVALID_INPUT),"combine"===e.type){const r=tp(e);(!Number.isInteger(r)||r<0)&&ep(`messageList[${t}] combineLevel is invalid`,`messageList[${t}].combineLevel`,ot.COMBINE_INVALID_INPUT),r>10&&ep(`messageList[${t}] combineLevel exceeds limit`,`messageList[${t}].combineLevel`,ot.COMBINE_LEVEL_EXCEEDED)}},sp=(e,t=300)=>{(!Number.isInteger(e)||e<=0)&&ep("messageList must not be empty","messageList",ot.COMBINE_INVALID_INPUT),(!Number.isInteger(t)||t<=0||t>300)&&ep("max items is invalid","maxItems",ot.COMBINE_INVALID_INPUT),e>t&&ep(`messageList max length is ${t}`,"messageList",ot.COMBINE_ITEM_LIMIT_EXCEEDED)},np=e=>{sp(e.length);for(let t=0;t<e.length;t+=1){const r=e[t];void 0!==r?rp(r,t):ep(`messageList[${t}] is required`,`messageList[${t}]`,ot.COMBINE_INVALID_INPUT)}},ip=e=>{let t=0;for(const r of e){if("combine"!==r.type)continue;const e=tp(r);e>t&&(t=e)}return t+1},op=e=>{(!Number.isInteger(e)||e<=0)&&ep("combineLevel must be positive integer","combineLevel",ot.COMBINE_INVALID_INPUT),e>10&&ep("combineLevel must be <= 10","combineLevel",ot.COMBINE_LEVEL_EXCEEDED)},ap=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class cp{constructor(e,t,r,s){this.websocket=null,this.pendingMessages=new Map,this.ackTimeout=15e3,this.attachmentUploader=null,this.messageReportCount=0,this.chatRoomReportCount=0,this.messageReportSaturated=!1,this.chatRoomReportSaturated=!1,this.websocket=t,this.eventHub=r,this.msyncCodec=e,this.attachmentUploader=s??null}updateAuthToken(e){this.attachmentUploader?.updateAuthToken(e)}async sendMessage(e,t){const r=this.msyncCodec.toProtocolId(e.msgLocalId);if(it(e))throw new ft("Stream message send is not supported",{code:ot.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:e.msgLocalId,retryable:!1}});if(!this.websocket||this.websocket.readyState!==ln){const t=this.msyncCodec.toProtocolId(e.msgLocalId);throw new ft("WebSocket is not connected",{code:ot.MESSAGE_NOT_CONNECTED,details:{msgLocalId:e.msgLocalId,protocolId:t,retryable:!0}})}let s={...e,sendStatus:"sending"};Ju(e,s),js("Message send queued",{msgLocalId:e.msgLocalId,protocolId:r,type:e.type,conversationType:e.conversationType,conversationId:e.conversationId});try{const e="combine"===s.type?this.prepareCombineMessage(s):s,r={...this.attachmentUploader?await this.attachmentUploader.prepareMessage(e,t):e,sendStatus:"sending"};Ju(s,r),s=r,t?.onSending?.(r);const n=await this.doSendMessage(r);return t?.onSuccess?.(n),n}catch(n){const e={...s,sendStatus:"failed"};throw Ju(s,e),t?.onFailed?.(e,n instanceof Error?n:new Error(String(n))),n}}async sendAction(e,t){const r=this.msyncCodec.toProtocolId(`${e.kind}:${e.messageId??e.conversationId}:${Date.now()}`);"clearAllConversationUnreadMessageCount"===e.kind&&js("Clear-all unread action encode started",{operation:"message.action.clear-all-unread.encode",protocolId:r,conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:e.sendToPeer,clearAllUnreadMessageCount:e.clearAllUnreadMessageCount});const s=this.msyncCodec.encodeActionMessage(e,r);"clearAllConversationUnreadMessageCount"===e.kind&&js("Clear-all unread action encoded",{operation:"message.action.clear-all-unread.encoded",protocolId:r,payloadBytes:s.byteLength});const n="recall"===e.kind?"MSYNC_RECALLMESSAGE":"update"===e.kind?"MSYNC_MODIFYMESSAGE":`MSYNC_${e.kind.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()}`;return this.sendProtocolPayload(r,s,t,this.createPendingDataReport({category:"message",operationName:n,operationType:"MESSAGE",requestName:n,msgId:e.messageId,messageType:ap(e.conversationType)}))}async sendChatRoomOperation(e,t){const r=this.msyncCodec.toProtocolId(`chatroom:${e.operation}:${e.chatRoomId}:${Date.now()}`),s=this.msyncCodec.encodeChatRoomOperation(e,r),n="join"===e.operation?"CHATROOM_JOINCAHTROOM":"CHATROOM_LEAVECAHTROOM";return this.sendProtocolPayload(r,s,t,this.createPendingDataReport({category:"chatroom",operationName:n,operationType:"CHATROOM",requestName:n,msgId:e.chatRoomId}))}async doSendMessage(e){const t=this.createPendingDataReport({category:"message",operationName:"MSYNC_SENDMESSAGE",operationType:"SENDMESSAGE",requestName:"MSYNC_SENDMESSAGE",msgId:e.msgLocalId,messageType:ap(e.conversationType)});return new Promise((r,s)=>{const n=this.msyncCodec.toProtocolId(e.msgLocalId),i=setTimeout(()=>{this.pendingMessages.delete(n),this.finishPendingDataReport(t,{code:ot.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),s(new ft("Message ACK timeout",{code:ot.MESSAGE_ACK_TIMEOUT,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(n,{kind:"message",message:e,protocolId:n,timeoutId:i,resolve:e=>{clearTimeout(i),r(e)},reject:e=>{clearTimeout(i),s(e)},report:t});try{if(!this.websocket||this.websocket.readyState!==ln)throw new ft("WebSocket is not connected",{code:ot.MESSAGE_NOT_CONNECTED,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}});const r=this.msyncCodec.encodeChatMessage(e,n),o=this.msyncCodec.prepareOutgoing(r);Promise.resolve(this.websocket.send(o)).catch(r=>{const o=r instanceof Error?r.message:String(r);this.pendingMessages.delete(n),clearTimeout(i),this.finishPendingDataReport(t,{code:-1,success:!1,description:o}),Vs("Message send socket failure",{msgLocalId:e.msgLocalId,protocolId:n,websocketReadyState:this.websocket?.readyState??null,cause:o}),s(new ft(`WebSocket send failed: ${o}`,{code:ot.MESSAGE_NOT_CONNECTED,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0,cause:o}}))}),js("Message sent",{msgLocalId:e.msgLocalId,protocolId:n})}catch(o){if(this.pendingMessages.delete(n),clearTimeout(i),this.finishPendingDataReport(t,{code:o instanceof ft?o.code:ot.MESSAGE_ENCODE_FAILED,success:!1,description:o instanceof Error?o.message:String(o)}),o instanceof ft)throw o;throw new ft("Message encode failed",{code:ot.MESSAGE_ENCODE_FAILED,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}})}})}async sendProtocolPayload(e,t,r,s){return new Promise((n,i)=>{const o=setTimeout(()=>{this.pendingMessages.delete(e),this.finishPendingDataReport(s,{code:ot.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),i(new ft("Message ACK timeout",{code:ot.MESSAGE_ACK_TIMEOUT,details:{protocolId:e,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(e,{kind:"action",protocolId:e,timeoutId:o,createAckError:r,resolve:n,reject:i,report:s});try{if(!this.websocket||this.websocket.readyState!==ln)throw new ft("WebSocket is not connected",{code:ot.MESSAGE_NOT_CONNECTED,details:{protocolId:e,retryable:!0}});const r=this.msyncCodec.prepareOutgoing(t);Promise.resolve(this.websocket.send(r)).catch(t=>{const r=t instanceof Error?t.message:String(t);this.pendingMessages.delete(e),clearTimeout(o),this.finishPendingDataReport(s,{code:-1,success:!1,description:r}),i(new ft(`WebSocket action send failed: ${r}`,{code:ot.MESSAGE_NOT_CONNECTED,details:{protocolId:e,retryable:!0,cause:r}}))})}catch(a){if(this.pendingMessages.delete(e),clearTimeout(o),this.finishPendingDataReport(s,{code:a instanceof ft?a.code:ot.MESSAGE_ENCODE_FAILED,success:!1,description:a instanceof Error?a.message:String(a)}),a instanceof ft)throw a;i(new ft("Message encode failed",{code:ot.MESSAGE_ENCODE_FAILED,details:{protocolId:e,retryable:!1}}))}})}prepareCombineMessage(e){const t=e.body,r=t.messageList??[];np(r);const s=ip(r);op(s);const n=((e,t)=>{try{const r=e.map((e,r)=>{const s=t(e,r);if(0===s.length)throw new ft("Combine payload item encode failed",{code:ot.COMBINE_ENCODE_FAILED,details:{index:r}});return s}),s=Gh.length+r.reduce((e,t)=>e+4+t.length,0)+1,n=new Uint8Array(s);let i=0;n.set(Gh,i),i+=Gh.length;for(const e of r){const t=Kh(e.length);n.set(t,i),i+=t.length,n.set(e,i),i+=e.length}const o=Hh(n.subarray(0,n.length-1));return n[n.length-1]=o,n}catch(r){if(r instanceof ft)throw r;throw new ft("Combine payload encode failed",{code:ot.COMBINE_ENCODE_FAILED,details:{cause:r instanceof Error?r.message:String(r)}})}})(r,e=>this.msyncCodec.encodeCombineMessageMeta(e)),i=new ArrayBuffer(n.byteLength);new Uint8Array(i).set(n);const o=new File([i],t.filename||"combine",{type:t.filetype||"application/octet-stream"}),a=Fh(o);if(!a&&!this.attachmentUploader)throw new ft("Combine payload local url generation failed",{code:ot.COMBINE_ENCODE_FAILED});xh.set(e.msgLocalId,o);const c={...e,body:{...t,combineLevel:s,fileLength:n.byteLength,filename:t.filename||"combine",filetype:t.filetype||"application/octet-stream",url:a??t.url}};return Ju(e,c),el(e,c),c}handleAck(e,t,r,s){const n=this.pendingMessages.get(e);if(!n)return void js("Received ACK without a tracked pending message",{protocolId:e});if("action"===n.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:200,success:!0}),void n.resolve({protocolId:e,serverId:t??"",statusCode:0,chatRoomInfo:s});const i={...n.message,...this.resolveReplacedMessage(n.message,r),sendStatus:"sent",msgServerId:t||r?.msgServerId||n.message.msgServerId};Ju(n.message,i),this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:200,success:!0}),"image"!==i.type&&"video"!==i.type&&"voice"!==i.type&&"file"!==i.type&&"combine"!==i.type||xh.delete(i.msgLocalId),js("Message ACK matched",{protocolId:e,msgLocalId:i.msgLocalId,msgServerId:i.msgServerId??null,type:i.type,conversationType:i.conversationType,conversationId:i.conversationId}),this.eventHub.dispatch(I,i),n.resolve(i)}resolveReplacedMessage(e,t){return t?{type:t.type,body:t.body,ext:t.ext,timestamp:t.timestamp||e.timestamp}:{}}handleSendError(e,t){const r=this.pendingMessages.get(e);if(!r)return;if("action"===r.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t instanceof ft?t.code:-1,success:!1,description:t.message}),void r.reject(t);const s={...r.message,sendStatus:"failed"};Ju(r.message,s),this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t instanceof ft?t.code:-1,success:!1,description:t.message}),Vs("Message send failed after ACK/error",{protocolId:e,msgLocalId:s.msgLocalId,type:s.type,conversationType:s.conversationType,conversationId:s.conversationId,error:t.message}),r.reject(t)}handleAckFailure(e,t,r,s){const n=this.pendingMessages.get(e);if(n)return"action"===n.kind?(this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:t,success:!1,description:r??s.message}),void n.reject(n.createAckError?.(t,r)??s)):void this.handleSendError(e,s)}setWebSocket(e){this.websocket=e}destroy(){for(const[e,t]of this.pendingMessages)clearTimeout(t.timeoutId),this.finishPendingDataReport(t.report,{code:-1,success:!1,description:"Message sender destroyed"}),t.reject(new ft("Message sender destroyed",{code:ot.MESSAGE_SENDER_DESTROYED,details:"message"===t.kind?{msgLocalId:t.message.msgLocalId,protocolId:e,retryable:!1}:{protocolId:e,retryable:!1}}));this.pendingMessages.clear()}createPendingDataReport(e){if(("message"===e.category?this.messageReportCount:this.chatRoomReportCount)>=_h){return void(("message"===e.category?this.messageReportSaturated:this.chatRoomReportSaturated)||(Vs("DataReport correlation limit reached",{category:e.category}),"message"===e.category?this.messageReportSaturated=!0:this.chatRoomReportSaturated=!0))}const t=Uh({operationName:e.operationName,operationType:e.operationType,msgId:e.msgId,messageType:e.messageType});if(t)return"message"===e.category?this.messageReportCount+=1:this.chatRoomReportCount+=1,{category:e.category,operation:t,request:t.startRequest({requestName:e.requestName,method:"WS",url:""}),released:!1}}finishPendingDataReport(e,t){e&&!e.released&&(e.released=!0,e.request.finish(t),e.operation.finish(t),"message"===e.category?(this.messageReportCount=Math.max(0,this.messageReportCount-1),this.messageReportCount<_h&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<_h&&(this.chatRoomReportSaturated=!1)))}}class dp{constructor(e){this.sessions=new Map,this.ttlMs=e?.ttlMs??3e5,this.maxSessions=e?.maxSessions??100}getOrCreate(e){this.evictStale();const t=this.sessions.get(e);if(t)return t.lastActivityTs=Date.now(),t;this.sessions.size>=this.maxSessions&&this.evictOldest();const r={msgId:e,startSeq:null,lastDispatchedSeq:-1,fullText:"",completed:!1,chunksBySeq:new Map,lastActivityTs:Date.now()};return this.sessions.set(e,r),r}get(e){return this.sessions.get(e)}addChunk(e,t){const r=this.getOrCreate(e),s=t.stream.seq;return r.chunksBySeq.has(s)?{duplicate:!0,session:r}:(r.chunksBySeq.set(s,t),r.lastActivityTs=Date.now(),t.stream.status!==nt.START&&t.stream.status!==nt.START_COMPLETED||null!==r.startSeq||(r.startSeq=s),{duplicate:!1,session:r})}getSequentialChunks(e){const t=this.sessions.get(e);if(!t||t.completed||null===t.startSeq)return[];let r=t.lastDispatchedSeq<t.startSeq?t.startSeq:t.lastDispatchedSeq+1;const s=[];for(;t.chunksBySeq.has(r);){const e=t.chunksBySeq.get(r);if(!e)break;s.push(e),r+=1}return s}markDispatched(e,t,r){const s=this.sessions.get(e);if(!s)return;const n=t.stream.seq;s.lastDispatchedSeq=Math.max(s.lastDispatchedSeq,n),s.fullText=r,s.chunksBySeq.delete(n)}markCompleted(e,t,r){const s=this.getOrCreate(e);s.completed=!0,s.completedReason=t,s.fullText=r}clear(e){this.sessions.delete(e)}clearAll(){this.sessions.clear()}evictStale(){const e=Date.now();for(const[t,r]of this.sessions)e-r.lastActivityTs>this.ttlMs&&this.sessions.delete(t)}evictOldest(){let e=null,t=1/0;for(const[r,s]of this.sessions)s.lastActivityTs<t&&(t=s.lastActivityTs,e=r);e&&this.sessions.delete(e)}}class up{constructor(e,t){this.completedIds=new Set,this.eventHub=e,this.cache=t??new dp}handle(e){const t=this.resolveMessageId(e);if(!t)return void Vs("stream message id missing, skip dispatch");if(this.completedIds.has(t))return void js("stream message already completed, ignore",{msgId:t});if(e.stream.status===nt.FULL)return void this.handleFullChunk(t,e);const r=this.cache.get(t);if(r?.completed)return void js("stream session completed, ignore chunk",{msgId:t,seq:e.stream.seq});const{duplicate:s}=this.cache.addChunk(t,e);s?js("stream duplicate chunk ignored",{msgId:t,seq:e.stream.seq}):e.stream.errorType>0?this.dispatchServerError(t,e):this.dispatchSequentialChunks(t)}destroy(){this.cache.clearAll(),this.completedIds.clear()}dispatchSequentialChunks(e){const t=this.cache.getSequentialChunks(e);if(0!==t.length)for(const r of t){const t=this.cache.get(e);if(!t)return;const s=t.fullText,n=r.stream.deltaText,i=`${s}${n}`,o=r.stream.errorType>0?nt.ERROR:r.stream.status,a=this.buildDispatchMessage(r,{status:o,fullText:i,deltaText:n});if(this.eventHub.dispatch(U,a),this.cache.markDispatched(e,r,i),o===nt.START_COMPLETED||o===nt.COMPLETED||o===nt.ERROR){const t=o===nt.ERROR?"timeout_error":"normal";return this.cache.markCompleted(e,t,i),this.cache.clear(e),void this.markCompleted(e)}}else js("stream chunks pending for missing seq",{msgId:e})}handleFullChunk(e,t){const r=this.cache.get(e),s=r?.fullText??"",n=this.resolveFullText(t,s),i=this.resolveDeltaText(s,n,t.stream.deltaText),o=!r||-1===r.lastDispatchedSeq&&0===r.chunksBySeq.size,a=t.stream.errorType>0?nt.ERROR:o?nt.START_COMPLETED:nt.COMPLETED,c=this.buildDispatchMessage(t,{status:a,fullText:n,deltaText:i});this.eventHub.dispatch(U,c);const d=a===nt.ERROR?"timeout_error":"fallback_full";this.cache.markCompleted(e,d,n),this.cache.clear(e),this.markCompleted(e)}dispatchServerError(e,t){const r=this.cache.get(e),s=r?.fullText??"",n=this.resolveFullText(t,s),i=this.resolveDeltaText(s,n,t.stream.deltaText),o=this.buildDispatchMessage(t,{status:nt.ERROR,fullText:n,deltaText:i});this.eventHub.dispatch(U,o),this.cache.markCompleted(e,"timeout_error",n),this.cache.clear(e),this.markCompleted(e)}buildDispatchMessage(e,t){return{...e,body:{...e.body,content:t.fullText},stream:{...e.stream,status:t.status,fullText:t.fullText,deltaText:t.deltaText}}}resolveMessageId(e){return e.msgServerId&&e.msgServerId.length>0?e.msgServerId:e.msgLocalId}resolveFullText(e,t){const r=e.stream.fullText;if(r&&r.length>=t.length)return r;const s=e.body.content;return s&&s.length>=t.length?s:`${t}${e.stream.deltaText}`}resolveDeltaText(e,t,r){return t.startsWith(e)?t.slice(e.length):r}markCompleted(e){if(this.completedIds.add(e),this.completedIds.size<=2048)return;const t=this.completedIds.values().next().value;t&&this.completedIds.delete(t)}}class lp{constructor(e=100){this.seenIds=new Set,this.orderedIds=[],this.limit=Math.max(1,Math.floor(e))}checkAndRecord(e){if(!e)return!1;if(this.seenIds.has(e))return!0;for(this.seenIds.add(e),this.orderedIds.push(e);this.orderedIds.length>this.limit;){const e=this.orderedIds.shift();e&&this.seenIds.delete(e)}return!1}clear(){this.seenIds.clear(),this.orderedIds.length=0}size(){return this.seenIds.size}}const hp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class pp{constructor(e,t,r){this.eventHub=r,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new up(r),this.messageContexts=new Map,this.recentMessageIds=new lp(100),this.enableDeliveryReceipt=!1}setDeliveryAckEnabled(e){this.enableDeliveryReceipt=e}rememberSentMessageContext(e){"sent"===e.sendStatus&&(this.rememberMessageContext(e),this.recentMessageIds.checkAndRecord(this.resolveMessageContextId(e)))}handleSyncPayload(e){try{js("handleSyncPayload payload",{length:e.length});const t=this.msyncCodec.decodeSync(e);js("handleSyncPayload result",{ack:Boolean(t.ack),messageCount:t.messages.length});const{ack:r,messages:s}=t;t.notifies&&t.notifies.length>0&&this.handleNotifies(t.notifies),r&&(js("Decoded sync ACK",{ok:r.ok,protocolId:r.protocolId,serverId:r.serverId??null,statusCode:r.statusCode??null,reason:r.reason??null,hasReplacedMessage:Boolean(t.replacedMessage)}),this.handleAck(r,t.replacedMessage));for(const e of s)this.dispatchMessage(e);return t}catch(t){Ks("Failed to decode sync payload",t)}return null}handleAck(e,t){if(e.ok)return js("ACK accepted",{protocolId:e.protocolId,serverId:e.serverId??null,hasReplacedMessage:Boolean(t)}),void(e.chatRoomInfo?this.messageSender.handleAck(e.protocolId,e.serverId,t,e.chatRoomInfo):this.messageSender.handleAck(e.protocolId,e.serverId,t));Vs("ACK rejected",{protocolId:e.protocolId,statusCode:e.statusCode,reason:e.reason,hasReplacedMessage:Boolean(t)});const r=((e,t)=>{const r=Wr(e,t),s=r.code===ot.UNKNOWN?ot.MESSAGE_SEND_FAILED:r.code;return{code:s,message:Jr[s]??(t?`Message send failed: ${t}`:"Message send failed for an unknown reason"),retryable:r.retryable}})(e.statusCode,e.reason),s=new ft(r.message,{code:r.code,details:{protocolId:e.protocolId,serverCode:e.statusCode,reason:e.reason,retryable:!1}});this.messageSender.handleAckFailure(e.protocolId,e.statusCode,e.reason,s)}dispatchMessage(e){if(it(e))return void this.streamMessageHandler.handle(e);this.rememberMessageContext(e),this.sendDeliveryAckIfNeeded(e);const t=this.resolveMessageContextId(e);this.recentMessageIds.checkAndRecord(t)?js("Duplicate message ignored",{messageId:t}):(this.eventHub.dispatch(M,e),js("Message received",{msgServerId:e.msgServerId}))}sendDeliveryAckIfNeeded(e){if(!this.enableDeliveryReceipt)return;if("singleChat"!==e.conversationType)return;const t=this.msyncCodec.getContext().userId;t&&e.from!==t&&this.messageSender.sendAction({kind:"deliveryAck",conversationId:e.from,conversationType:"singleChat",messageId:e.msgServerId??e.msgLocalId}).catch(e=>{Vs("Failed to send delivery ack",e)})}handleNotifies(e){const t=[];for(const r of e)if("presence"===r.type)this.handlePresenceNotify(r);else if("contact"===r.type)this.handleContactNotify(r);else if("group"===r.type)this.handleGroupNotify(r);else if("thread"===r.type)this.handleChatThreadNotify(r);else if("chatroom"===r.type)this.handleChatRoomNotify(r);else if("reaction"===r.type)this.handleReactionNotify(r);else if("conv"===r.type)this.handleConversationNotify(r);else if("multiDevice"===r.type)this.handleMultiDeviceNotify(r);else if("message_receipts"===r.type){const e=this.toMessageReceiptPayload(r);e&&t.push(e)}else"message_recalled"===r.type?this.handleMessageRecalledNotify(r):"message_updated"===r.type?this.handleMessageUpdatedNotify(r):"message_delivered"===r.type?this.handleMessageDeliveredNotify(r):this.handleUserInfoNotify(r);t.length>0&&this.eventHub.dispatch(k,t)}handleUserInfoNotify(e){const t="subscribe_metadata_updated"===e.type||"contact_metadata_updated"===e.type||"user_metadata_updated"===e.type?e.type:"subscribe_metadata_updated"===e.eventName||"contact_metadata_updated"===e.eventName||"user_metadata_updated"===e.eventName?e.eventName:null;if(!t)return;const r=e.data;if(!r||"object"!=typeof r)return;const s=r,n="string"==typeof s.username?s.username:"string"==typeof s.userId?s.userId:"user_metadata_updated"===t?this.msyncCodec.getContext().userId:"",i=s.metadata&&"object"==typeof s.metadata&&!Array.isArray(s.metadata)?s.metadata:null,o="number"==typeof s.lastModified?s.lastModified:"string"==typeof s.lastModified?Number(s.lastModified):Number.NaN;if(!n||!i||!Number.isFinite(o))return;const a={notifyType:t,userId:n,metadata:i,lastModified:o};this.eventHub.dispatch(v,a)}handleContactNotify(e){if(js("[RosterSync] handleContactNotify",{eventName:e.eventName,type:e.type}),"string"!=typeof e.eventName)return;if(e.eventName!==z&&e.eventName!==H&&e.eventName!==W&&e.eventName!==J&&e.eventName!==Q)return;const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.from&&r.from&&"string"==typeof r.to&&r.to&&"string"==typeof r.message&&this.eventHub.dispatch(e.eventName,r)}handlePresenceNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t,s=Array.isArray(r.values)?r.values:[];if(0===s.length)return;const n=[];for(const i of s){if(!i||"object"!=typeof i)continue;const e=i,t=this.normalizePresenceStatus(e.status),r="string"==typeof e.uid?e.uid:"";r&&n.push({userId:r,statusDetails:t,ext:"string"==typeof e.ext?e.ext:"",lastTime:Number(e.last_time)||0,expire:Number(e.expiry)||0})}0!==n.length&&this.eventHub.dispatch(K,n)}handleGroupNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(f,r)}handleChatRoomNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(g,r)}handleReactionNotify(e){const t=Array.isArray(e.data)?e.data:[];for(const r of t){if(!hp(r)||"string"!=typeof r.messageId)continue;const e=this.resolveReactionConversationContext(r);e&&this.eventHub.dispatch(F,{messageId:r.messageId,conversationId:e.conversationId,conversationType:e.conversationType,from:e.from,to:e.to,reactions:this.normalizeReactionList(r.reactions),timestamp:this.normalizeTimestamp(r.ts)})}}handleConversationNotify(e){if(!hp(e.data))return;const t=e.data;if("pin"!==t.op&&"pin_delete"!==t.op)return;const r=this.msyncCodec.getContext();if("string"==typeof t.res&&t.res===r.clientResource&&"string"==typeof t.from&&t.from===r.userId)return;const s="string"==typeof t.ext?t.ext:"",n="string"==typeof t.type?t.type:"",i="string"==typeof t.from?t.from:"",o="string"==typeof t.id?t.id:"";s&&i&&o&&this.eventHub.dispatch(B,{messageId:s,conversationId:"chat"===n?i:o,conversationType:"chat"===n?"singleChat":"groupChat",operation:"pin"===t.op?"pin":"unpin",operatorId:i,pinTime:"number"==typeof t.ts?t.ts:Number(t.ts)||void 0})}handleMultiDeviceNotify(e){if(!hp(e.data)||"string"!=typeof e.eventName)return;const t=e.data;switch(e.eventName){case"onMultiDeviceContact":case"onMultiDeviceGroup":case"onMultiDeviceThread":case"onMultiDeviceConversation":case"onMultiDeviceMessageRemoved":return void this.eventHub.dispatch(e.eventName,t);default:return}}toMessageReceiptPayload(e){if(!hp(e.data))return null;const t=e.data;if(!Array.isArray(t.messageIds)||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||"number"!=typeof t.timestamp)return null;const r=t.messageIds.filter(e=>"string"==typeof e&&e.length>0);if(0===r.length)return null;const s=r[0];if(!s)return null;const n=this.resolveMessageReceiptContext(s,t.conversationId,t.conversationType);if("groupChat"===n.conversationType){const e=new Set(r),s=Array.isArray(t.receiptDetails)?t.receiptDetails.flatMap(t=>{if(!hp(t))return[];const r=t.messageId,s=t.count;return"string"==typeof r&&e.has(r)&&"number"==typeof s&&Number.isInteger(s)&&s>=0?[{messageId:r,count:s}]:[]}):[];return{messageIds:r,conversationId:n.conversationId,conversationType:"groupChat",timestamp:t.timestamp,receiptDetails:s}}return{messageIds:r,conversationId:n.conversationId,conversationType:"singleChat",timestamp:t.timestamp}}handleMessageDeliveredNotify(e){if(!hp(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&this.eventHub.dispatch(D,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"singleChat"})}handleMessageRecalledNotify(e){if(!hp(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&"string"==typeof t.conversationType&&this.eventHub.dispatch(P,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"chatRoom"===t.conversationType?"chatRoom":"groupChat"===t.conversationType?"groupChat":"singleChat",timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now()})}handleMessageUpdatedNotify(e){if(!hp(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!hp(t.message)||"string"!=typeof t.message.type||!hp(t.message.body)||!hp(t.message.ext))return;const r={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...hp(t.message.modifiedInfo)?{modifiedInfo:{operatorId:"string"==typeof t.message.modifiedInfo.operatorId?t.message.modifiedInfo.operatorId:"",operationCount:"number"==typeof t.message.modifiedInfo.operationCount?t.message.modifiedInfo.operationCount:0,operationTime:"number"==typeof t.message.modifiedInfo.operationTime?t.message.modifiedInfo.operationTime:0}}:{}};this.eventHub.dispatch(x,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"chatRoom"===t.conversationType?"chatRoom":"groupChat"===t.conversationType?"groupChat":"singleChat",message:r,timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now()})}normalizeUpdatedMessageBody(e,t){if("text"!==e)return t;const r="string"==typeof t.content?t.content:"string"==typeof t.message?t.message:void 0;if(void 0===r)return t;const{message:s,...n}=t;return{...n,content:r}}handleChatThreadNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"onChatThreadChange"===r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(y,r)}normalizePresenceStatus(e){if(!e||"object"!=typeof e)return[];return Object.entries(e).map(([e,t])=>({device:e,status:Number(t)||0}))}destroy(){this.streamMessageHandler.destroy(),this.recentMessageIds.clear(),this.messageContexts.clear()}rememberMessageContext(e){const t=this.resolveMessageContextId(e),r=this.resolveMessageConversationContext(e);if(t&&r)for(this.messageContexts.delete(t),this.messageContexts.set(t,r);this.messageContexts.size>500;){const e=this.messageContexts.keys().next().value;if(!e)break;this.messageContexts.delete(e)}}resolveMessageReceiptContext(e,t,r){const s=this.messageContexts.get(e);return s||("groupChat"===r?{conversationId:t,conversationType:"groupChat"}:{conversationId:t,conversationType:"singleChat"})}resolveMessageContextId(e){return"string"==typeof e.msgServerId&&e.msgServerId.length>0?e.msgServerId:"string"==typeof e.msgLocalId&&e.msgLocalId.length>0?e.msgLocalId:""}resolveMessageConversationContext(e){if("string"!=typeof e.conversationId||!e.conversationId)return null;if("groupChat"===e.conversationType)return{conversationId:e.conversationId,conversationType:"groupChat"};if("chatRoom"===e.conversationType)return{conversationId:e.conversationId,conversationType:"chatRoom"};if("singleChat"!==e.conversationType)return null;const t=this.msyncCodec.getContext().userId,r="SEND"===e.direct||e.sender.userId===t?e.conversationId:e.sender.userId;return r?{conversationId:r,conversationType:"singleChat"}:null}resolveReactionConversationContext(e){const t="string"==typeof e.from?e.from:"",r="string"==typeof e.to?e.to:"",s="string"==typeof e.channel_type?e.channel_type:"";if(!t||!r)return null;if("groupChat"===s||"groupchat"===s||"group"===s)return{conversationId:r,conversationType:"groupChat",from:t,to:r};if(""!==s&&"chat"!==s&&"singleChat"!==s)return null;return{conversationId:t===this.msyncCodec.getContext().userId?r:t,conversationType:"singleChat",from:t,to:r}}normalizeReactionList(e){if(!Array.isArray(e))return[];const t=[];for(const r of e)hp(r)&&"string"==typeof r.reaction&&t.push({reaction:r.reaction,count:"number"==typeof r.count&&Number.isFinite(r.count)?r.count:0,userList:Array.isArray(r.userList)?r.userList.filter(e=>"string"==typeof e):[],isAddedBySelf:"boolean"==typeof r.isAddedBySelf?r.isAddedBySelf:void 0,op:this.normalizeReactionOperations(r.op)});return t}normalizeReactionOperations(e){if(!Array.isArray(e))return;const t=[];for(const r of e)!hp(r)||"string"!=typeof r.operator||"create"!==r.reactionType&&"delete"!==r.reactionType||t.push({operator:r.operator,reactionType:r.reactionType});return t.length>0?t:void 0}normalizeTimestamp(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){const t=Number(e);return Number.isFinite(t)?t:0}return 0}}const mp=()=>{const e=globalThis;return"function"==typeof e.fetch?e.fetch:void 0},fp=()=>oc({fetchImpl:mp()})??{request:e=>Promise.reject(dn("Request capability is missing for current platform.",{code:sn,stage:Zs,retryable:!1,details:{capability:"request"}}))},gp=e=>e??fp(),yp=e=>e instanceof Error?e.message:String(e);class vp{constructor(e){this.requestAdapter=gp(e)}async downloadAndParse(e){const t=e.url.trim();if(!t)throw new mt("Combine message url is required",{code:ot.COMBINE_INVALID_INPUT,details:{fields:[{path:"url",message:"Combine message url is required",rule:"required"}]}});const r="number"==typeof e.maxItems?e.maxItems:300;sp(1,r);const s=bs(t,e.secret);try{const t=await this.requestAdapter.request({url:s,method:"GET",responseType:"arraybuffer",timeoutMs:e.timeoutMs??15e3,headers:{[ru]:tu()}});if(401===t.status||403===t.status)throw new pt(401===t.status?"Combine payload download unauthorized":"Combine payload download forbidden",{code:401===t.status?ot.AUTH_UNAUTHORIZED:ot.AUTH_FORBIDDEN,details:{url:s,httpStatus:t.status}});if(t.status>=400)throw new gt("Combine payload download failed",{code:ot.COMBINE_DOWNLOAD_FAILED,details:{status:t.status,url:s}});const n=(e=>{if(e.length<Gh.length+1)throw new gt("Combine payload is too short",{code:ot.COMBINE_PARSE_FAILED});const t=e.subarray(0,Gh.length);if(t[0]!==Gh[0]||t[1]!==Gh[1])throw new gt("Combine payload header is invalid",{code:ot.COMBINE_PARSE_FAILED});const r=e.subarray(0,e.length-1),s=Hh(r),n=e[e.length-1]??0;if(n!==s)throw new gt("Combine payload checksum failed",{code:ot.COMBINE_PARSE_FAILED,details:{expectedChecksum:s,actualChecksum:n}});const i=[];let o=Gh.length;const a=e.length-1;for(;o<a;){if(o+4>a)throw new gt("Combine payload length header is incomplete",{code:ot.COMBINE_PARSE_FAILED});const t=zh(e,o);if(o+=4,t<=0||o+t>a)throw new gt("Combine payload item length is invalid",{code:ot.COMBINE_PARSE_FAILED,details:{itemLength:t}});const r=e.subarray(o,o+t);o+=t;const s=Yh(r,i.length);i.push(s)}if(o!==a)throw new gt("Combine payload has unexpected trailing bytes",{code:ot.COMBINE_PARSE_FAILED,details:{offset:o,expected:a}});return i})((e=>{if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if("string"==typeof e)return zs(e);throw new gt("Combine payload response type is invalid",{code:ot.COMBINE_DOWNLOAD_FAILED})})(t.data));return sp(n.length,r),np(n),n.map(e=>({msgServerId:e.msgServerId??"",msgLocalId:e.msgLocalId??"",from:e.sender.userId,to:e.conversationId,sender:e.sender,conversationId:e.conversationId,conversationType:e.conversationType,type:e.type,sendStatus:"sent",ext:e.ext??{},timestamp:e.timestamp,body:e.body,direct:"RECEIVE"}))}catch(n){if(n instanceof mt||n instanceof pt||n instanceof gt)throw n;throw new gt("Combine payload download or parse failed",{code:ot.COMBINE_DOWNLOAD_FAILED,details:{cause:yp(n),url:s}})}}}const Ip=e=>{switch(e.type){case"image":return e.body.filename??"image";case"video":return e.body.filename??"video";case"voice":return e.body.filename??"voice";case"file":return e.body.filename??"file";default:return"attachment"}},bp=e=>{switch(e.type){case"image":case"video":case"voice":case"file":return e.body.filetype??"application/octet-stream";default:return"application/octet-stream"}};class _p{constructor(e){this.requestAdapter=gp(e)}async download(e,t=15e3){if("image"!==e.type&&"video"!==e.type&&"voice"!==e.type&&"file"!==e.type)throw new mt("message does not contain downloadable attachment",{code:ot.ATTACHMENT_INVALID,details:{fields:[{path:"message.type",message:"does not contain downloadable attachment",rule:"attachment_type"}]}});const{url:r,secret:s}=(e=>{switch(e.type){case"image":{const t=e.body;return{url:t.originalImageUrl??t.bigImageUrl??t.thumbnailUrl??"",secret:t.secret}}case"video":case"voice":case"file":{const t=e.body;return{url:t.url??"",secret:t.secret}}default:return{url:""}}})(e);if(!r)throw new mt("attachment url is required",{code:ot.ATTACHMENT_INVALID,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}});let n;try{n=await this.requestAdapter.request({url:bs(r,s),method:"GET",responseType:"arraybuffer",timeoutMs:t,headers:{[ru]:tu()}})}catch(i){if("object"==typeof i&&null!==i&&i.code===sn)throw new lt("request adapter is required for attachment download");throw i}if(401===n.status)throw new pt("attachment download unauthorized",{code:ot.AUTH_UNAUTHORIZED,details:{url:r,httpStatus:n.status}});if(403===n.status)throw new pt("attachment download forbidden",{code:ot.AUTH_FORBIDDEN,details:{url:r,httpStatus:n.status}});if(404===n.status){const e=("string"==typeof n.data?n.data:"").includes("expired");throw new ut(e?"attachment file is expired":"attachment not found",e?ot.ATTACHMENT_EXPIRED:ot.ATTACHMENT_NOT_FOUND)}if(429===n.status)throw new ut("attachment download rate limited",ot.SERVICE_LIMIT_EXCEEDED);if(n.status>=400)throw new ut("attachment download failed",ot.FILE_DOWNLOAD_FAILED,{details:{status:n.status,url:r}});return{filename:Ip(e),mimeType:bp(e),size:(()=>{switch(e.type){case"image":case"video":case"voice":return e.body.fileLength;case"file":return e.body.fileLength??e.body.fileSize;default:return}})(),data:new Uint8Array(n.data),downloadUrl:r}}}const Tp=(e,t,r)=>({Authorization:`Bearer ${e}`,Accept:t,[ru]:tu(),...r??{}}),Cp=async e=>{const t=Tp(e.token,"application/json",e.headers),r=Date.now(),s="upload.multipart.init"===e.operation?"REST_INIT_UPLOAD_TASK_IN_PARTS":"upload.multipart.complete"===e.operation?"REST_COMPLETE_UPLOAD_PART":"REST_ABORT_UPLOAD_PART",n=e.dataReportOperation?.startRequest({requestName:s,method:e.method,url:e.url});let i=0;js("Upload request start",{operation:e.operation,method:e.method});try{const s=await e.requestAdapter.request({url:e.url,method:e.method,headers:t,responseType:"json",timeoutMs:Qr});i=s.status;const a=Date.now()-r;if(s.status<200||s.status>=300)throw Vs("Upload response error",{operation:e.operation,method:e.method,status:s.status,duration:a}),new bt("Upload request failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{url:e.url,status:s.status}});js("Upload response success",{operation:e.operation,method:e.method,status:s.status,duration:a});const c="string"==typeof(o=s.data)?JSON.parse(o):o;return n?.finish({code:s.status,success:!0}),c}catch(a){if(n?.finish({code:0!==i?i:a instanceof bt?a.code:ot.UPLOAD_REQUEST_FAILED,success:!1,description:a instanceof Error?a.message:String(a)}),a instanceof bt)throw a;throw Vs("Upload request failed",{operation:e.operation,method:e.method}),new bt("Upload request failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{url:e.url}})}var o},Sp=async e=>{const t=Date.now(),r=e.dataReportOperation?.startRequest({requestName:"REST_UPLOAD_PART",method:"PUT",url:e.url});js("Upload part start",{operation:"upload.multipart.part",partNumber:e.partNumber});try{const s=await e.uploadAdapter.upload({url:e.url,method:"PUT",headers:Tp(e.token,"*/*",{"restrict-access":"true"}),source:{sourceType:"web-file",file:e.part,name:`${e.fileName}.part-${e.partNumber}`,mimeType:e.fileType,size:e.part.size},fields:{part_number:e.partNumber},fileFieldName:"part_file",timeoutMs:Qr,onProgress:t=>e.onProgress?.(t.loaded)}),n=Date.now()-t;if(s.status<200||s.status>=300)throw new bt("Upload part failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{url:e.url,partNumber:e.partNumber,status:s.status,response:s.body}});js("Upload part success",{operation:"upload.multipart.part",partNumber:e.partNumber,duration:n}),r?.finish({code:s.status,success:!0})}catch(s){const t=Pd(s),n=t.details&&"object"==typeof t.details?t.details:void 0;throw r?.finish({code:t.code,success:!1,description:t.message}),Vs("Upload part failed",{operation:"upload.multipart.part",partNumber:e.partNumber}),new bt(t.message,{code:t.code,details:{...n,url:e.url,partNumber:e.partNumber}})}},Ep=async e=>{if(e.fileSize<=as)throw new bt("Multipart not required",{code:ot.UPLOAD_REQUEST_FAILED,details:{reason:"file size below threshold"}});const{config:t,file:r,conversationId:s,conversationType:n,fileName:i,fileType:o,fileSize:a,messageType:c,imageType:d,md5:u,width:l,height:h}=e,p=(e=>gp(e))(t.requestAdapter),m=(e=>{if(e)return e;const t=vc();if(t)return t;throw new bt("Upload adapter is required for multipart upload",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{capability:"upload"}})})(t.uploadAdapter),{orgName:f,appName:g}=fs(t.appKey),y=`${t.restBaseUrl}/${f}/${g}/sdk/chatfiles/part-upload`;let v;try{v=await Cp({url:y,method:"POST",token:t.token,operation:"upload.multipart.init",requestAdapter:p,dataReportOperation:e.dataReportOperation})}catch(O){throw new bt("Multipart init failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{stage:"init",cause:O,url:y}})}const I=(e=>{const t=e.entities?.[0],r="number"==typeof t?.file_upper_limit?t.file_upper_limit:0,s="number"==typeof t?.part_lower_limit?t.part_lower_limit:cs,n="string"==typeof t?.uuid?t.uuid:"";if(!n)throw new bt("Multipart init failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{response:e}});return{fileMaxSize:r,partMinSize:s,uuid:n}})(v);if(I.fileMaxSize&&a>I.fileMaxSize)throw new bt("File size exceeds limit",{code:ot.UPLOAD_SIZE_EXCEEDED,details:{fileSize:a,maxSize:I.fileMaxSize}});const b=I.partMinSize||cs,_=Math.ceil(a/b),T=Array.from({length:_},()=>0),C=`${t.restBaseUrl}/${f}/${g}/sdk/chatfiles/part-upload/${I.uuid}`,S=[],E=(t,r)=>{T[t]=r;const s=T.reduce((e,t)=>e+t,0),n=a?s/a*100:void 0;e.callbacks?.onFileUploadProgress?.({loaded:s,total:a,percent:n})};for(let M=0;M<_;M+=1){const s=M*b,n=Math.min(a,s+b),c=r.slice(s,n),d=String(M+1),u=Sp({url:C,token:t.token,partNumber:d,part:c,fileName:i,fileType:o,uploadAdapter:m,onProgress:e=>E(M,e),dataReportOperation:e.dataReportOperation}).finally(()=>{const e=S.indexOf(u);e>=0&&S.splice(e,1)});S.push(u),S.length>=4&&await Promise.race(S)}await Promise.all(S);const w=gs(n),R=Is(`${t.restBaseUrl}/${f}/${g}/sdk/chatfiles/part-upload/${I.uuid}`,{"restrict-access":"true","chat-type":w,"chat-target":s,"thumbnail-width":e.thumbnailWidth,"thumbnail-height":e.thumbnailHeight,md5:u??"",..."image"===c?{imageType:Cs(d),width:l,height:h}:{}}),A=await Cp({url:R,method:"POST",token:t.token,operation:"upload.multipart.complete",requestAdapter:p,dataReportOperation:e.dataReportOperation}),N=Es({response:A,restBaseUrl:t.restBaseUrl,orgName:f,appName:g,fileType:o,fileName:i,fallbackSize:a,messageType:c,imageType:d,useCustomAttachmentUpload:t.useCustomAttachmentUpload});return e.callbacks?.onFileUploadComplete?.(N),N},wp=async e=>{const{config:t,file:r,conversationId:s,conversationType:n,messageType:i,imageType:o,md5:a,width:c,height:d,fileName:u,fileType:l,fileSize:h}=e,p=(e=>{if(e)return e;const t=vc();if(t)return t;throw new bt("Upload adapter is required for simple upload",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{capability:"upload"}})})(t.uploadAdapter),{orgName:m,appName:f}=fs(t.appKey),g=gs(n),y=Is(`${t.restBaseUrl}/${m}/${f}/chatfiles`,{"chat-type":g,"chat-target":s,md5:a??"",..."image"===i?{imageType:Cs(o),width:c,height:d}:{}}),v=Date.now(),I=e.dataReportOperation?.startRequest({requestName:"UPLOAD_MSG_ATTACH",method:"POST",url:y});js("Upload request start",{operation:"upload.simple",method:"POST",fileSize:h,messageType:i});const b={};let _;void 0!==e.thumbnailWidth&&(b["thumbnail-width"]=String(e.thumbnailWidth)),void 0!==e.thumbnailHeight&&(b["thumbnail-height"]=String(e.thumbnailHeight));try{_=await p.upload({url:y,method:"POST",headers:{"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${t.token}`,[ru]:tu()},source:{sourceType:"web-file",file:r,name:u,mimeType:l,size:h},fields:b,fileFieldName:"file",timeoutMs:Qr,onProgress:t=>e.callbacks?.onFileUploadProgress?.(t)})}catch(T){const t=Pd(T),r=t.details&&"object"==typeof t.details?t.details:void 0,s=new bt(t.message,{code:t.code,details:{...r,url:y,...t.code===ot.UPLOAD_TIMEOUT?{timeout:Qr}:{}}});throw I?.finish({code:s.code,success:!1,description:s.message}),s.code===ot.UPLOAD_ABORTED?(Vs("Upload request aborted",{operation:"upload.simple"}),e.callbacks?.onFileUploadCanceled?.()):s.code===ot.UPLOAD_TIMEOUT?Vs("Upload request timeout",{operation:"upload.simple",timeout:Qr}):Vs("Upload request failed",{operation:"upload.simple"}),s}try{const r=JSON.parse(_.body),s=Date.now()-v;if(_.status>=400)throw Vs("Upload response error",{operation:"upload.simple",status:_.status,duration:s}),new bt("Upload failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{status:_.status,response:r}});js("Upload response success",{operation:"upload.simple",status:_.status,duration:s});const n=Es({response:r,restBaseUrl:t.restBaseUrl,orgName:m,appName:f,fileType:l,fileName:u,fallbackSize:h,messageType:i,imageType:o,useCustomAttachmentUpload:t.useCustomAttachmentUpload});return e.callbacks?.onFileUploadComplete?.(n),I?.finish({code:_.status||200,success:!0}),n}catch(T){throw I?.finish({code:T instanceof bt?T.code:ot.UPLOAD_REQUEST_FAILED,success:!1,description:T instanceof Error?T.message:String(T)}),T instanceof Error?T:new Error(String(T))}},Rp=Lc(),Ap=e=>Object.prototype.toString.call(e),Np=e=>{const t=e&&"object"==typeof e?e:null,r="string"==typeof t?.path?t.path:void 0,s="string"==typeof t?.uri?t.uri:void 0,n="string"==typeof t?.name?t.name:void 0,i="string"==typeof t?.type?t.type:void 0,o="number"==typeof t?.size?t.size:void 0;return{kind:Ap(e),isFile:"undefined"!=typeof File&&e instanceof File,isBlob:"undefined"!=typeof Blob&&e instanceof Blob,hasPath:"string"==typeof r&&r.length>0,pathPrefix:r?r.slice(0,48):void 0,hasUri:"string"==typeof s&&s.length>0,uriPrefix:s?s.slice(0,48):void 0,name:n,type:i,size:o}},Op=e=>({sourceType:e.source.sourceType,fileName:e.fileName,fileType:e.fileType,fileSize:e.fileSize,hasWebFile:Boolean(e.webFile),sourceName:e.source.name,sourceMimeType:e.source.mimeType,sourceSize:e.source.size}),Mp=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,Up=e=>"object"==typeof e&&null!==e,Lp=(e,t)=>{const r=Up(t)?t:void 0,s=r?.code===sn&&r.stage===tn;return"miniapp-path"===e&&(e=>{if(!Up(e))return!1;const t=Up(e.details)?e.details:void 0;return e.code===sn&&e.stage===tn&&"string"==typeof t?.capability&&t.capability.includes("FileSystem")})(t)||"rn-uri"===e&&s};class kp{constructor(e){this.config=e??null}updateConfig(e){this.config=e}updateAuthToken(e){this.config&&(this.config={...this.config,token:e})}async prepareMessage(e,t){if(!Mp(e.type))return e;const r=e.body;if(this.hasUploadedRemoteResource(e.type,r))return e;const s=this.resolveUploadUrl(e.type,r),n=xh.get(e.msgLocalId),i=Boolean(n);if(Vs("Attachment upload prepare entry",{operation:"upload.prepare.entry",msgLocalId:e.msgLocalId,messageType:e.type,conversationType:e.conversationType,hasFile:i,uploadUrl:s,cachedFile:Np(n),adapter:{hasRequestAdapter:Boolean(this.config?.requestAdapter),hasUploadAdapter:Boolean(this.config?.uploadAdapter),hasImageProcessor:Boolean(this.config?.imageProcessor),restBaseUrl:Boolean(this.config?.restBaseUrl),useCustomAttachmentUpload:this.config?.useCustomAttachmentUpload}}),!((e,t)=>!!t||!e||!ms(e))(s,i))return e;if(!n)throw new bt("Attachment file is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{msgLocalId:e.msgLocalId,url:s}});if(!this.config?.restBaseUrl)throw new bt("REST base url is required for upload",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"restBaseUrl missing"}});let o,a,c;try{o=await this.prepareAttachmentUpload(e,r,n),o.precheck?.hit||(c=Uh({operationName:"UPLOAD_MSG_ATTACH",operationType:"REST",msgId:e.msgLocalId,messageType:e.type})),a=o.precheck?.hit?this.buildPrecheckedUploadResult(e,o,t):await this.uploadAttachment(e,o,t,c),c?.finish({code:0,success:!0})}catch(d){const e=Pd(d);throw c?.finish({code:e.code,success:!1,description:e.message}),e.code===ot.UPLOAD_ABORTED&&t?.onFileUploadCanceled?.(),t?.onFileUploadError?.(e),e}return this.buildPreparedMessage(e,o,a)}resolveUploadUrl(e,t){if("image"===e){const e=t;return("string"==typeof e.localUrl?e.localUrl.trim():"")||("string"==typeof e.originalImageUrl?e.originalImageUrl.trim():"")}return"url"in t&&"string"==typeof t.url?t.url.trim():""}hasUploadedRemoteResource(e,t){if("image"===e){const e=t;return"string"==typeof e.originalImageUrl&&ms(e.originalImageUrl)}return"url"in t&&"string"==typeof t.url&&ms(t.url)}async prepareAttachmentUpload(e,t,r){const s=((e,t)=>{if(!e)throw new bt("Attachment file is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"file missing"}});const r=("number"==typeof t.fileLength?t.fileLength:void 0)??("fileSize"in t&&"number"==typeof t.fileSize?t.fileSize:void 0),s=os({file:e,fallbackName:t.filename,fallbackMimeType:t.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new bt("Attachment file is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"web file missing"}});return s})(r,t);if(Vs("Attachment file normalized",{operation:"upload.prepare.normalized",messageType:e.type,fileInfo:Op(s)}),"image"!==e.type){return{body:t,fileInfo:s,md5FileInfo:s,precheck:await this.maybePrecheck(e,s,s,void 0)}}const n=t,i=await this.resolveImageCandidate(n,s),o={...n,width:i.width,height:i.height,isOriginalImage:i.imagePolicy.resolvedImageType===hs},a=await this.maybePrecheck(e,i.fileInfo,s,i.imagePolicy.resolvedImageType);return{body:o,fileInfo:i.fileInfo,md5FileInfo:s,imageType:i.imagePolicy.resolvedImageType,precheck:a,originalWidth:n.width,originalHeight:n.height}}async resolveImageCandidate(e,t){const r=(e=>e.isGif?{resolvedImageType:hs,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:hs,reason:"explicit-original"}:{resolvedImageType:ps,reason:"default-large"})(e);if(Vs("Image send policy resolved",{operation:"upload.image.policy",reason:r.reason,imageType:r.resolvedImageType,isGif:e.isGif,source:Op(t)}),r.resolvedImageType===hs){let s=e.width,n=e.height;if(!s||!n){const e=this.resolveImageProcessor(t.source.sourceType);Vs("Image original info resolving",{operation:"upload.image.info",processorSourceType:t.source.sourceType,source:Op(t)});const r=await e.getImageInfo(t.source);s=r.width,n=r.height}return{imagePolicy:r,sourceKind:"origin",fileInfo:t,width:s,height:n}}try{const e=this.resolveImageProcessor(t.source.sourceType);Vs("Image big generation start",{operation:"upload.image.big.start",processorSourceType:t.source.sourceType,source:Op(t)});const s=await e.generateBigImage(t.source,{maxShortEdge:720,quality:.85});return{imagePolicy:r,sourceKind:"big",fileInfo:{source:s.source,fileName:s.fileName??t.fileName,fileType:s.fileType??t.fileType,fileSize:s.fileSize??t.fileSize,webFile:s.webFile},width:s.width,height:s.height}}catch(s){return Vs("Image big generation failed, fallback to original",{operation:"upload.image.big-fallback",reason:r.reason,error:s instanceof Error?s.message:String(s),source:Op(t)}),{imagePolicy:{resolvedImageType:hs,reason:"large-fallback-origin"},sourceKind:"origin",fileInfo:t,width:e.width??0,height:e.height??0}}}async maybePrecheck(e,t,r,s){if(!Mp(e.type))return;if(!0!==this.config?.enableMd5Check)return void js("Attachment precheck skipped because MD5 check is disabled",{operation:"upload.precheck.skip",reason:"md5-check-disabled",messageType:e.type,imageType:s,fileSize:t.fileSize});const n=_s({messageType:e.type,fileSize:t.fileSize,imageType:s});if(!n.shouldPrecheck)return void js("Attachment precheck skipped",{operation:"upload.precheck.skip",messageType:e.type,imageType:s,fileSize:t.fileSize,thresholdBytes:n.thresholdBytes});let i;try{i=await this.computeMd5(r)}catch(a){if(Lp(r.source.sourceType,a))return void Vs("Attachment precheck skipped because md5 is unavailable",{operation:"upload.precheck.md5-unavailable",messageType:e.type,imageType:s,thresholdType:n.thresholdType,source:Op(r),error:a instanceof Error?a.message:String(a)});throw a}const o=await this.requestPrecheck(e,n.thresholdType,i,s);return js(o.hit?"Attachment precheck hit":"Attachment precheck miss",{operation:o.hit?"upload.precheck.hit":"upload.precheck.miss",messageType:e.type,imageType:s,exists:o.exists,existsType:o.existsType,uuid:o.uuid,hasShareSecret:"string"==typeof o.shareSecret&&o.shareSecret.length>0}),{...o,md5:i}}async computeMd5(e){const t=this.resolveImageProcessor(e.source.sourceType);return Vs("Attachment md5 compute start",{operation:"upload.md5.start",source:Op(e)}),t.computeMd5(e.source)}resolveImageProcessor(e){if(this.config?.imageProcessor)return Vs("Image processor resolved from platform adapter",{operation:"upload.image.processor",sourceType:e,processor:"platform"}),this.config.imageProcessor;if("web-file"===e)return Vs("Image processor resolved from web fallback",{operation:"upload.image.processor",sourceType:e,processor:"web-fallback"}),Rp;throw Vs("Image processor missing",{operation:"upload.image.processor-missing",sourceType:e}),dn("Image processor capability is missing for current platform",{code:sn,stage:tn,retryable:!1,details:{capability:"imageProcessor",sourceType:e}})}async requestPrecheck(e,t,r,s){if(!this.config)throw new bt("Upload config is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:n,appName:i}=fs(this.config.appKey),o=Is(`${this.config.restBaseUrl}/${n}/${i}/chatfiles/exists`,{md5:r,..."image"===e.type?{imageType:Cs(s)}:{}}),a=await this.requestJson({url:o,method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,Accept:"application/json"},operation:"upload.precheck"}).catch(n=>{Vs("Attachment precheck failed, fallback to upload",{operation:"upload.precheck.fail-open",messageType:e.type,imageType:s,thresholdType:t,md5:r,error:n instanceof Error?n.message:String(n)})});return a?(e=>{const t=e.entities?.[0],r=!0===t?.exists,s="string"==typeof t?.uuid&&t.uuid.length>0?t.uuid:void 0,n=t,i=n?.["exists-type"]??n?.existsType,o="origin"===i?hs:i===ps||i===hs?i:void 0,a="string"==typeof t?.["share-secret"]?t["share-secret"]:void 0;if(r&&!s)throw new bt("Upload precheck response missing uuid",{code:ot.UPLOAD_REQUEST_FAILED,details:{response:e}});return{uuid:s,exists:r,existsType:o,shareSecret:a,hit:(c={exists:r,uuid:s},c.exists&&"string"==typeof c.uuid&&c.uuid.length>0)};var c})(a):{exists:!1,hit:!1}}async requestJson(e){return this.requestByAdapter(gp(this.config?.requestAdapter),e)}async requestByAdapter(e,t){const r=await e.request({url:t.url,method:t.method,headers:t.headers,responseType:"json",timeoutMs:Qr});if(r.status>=400)throw new bt("Upload precheck request failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{url:t.url,status:r.status,operation:t.operation}});return"string"==typeof r.data?JSON.parse(r.data):r.data}buildPrecheckedUploadResult(e,t,r){if(!this.config||!t.precheck)throw new bt("Precheck result is required",{code:ot.UPLOAD_REQUEST_FAILED});if(!t.precheck.uuid)throw new bt("Precheck hit missing uuid",{code:ot.UPLOAD_REQUEST_FAILED,details:{precheck:t.precheck}});if(!Mp(e.type))throw new bt("Attachment message type is invalid",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:e.type}});const{orgName:s,appName:n}=fs(this.config.appKey),i="image"===e.type?t.precheck.existsType??t.imageType:void 0,o="image"===e.type&&i===hs?t.md5FileInfo:t.fileInfo,a="image"===e.type&&i===hs?t.originalWidth:"image"===e.type?t.body.width:void 0,c="image"===e.type&&i===hs?t.originalHeight:"image"===e.type?t.body.height:void 0,d={entities:[{uuid:t.precheck.uuid,...t.precheck.shareSecret?{"share-secret":t.precheck.shareSecret}:{}}]},u=Es({response:d,restBaseUrl:this.config.restBaseUrl,orgName:s,appName:n,fileType:o.fileType,fileName:o.fileName,fallbackSize:o.fileSize,messageType:e.type,imageType:i,width:a,height:c,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return r?.onFileUploadComplete?.(u),u}async uploadAttachment(e,t,r,s){if(!this.config)throw new bt("Upload config is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING});if(!Mp(e.type))throw new bt("Attachment message type is invalid",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:e.type}});const n=e.type,i=await this.resolveUploadMetadata(n,t);if(!t.fileInfo.webFile){if(this.config.uploadAdapter)return this.uploadByAdapter(this.config.uploadAdapter,e,t,i,r);throw new bt("Upload adapter is required for non-web file source",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{sourceType:t.fileInfo.source.sourceType}})}const o={message:e,file:t.fileInfo.webFile,conversationId:e.conversationId,conversationType:e.conversationType,messageType:n,imageType:t.imageType,md5:i.md5,width:i.width,height:i.height,fileName:t.fileInfo.fileName,fileType:t.fileInfo.fileType,fileSize:t.fileInfo.fileSize,thumbnailWidth:this.resolveThumbnailWidth(n,t.body),thumbnailHeight:this.resolveThumbnailHeight(n,t.body),callbacks:r,config:this.config,dataReportOperation:s},a=!1!==this.config?.enableMultipartUpload,c=a&&t.fileInfo.fileSize>as;if(Vs("Attachment web upload selected",{operation:"upload.web.selected",messageType:n,source:Op(t.fileInfo),multipartEnabled:a,uploadMode:c?"multipart":"simple"}),c)try{return await Ep(o)}catch(d){const e=d instanceof bt?d.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return wp(o);throw d}return this.config.uploadAdapter?(Vs("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:n,source:Op(t.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,e,t,i,r)):wp(o)}async uploadByAdapter(e,t,r,s,n){if(!this.config)throw new bt("Upload config is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:i,appName:o}=fs(this.config.appKey),a=gs(t.conversationType);if(!Mp(t.type))throw new bt("Attachment message type is invalid",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const c=t.type,d=Is(`${this.config.restBaseUrl}/${i}/${o}/chatfiles`,{"chat-type":a,"chat-target":t.conversationId,md5:s.md5,..."image"===c?{imageType:Cs(r.imageType),width:s.width,height:s.height}:{}}),u={},l={"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${this.config.token}`,[ru]:tu()},h=this.resolveThumbnailWidth(c,r.body),p=this.resolveThumbnailHeight(c,r.body);void 0!==h&&(u["thumbnail-width"]=String(h)),void 0!==p&&(u["thumbnail-height"]=String(p)),Vs("Attachment adapter upload start",{operation:"upload.adapter.start",messageType:c,source:Op(r.fileInfo),uploadUrl:d,fields:u});const m=await e.upload({url:d,headers:l,source:r.fileInfo.source,fields:u,onProgress:e=>{n?.onFileUploadProgress?.(e)}});if(m.status>=400){const e=m.body??"",t=413===m.status?ot.FILE_TOO_LARGE:"string"==typeof e&&e.includes("content improper")?ot.FILE_CONTENT_IMPROPER:ot.UPLOAD_REQUEST_FAILED;throw new bt("Upload failed",{code:t,details:{status:m.status,response:m.body}})}let f;try{f=JSON.parse(m.body)}catch(y){throw new bt("Upload response parse failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{response:m.body,cause:y instanceof Error?y.message:String(y)}})}const g=Es({response:f,restBaseUrl:this.config.restBaseUrl,orgName:i,appName:o,fileType:r.fileInfo.fileType,fileName:r.fileInfo.fileName,fallbackSize:r.fileInfo.fileSize,messageType:c,imageType:r.imageType,width:s.width,height:s.height,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return n?.onFileUploadComplete?.(g),g}buildPreparedMessage(e,t,r){if("image"===e.type){const s=t.body,n={...e,body:{...s,isOriginalImage:r.isOriginalImage??s.isOriginalImage,originalImageUrl:r.originalImageUrl??s.originalImageUrl,bigImageUrl:r.bigImageUrl??s.bigImageUrl,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename,thumbnailUrl:r.thumbnailUrl??s.thumbnailUrl,width:r.width??s.width,height:r.height??s.height}};return Ju(e,n),el(e,n),n}if("video"===e.type){const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename,thumbnailUrl:r.thumbnailUrl??s.thumbnailUrl}};return Ju(e,n),n}if("voice"===e.type){const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename}};return Ju(e,n),n}if("combine"===e.type){const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename}};return Ju(e,n),n}const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename}};return Ju(e,n),n}resolveThumbnailWidth(e,t){if("video"===e){const e="width"in t?t.width:void 0;return"number"==typeof e&&e>0?e:void 0}}resolveThumbnailHeight(e,t){if("video"===e){const e="height"in t?t.height:void 0;return"number"==typeof e&&e>0?e:void 0}}async resolveUploadMetadata(e,t){let r=t.precheck?.md5??"";if(!t.precheck)try{r=await this.computeMd5(t.md5FileInfo)}catch(n){if(!Lp(t.md5FileInfo.source.sourceType,n))throw n;Vs("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:Op(t.md5FileInfo),error:n instanceof Error?n.message:String(n)})}const s=t.body;return{md5:r,width:"image"===e&&"number"==typeof s.width&&s.width>0?s.width:void 0,height:"image"===e&&"number"==typeof s.height&&s.height>0?s.height:void 0}}}class Dp{constructor(e,t){this.unsubscribeNetwork=null,this.unsubscribeVisibility=null,this.lastOnline=null,this.lastForeground=null,this.runtime=e,this.handlers=t}start(){this.unsubscribeNetwork||this.unsubscribeVisibility||(this.unsubscribeNetwork=this.runtime.onNetworkChange(e=>{this.handleNetworkChange(e)}),this.unsubscribeVisibility=this.runtime.onAppVisibilityChange(e=>{this.handleVisibilityChange(e)}))}stop(){this.unsubscribeNetwork?.(),this.unsubscribeVisibility?.(),this.unsubscribeNetwork=null,this.unsubscribeVisibility=null,this.lastOnline=null,this.lastForeground=null}handleNetworkChange(e){this.lastOnline!==e&&(this.lastOnline=e,e?this.handlers.onOnline():this.handlers.onOffline())}handleVisibilityChange(e){this.lastForeground!==e&&(this.lastForeground=e,e?this.handlers.onForeground():this.handlers.onBackground())}}const Pp="__internal:core";class xp{constructor(e,t){this.runtimeEventBridge=null,this.handleOnline=()=>{this.connectionManager.handleOnline()},this.handleOffline=()=>{this.connectionManager.handleOffline()},this.handleForegroundChange=e=>{e&&this.connectionManager.handleForeground()},this.eventHub=t,this.connectionManager=new Ph({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const r=this.connectionManager.getMsyncCodec(),s=e.restBaseUrl?new kp({restBaseUrl:e.restBaseUrl,token:e.token,appKey:e.appKey,useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,enableMultipartUpload:e.enableMultipartUpload,requestAdapter:e.platformAdapter?.request,uploadAdapter:e.platformAdapter?.upload,imageProcessor:e.platformAdapter?.imageProcessor}):void 0;this.messageSender=new cp(r,null,this.eventHub,s),this.messageReceiver=new pp(r,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new vp(e.platformAdapter?.request),this.attachmentDownloader=new _p(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(Pp,{[a]:e=>{const t=this.connectionManager.getWebSocket();t&&this.messageSender.setWebSocket(t)},[c]:e=>{this.messageSender.setWebSocket(null)},[d]:e=>{this.messageSender.setWebSocket(null)},[I]:e=>{this.messageReceiver.rememberSentMessageContext(e)}})}registerNetworkListeners(){const e=this.resolveRuntimeAdapter();this.runtimeEventBridge=new Dp(e,{onOnline:this.handleOnline,onOffline:this.handleOffline,onForeground:()=>{this.handleForegroundChange(!0)},onBackground:()=>{this.handleForegroundChange(!1)}}),this.runtimeEventBridge.start()}unregisterNetworkListeners(){this.runtimeEventBridge?.stop(),this.runtimeEventBridge=null}resolveRuntimeAdapter(){return this.platformAdapter?this.platformAdapter.runtime:this.createBrowserRuntimeAdapter()}createBrowserRuntimeAdapter(){return{getPlatform:()=>"web",onNetworkChange(e){if("undefined"==typeof window)return()=>{};const t=()=>{e(!0)},r=()=>{e(!1)};return window.addEventListener("online",t),window.addEventListener("offline",r),"undefined"!=typeof navigator&&"boolean"==typeof navigator.onLine&&e(navigator.onLine),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",r)}},onAppVisibilityChange(e){if("undefined"==typeof document)return()=>{};const t=()=>{e("visible"===document.visibilityState)};return document.addEventListener("visibilitychange",t),t(),()=>{document.removeEventListener("visibilitychange",t)}}}}async connect(e){return this.connectionManager.connect(e)}async disconnect(){return this.connectionManager.disconnect()}getConnectionStatus(){return this.connectionManager.getConnectionStatus()}recoverConnectionForSend(){return this.connectionManager.recoverConnectionForSend()}getClientResource(){return this.connectionManager.getClientResource()}renewToken(e,t){const r=this.connectionManager.renewToken(e,t);return this.messageSender.updateAuthToken(e),r}async sendMessage(e,t){return this.messageSender.sendMessage(e,t)}async sendMessageAction(e,t){return this.messageSender.sendAction(e,t)}async sendChatRoomOperation(e,t){return this.messageSender.sendChatRoomOperation(e,t)}async downloadAndParseCombineMessage(e){return this.combineMessageDownloader.downloadAndParse(e)}async downloadAttachment(e,t){return this.attachmentDownloader.download(e,t)}decodeServerMessageMeta(e){return this.connectionManager.getMsyncCodec().decodeServerMessageMeta(e)}destroy(){this.unregisterNetworkListeners(),this.connectionManager.destroy(),this.messageSender.destroy(),this.messageReceiver.destroy(),this.eventHub.removeEventHandler(Pp),xh.clear()}}const Fp=e=>{if(e.length>=1048576){const t=[],r=32768;for(let s=0;s<e.length;s+=r)t.push(String.fromCharCode(...e.subarray(s,s+r)));return btoa(t.join(""))}let t="";for(let r=0;r<e.length;r+=1){const s=e[r];void 0!==s&&(t+=String.fromCharCode(s))}return btoa(t)},Bp=e=>{const t=new Uint8Array(fa.util.base64.length(e));return fa.util.base64.decode(e,t,0),t};class Gp{getCrypto(){return fn().crypto}constructor(e,t){if(this.enabled=(()=>{const e=fn();if([e.wx,e.qq,e.tt,e.swan,e.my,e.dd,e.jd,e.ks,e.uni].some(e=>void 0!==e))return!1;const t=On(e);if("web"!==t.framework&&"worker"!==t.framework&&t.platform!==Js.ELECTRON_RENDERER)return!1;const r=e.crypto;return void 0!==r&&void 0!==r.subtle&&"function"==typeof r.getRandomValues&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder})(),this.enabled){const r=`${e}:${t}`;this.keyPromise=this.deriveKey(r)}else this.keyPromise=null}isEnabled(){return this.enabled}async encrypt(e){if(!this.enabled||!this.keyPromise)return e;const t=await this.keyPromise,r=new TextEncoder,s=this.getCrypto().getRandomValues(new Uint8Array(12)),n=r.encode(e),i=await this.getCrypto().subtle.encrypt({name:"AES-GCM",iv:s},t,n),o={__enc:!0,v:1,alg:"AES-GCM",kdf:"SHA-256",iv:Fp(s),ct:Fp(new Uint8Array(i))};return JSON.stringify(o)}async decrypt(e){if(!this.enabled||!this.keyPromise)return e;let t;try{t=JSON.parse(e)}catch{return e}if(!(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return!0===t.__enc&&1===t.v&&"AES-GCM"===t.alg&&"SHA-256"===t.kdf&&"string"==typeof t.iv&&"string"==typeof t.ct})(t))return e;try{const e=await this.keyPromise,r=Bp(t.iv),s=Bp(t.ct),n=await this.getCrypto().subtle.decrypt({name:"AES-GCM",iv:r},e,s);return(new TextDecoder).decode(n)}catch{return null}}async deriveKey(e){const t=(new TextEncoder).encode(e),r=this.getCrypto(),s=await r.subtle.digest("SHA-256",t);return r.subtle.importKey("raw",s,{name:"AES-GCM"},!1,["encrypt","decrypt"])}}const qp="conversationMap",$p="userInfoMap",jp="groupNamecardMap",Vp="contactRelationMap",Kp="contactVersion",zp="contactMeta",Hp="sessionListMap",Wp="sessionListCheckpoint",Jp="joinedGroupPreview",Qp="metadata",Zp=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class Yp{constructor(e,t,r){this.store=e,this.key=t,this.schemaVersion=r}async load(){const e={schemaVersion:this.schemaVersion,lastFlush:0},t=await this.store.readAsync(this.key,e);return t.schemaVersion!==this.schemaVersion?e:t}async save(e){await this.store.writeAsync(this.key,e)}async touchLastFlush(){const e={schemaVersion:this.schemaVersion,lastFlush:Date.now()};return await this.save(e),e}}const Xp=()=>{const e="undefined"!=typeof window?window.localStorage:void 0;if(e&&"function"==typeof e.getItem)return e;const t=fn().localStorage;return t&&"function"==typeof t.getItem?t:null};class em{constructor(e,t){this.storage=t??em.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!em.checkAvailable())return null;const e=Xp();return e?{getItem:t=>Promise.resolve(e.getItem(t)),setItem:(t,r)=>(e.setItem(t,r),Promise.resolve()),removeItem:t=>(e.removeItem(t),Promise.resolve())}:null}static checkAvailable(){const e=Xp();if(!e)return!1;try{const t="__im_sdk_cache_test__";return e.setItem(t,"1"),e.removeItem(t),!0}catch{return!1}}async readAsync(e,t){if(!this.storage)return t;try{const r=await this.storage.getItem(e);if(!r)return t;let s=r;if(this.cryptoAdapter&&this.cryptoAdapter.isEnabled()){const e=await this.cryptoAdapter.decrypt(r);if(null===e)return t;s=e}return mu(s,t)}catch(r){return Vs("CacheStore read failed",r),t}}async writeAsync(e,t){await this.writeInternal(e,t,!1)}async writeStrictAsync(e,t){await this.writeInternal(e,t,!0)}async writeInternal(e,t,r){if(!this.storage)return;const s=(e=>{try{return JSON.stringify(e)}catch{return null}})(t);if(null!==s)try{const t=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(s):s;await this.storage.setItem(e,t)}catch(n){if(Kc(n))throw n;if(r)throw n;Vs("CacheStore write failed",n)}else if(r)throw new TypeError("CacheStore value cannot be serialized")}async remove(e){if(this.storage)try{await this.storage.removeItem(e)}catch(t){Vs("CacheStore remove failed",t)}}}const tm={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},rm={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class sm{constructor(){this.items=new Map,this.versionState=tm,this.meta=rm}load(e,t,r){this.items.clear();for(const s of e){const e=this.normalizeRecord(s);e&&this.items.set(e.userId,e)}this.versionState=this.normalizeVersionState(t),this.meta=this.normalizeMeta(r)}getAll(){return Array.from(this.items.values()).sort((e,t)=>e.addTs!==t.addTs?e.addTs-t.addTs:e.userId.localeCompare(t.userId))}getVersionState(){return this.versionState}getMeta(){return this.meta}getUserIds(){return Array.from(this.items.keys())}replaceAll(e){this.items.clear(),this.upsert(e)}upsert(e){for(const t of e){const e=this.normalizeRecord(t);e&&this.items.set(e.userId,e)}}addByNotice(e,t){const r=e.trim();return!!r&&(!this.items.has(r)&&(this.items.set(r,{userId:r,remark:"",sign:"",addTs:t,updatedAt:t,metadataUpdatedAt:t}),!0))}remove(e){return this.items.delete(e)}updateRemark(e,t,r){const s=this.items.get(e);return!(!s||s.remark===t)&&(this.items.set(e,{...s,remark:t,updatedAt:r}),!0)}setVersionState(e){this.versionState=this.normalizeVersionState(e)}updateVersionFromNotice(e,t){const r=e.trim();return!!r&&((this.versionState.version!==r||"roster_notice"!==this.versionState.lastVersionSource)&&(this.versionState={version:r,lastVersionCheckAt:t,lastVersionSource:"roster_notice"},!0))}setMeta(e){this.meta=this.normalizeMeta(e)}updateMeta(e){this.meta={cacheIntegrity:e.cacheIntegrity,reason:"complete"===e.cacheIntegrity?void 0:e.reason,lastSyncTs:e.lastSyncTs??this.meta.lastSyncTs,lastSuccessfulVersion:e.lastSuccessfulVersion??this.meta.lastSuccessfulVersion,lastSyncMode:e.lastSyncMode??this.meta.lastSyncMode}}computeIntegrity(e){if(0===this.items.size&&!this.meta.lastSuccessfulVersion)return{...this.meta,cacheIntegrity:"incomplete",reason:"first_sync_pending"};const t=new Set(e.map(e=>e.userId));return this.getUserIds().some(e=>!t.has(e))?{...this.meta,cacheIntegrity:"incomplete",reason:"user_info_missing"}:{...this.meta,cacheIntegrity:"complete",reason:void 0}}buildSnapshot(e,t){const r=new Map(e.map(e=>[e.userId,e])),s=this.getAll().map(e=>{const t=r.get(e.userId);return{userId:e.userId,userInfo:{userId:e.userId,nickname:t?.nickname,avatarUrl:t?.avatarUrl,sign:t?.sign??e.sign,ext:t?.ext},remark:e.remark,addTs:e.addTs}}),n="complete"===this.computeIntegrity(e).cacheIntegrity;return{items:s,source:t,version:this.versionState.version||this.meta.lastSuccessfulVersion,complete:n}}normalizeRecord(e){if(!pu(e))return null;const t="string"==typeof e.userId?e.userId:"";return t?{userId:t,remark:"string"==typeof e.remark?e.remark:"",sign:"string"==typeof e.sign?e.sign:"",addTs:"number"==typeof e.addTs?e.addTs:0,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:0,metadataUpdatedAt:"number"==typeof e.metadataUpdatedAt?e.metadataUpdatedAt:0}:null}normalizeVersionState(e){return pu(e)?{version:"string"==typeof e.version?e.version:"",lastVersionCheckAt:"number"==typeof e.lastVersionCheckAt?e.lastVersionCheckAt:0,lastVersionSource:"metadata"===e.lastVersionSource||"sync_page"===e.lastVersionSource||"roster_notice"===e.lastVersionSource?e.lastVersionSource:"metadata"}:tm}normalizeMeta(e){return pu(e)?{cacheIntegrity:"complete"===e.cacheIntegrity?"complete":"incomplete",reason:"quota_exceeded"===e.reason||"user_info_missing"===e.reason||"corrupted"===e.reason||"manual_reset"===e.reason||"first_sync_pending"===e.reason?e.reason:void 0,lastSyncTs:"number"==typeof e.lastSyncTs?e.lastSyncTs:0,lastSuccessfulVersion:"string"==typeof e.lastSuccessfulVersion?e.lastSuccessfulVersion:"",lastSyncMode:"full"===e.lastSyncMode||"incremental"===e.lastSyncMode||"skipped"===e.lastSyncMode?e.lastSyncMode:"skipped"}:rm}}const nm=(e,t,r)=>{if(t<=0)return{kept:e,removed:[]};const s=[],n=[];for(const i of e)r-i.lastUpdate>t?n.push(i):s.push(i);return{kept:s,removed:n}},im=(e,t)=>{if(t<=0||0===e.length)return{kept:e,removed:[]};const r=[...e].sort((e,t)=>e.lastAccess-t.lastAccess).slice(0,t),s=new Set(r);return{kept:e.filter(e=>!s.has(e)),removed:r}},om=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r};class am{constructor(){this.items=[]}load(e,t){const r=[];for(const s of e){const e=this.normalizeItem(s,t);e&&r.push(e)}this.items=r}getAll(){return this.items}setAll(e){this.items=[...e]}updateLastAccess(e,t){if(0===e.length)return!1;let r=!1;for(const s of e){const e=this.findIndex(s.conversationId,s.type);if(e<0)continue;const n=this.items[e];n&&(n.lastAccess!==t&&(this.items[e]={...n,lastAccess:t},r=!0))}return r}removeExpired(e,t){const r=nm(this.items,e,t);return this.items=[...r.kept],r.removed.length>0}evictByLru(e){const t=im(this.items,e);return this.items=[...t.kept],t.removed.length>0}trimMax(e){if(!e||this.items.length<=e)return!1;const t=[...this.items].sort((e,t)=>e.lastAccess-t.lastAccess),r=Math.max(this.items.length-e,0),s=t.slice(0,r),n=new Set(s);return this.items=this.items.filter(e=>!n.has(e)),s.length>0}findIndex(e,t){return this.items.findIndex(r=>r.conversationId===e&&r.type===t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;const r=e;if("string"!=typeof r.conversationId||0===r.conversationId.length)return null;const s="single"===(n=r.type)||"chat"===n||"singleChat"===n?"singleChat":"group"===n||"groupchat"===n||"groupChat"===n?"groupChat":"room"===n||"chatroom"===n||"chatRoom"===n?"chatRoom":null;var n;if(!s)return null;const i=this.normalizeMessage(r.lastMessage);return{conversationId:r.conversationId,type:s,lastMessage:i,unreadCount:"number"==typeof r.unreadCount?r.unreadCount:0,isPinned:"boolean"==typeof r.isPinned?r.isPinned:void 0,pinnedTime:"number"==typeof r.pinnedTime?r.pinnedTime:void 0,marks:om(r.marks),lastAccess:"number"==typeof r.lastAccess?r.lastAccess:0,lastUpdate:"number"==typeof r.lastUpdate?r.lastUpdate:t}}normalizeMessage(e){if(!e||"object"!=typeof e)return null;if(!pu(e))return null;const t="string"==typeof e.msgId?e.msgId:"",r="string"==typeof e.type?e.type:"",s="number"==typeof e.timestamp?e.timestamp:0,n=pu(e.body)?e.body:{},i="number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,o="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return t?{msgId:t,type:r,body:n,timestamp:s,userInfoUpdateTime:i,namecardUpdateTime:o}:null}}const cm=(e,t)=>`${e}:${t}`;class dm{constructor(){this.items=new Map}load(e,t){this.items.clear();for(const r of e){const e=this.normalizeItem(r,t);e&&this.items.set(cm(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,r,s){const n=cm(e,t),i=this.items.get(n);return i?(s&&this.items.set(n,{...i,lastAccess:r}),i):null}getByGroupId(e,t,r){const s=[];for(const n of this.items.values())n.groupId===e&&(s.push(n),r&&this.items.set(cm(n.groupId,n.userId),{...n,lastAccess:t}));return s}setAll(e,t){for(const r of e){const e=this.normalizeItem(r,t);if(!e)continue;const s=cm(e.groupId,e.userId),n=this.items.get(s);this.items.set(s,{...e,lastAccess:n?.lastAccess??e.lastAccess,lastUpdate:t})}}remove(e){for(const t of e)this.items.delete(cm(t.groupId,t.userId))}removeExpired(e,t,r=new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!r.has(e.userId)),i=nm(n,e,t),o=new Set(i.removed.map(e=>cm(e.groupId,e.userId)));this.items.clear();for(const a of s)o.has(cm(a.groupId,a.userId))||this.items.set(cm(a.groupId,a.userId),a);return i.removed.length>0}evictByLru(e,t=new Set){const r=Array.from(this.items.values()),s=r.filter(e=>!t.has(e.userId)),n=im(s,Math.min(e,s.length)),i=new Set(n.removed.map(e=>cm(e.groupId,e.userId)));this.items.clear();for(const o of r)i.has(cm(o.groupId,o.userId))||this.items.set(cm(o.groupId,o.userId),o);return n.removed.length>0}trimMax(e,t=new Set){return!(e<=0||this.items.size<=e)&&this.evictByLru(Math.max(this.items.size-e,0),t)}normalizeItem(e,t){if(!e||!pu(e))return null;const r="string"==typeof e.groupId?e.groupId:"",s="string"==typeof e.userId?e.userId:"";if(!r||!s)return null;return{groupId:r,userId:s,namecard:"string"==typeof e.namecard?e.namecard:"",namecardUpdateTime:"number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0,lastSyncAt:"number"==typeof e.lastSyncAt?e.lastSyncAt:void 0,lastAccess:"number"==typeof e.lastAccess?e.lastAccess:0,lastUpdate:"number"==typeof e.lastUpdate?e.lastUpdate:t}}}const um=100,lm=3e3,hm=e=>({...e}),pm=e=>"object"==typeof e&&null!==e,mm=e=>"DEFAULT"===e||"ALL"===e||"AT"===e||"NONE"===e?e:"mentionOnly"===e?"AT":"mute"===e?"NONE":"default"===e?"DEFAULT":2===e?"AT":3===e?"NONE":0===e?"DEFAULT":1===e?"ALL":void 0;class fm{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:um,serverLimit:lm,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:um,serverLimit:lm,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return pm(t=e)&&"string"==typeof t.groupId&&0!==t.groupId.length?{groupId:t.groupId,name:"string"==typeof t.name?t.name:"",description:"string"==typeof t.description?t.description:void 0,memberCount:"number"==typeof t.memberCount?t.memberCount:void 0,role:"owner"===t.role||"admin"===t.role||"member"===t.role?t.role:void 0,disabled:"boolean"==typeof t.disabled?t.disabled:void 0,ownerId:"string"==typeof t.ownerId?t.ownerId:void 0,avatarUrl:"string"==typeof t.avatarUrl?t.avatarUrl:void 0,muteAllMembers:"boolean"==typeof t.muteAllMembers?t.muteAllMembers:void 0,muteExpiration:"number"==typeof t.muteExpiration?t.muteExpiration:void 0,remindType:mm(t.remindType),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,updatedAt:"number"==typeof t.updatedAt?t.updatedAt:void 0,joinedAt:"number"==typeof t.joinedAt?t.joinedAt:void 0}:null;var t}).filter(e=>null!==e):[];this.items=t.slice(0,um),this.meta=(e=>{const t=pm(e)?e:{};return{integrity:"synced"===t.integrity||"limited"===t.integrity||"incomplete"===t.integrity||"unknown"===t.integrity?t.integrity:"preview",limited:!0===t.limited,storageLimit:"number"==typeof t.storageLimit?t.storageLimit:um,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:lm,source:"localPreview",lastSyncFinishedTs:"number"==typeof t.lastSyncFinishedTs?t.lastSyncFinishedTs:void 0,lastSuccessfulAt:"number"==typeof t.lastSuccessfulAt?t.lastSuccessfulAt:void 0,reason:"string"==typeof t.reason?t.reason:void 0}})(e.meta)}setSnapshot(e){this.items=e.items.map(e=>hm(e)).slice(0,um),this.meta={...e.meta,source:"localPreview",storageLimit:um,serverLimit:lm,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>hm(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>hm(e)),meta:{...this.meta,source:"localPreview"}}}}const gm=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,ym=e=>{const t={...e};return delete t.type,t},vm=e=>{if(!pu(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!pu(e.body))return null;const r=((e,t)=>{if(pu(e)&&"string"==typeof e.userId){const t={userId:e.userId};return"string"==typeof e.nickname&&(t.nickname=e.nickname),"string"==typeof e.avatarUrl&&(t.avatarUrl=e.avatarUrl),t}return t?{userId:t}:null})(e.sender,e.from);if(!r)return null;const s=gm(e.conversationType),n=(e=>{if("sending"===e||"sent"===e||"failed"===e)return e})(e.sendStatus??e.status),i=(e=>{if("SEND"===e||"RECEIVE"===e)return e})(e.direct),o=(e=>{if(pu(e)&&"string"==typeof e.operatorId&&"number"==typeof e.operationCount&&"number"==typeof e.operationTime)return{operatorId:e.operatorId,operationCount:e.operationCount,operationTime:e.operationTime}})(e.modifiedInfo),a="number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,c="number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0;return{msgServerId:t,from:e.from,to:"string"==typeof e.to?e.to:"",sender:r,body:ym(e.body),timestamp:e.timestamp,..."string"==typeof e.conversationId?{conversationId:e.conversationId}:{},...s?{conversationType:s}:{},..."string"==typeof e.type&&e.type.length>0?{type:e.type}:{},...n?{sendStatus:n}:{},...i?{direct:i}:{},...o?{modifiedInfo:o}:{},...void 0!==a?{userInfoUpdateTime:a}:{},...void 0!==c?{namecardUpdateTime:c}:{}}},Im=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r},bm=(e,t)=>{const r="number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,s="number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:0;if(r!==s)return s-r;const n=e.lastMessageAt??e.updatedAt,i=t.lastMessageAt??t.updatedAt;return n!==i?i-n:e.conversationId.localeCompare(t.conversationId)};class _m{constructor(){this.items=[]}load(e,t){const r=[];for(const s of e){const e=this.normalizeItem(s,t);e&&r.push(e)}this.items=r.sort(bm)}getAll(){return this.items}setAll(e){const t=Date.now(),r=[];for(const s of e){const e=this.normalizeItem(s,t);e&&r.push(e)}this.items=r.sort(bm)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!pu(e))return null;const r=e,s="string"==typeof r.conversationId?r.conversationId:"";if(!s)return null;const n=gm(r.conversationType);if(!n)return null;const i="string"==typeof r.conversationName&&r.conversationName.length>0?r.conversationName:s,o="string"==typeof r.conversationAvatar?r.conversationAvatar:void 0;return{conversationId:s,conversationType:n,unreadCount:"number"==typeof e.unreadCount&&e.unreadCount>=0?Math.floor(e.unreadCount):0,lastMessage:vm(e.lastMessage),lastMessageAt:"number"==typeof e.lastMessageAt?e.lastMessageAt:void 0,isPinned:"boolean"==typeof e.isPinned?e.isPinned:void 0,pinnedTimestamp:"number"==typeof r.pinnedTimestamp?r.pinnedTimestamp:void 0,marks:Im(e.marks),readAt:"number"==typeof r.readAt?r.readAt:void 0,remindType:(a=e.remindType,"DEFAULT"===a||"ALL"===a||"AT"===a||"NONE"===a?a:"mentionOnly"===a?"AT":"mute"===a?"NONE":"DEFAULT"),conversationName:i,conversationAvatar:o,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:t};var a}}class Tm{constructor(){this.items=new Map}load(e,t){this.items.clear();for(const r of e){const e=this.normalizeItem(r,t);e&&this.items.set(e.userId,e)}}getAll(){return Array.from(this.items.values())}getByIds(e,t,r){const s=[];for(const n of e){const e=this.items.get(n);e&&(s.push(e),r&&this.items.set(n,{...e,lastAccess:t}))}return s}setAll(e,t){for(const r of e){const e=this.normalizeItem(r,t);if(!e)continue;const s=this.items.get(e.userId),n=s?.lastAccess??e.lastAccess;this.items.set(e.userId,{...e,lastAccess:n,lastUpdate:e.lastUpdate})}}remove(e){for(const t of e)this.items.delete(t)}removeExpired(e,t,r=new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!r.has(e.userId)),i=nm(n,e,t),o=new Set(i.removed.map(e=>e.userId));this.items.clear();for(const a of s)o.has(a.userId)||this.items.set(a.userId,a);return i.removed.length>0}evictByLru(e,t=new Set){const r=Array.from(this.items.values()),s=r.filter(e=>!t.has(e.userId)),n=im(s,Math.min(e,s.length)),i=new Set(n.removed.map(e=>e.userId));this.items.clear();for(const o of r)i.has(o.userId)||this.items.set(o.userId,o);return n.removed.length>0}trimMax(e,t=new Set){if(e<=0||this.items.size<=e)return!1;const r=Array.from(this.items.values()),s=Math.max(r.length-e,0);return this.evictByLru(s,t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;if(!pu(e))return null;const r="string"==typeof e.userId?e.userId:"";if(!r)return null;return{userId:r,nickname:"string"==typeof e.nickname?e.nickname:void 0,avatarUrl:"string"==typeof e.avatarUrl?e.avatarUrl:void 0,sign:"string"==typeof e.sign?e.sign:void 0,ext:"string"==typeof e.ext?e.ext:void 0,userInfoUpdateTime:"number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,lastSyncAt:"number"==typeof e.lastSyncAt?e.lastSyncAt:void 0,lastAccess:"number"==typeof e.lastAccess?e.lastAccess:0,lastUpdate:"number"==typeof e.lastUpdate?e.lastUpdate:t}}}const Cm=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,Sm=e=>e.lastMessageAt??e.updatedAt,Em=e=>[...e].sort((e,t)=>{const r=Cm(t)-Cm(e);if(0!==r)return r;const s=Sm(t)-Sm(e);return 0!==s?s:e.conversationId.localeCompare(t.conversationId)}),wm=e=>`${e.conversationType}:${e.conversationId}`,Rm=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,Am=(e,t)=>((e,t)=>Sm(t)>Sm(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:Rm(e,t),lastMessageAt:Math.max(e.lastMessageAt??0,t.lastMessageAt??0),isPinned:t.isPinned??e.isPinned,pinnedTimestamp:"number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:e.pinnedTimestamp,marks:t.marks.length>0?t.marks:e.marks,readAt:t.readAt??e.readAt,remindType:t.remindType??e.remindType,conversationName:t.conversationName===t.conversationId?e.conversationName:t.conversationName,conversationAvatar:t.conversationAvatar??e.conversationAvatar,updatedAt:Math.max(e.updatedAt,t.updatedAt)}:e,Nm=e=>{const t=new Map,r=new Set;for(const i of e.snapshot)r.add(wm(i));for(const i of e.existing)t.set(wm(i),i);const s=e.snapshot.map(e=>{const r=t.get(wm(e));return r?Am(e,r):e}),n=e.existing.filter(t=>!r.has(wm(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return Em([...s,...n])},Om=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Mm=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Um=e=>({userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,lastAccess:e.lastAccess,lastUpdate:e.lastModified});class Lm{constructor(){this.records=new Map}clear(){this.records.clear()}get(e,t=!1,r=Date.now()){const s=this.records.get(e)??null;if(!s||!t)return s;const n={...s,lastAccess:r};return this.records.set(e,n),n}setAll(e,t=Date.now()){for(const r of e){const e=r.lastModified??t,s=this.records.get(r.profile.userId),n=s?.lastAccess??t;this.records.set(r.profile.userId,{profile:r.profile,lastModified:e,lastAccess:n,source:r.source})}}applyPatch(e,t,r=Date.now()){const s=this.records.get(e.userId),n={userId:e.userId,...t??{},...s?.profile??{}};if(s&&e.lastModified<s.lastModified)return{applied:!1,reason:"stale",record:s};const i={...n,...e.attributes,userId:e.userId};if(s&&e.lastModified===s.lastModified&&(o=s.profile,a=i,Om.every(e=>o[e]===a[e])))return{applied:!1,reason:"duplicate",record:s};var o,a;const c={profile:i,lastModified:e.lastModified,lastAccess:s?.lastAccess??r,source:"subscription"===e.source?"subscription_notify":"contact"===e.source?"contact_notify":"own_notify"};return this.records.set(e.userId,c),{applied:!0,reason:"applied",record:c}}}const km=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class Dm{constructor(e){this.conversationDeletionTimestamps=new Map,this.currentConversation=null,this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.flushTimer=null,this.flushIdleHandle=null,this.activeFlushPromise=null,this.sessionListCommitInProgress=!1,this.mutationRevision=0,this.domainRevisions=new Map,this.pendingDirtyRevisions=new Map,this.userId=e.userId,this.config={schemaVersion:1,ttlSeconds:86400,flushIntervalMs:1e3,maxUserInfoCount:1e3,maxGroupNamecardCount:1e3,maxConversations:e.config?.maxConversations,...e.config};const t="off"===e.cacheEncryptionMode?null:new Gp(e.appKey,e.userId);this.store=new em(t??void 0,e.storageAdapter);const r={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=Zp(r,qp),this.userInfoKey=Zp(r,$p),this.groupNamecardKey=Zp(r,jp),this.sessionListKey=Zp(r,Hp),this.sessionListCheckpointKey=Zp(r,Wp),this.joinedGroupPreviewKey=Zp(r,Jp),this.contactRelationKey=Zp(r,Vp),this.contactVersionKey=Zp(r,Kp),this.contactMetaKey=Zp(r,zp),this.metadataKey=Zp(r,Qp),this.metadataStore=new Yp(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new am,this.userInfoCache=new Tm,this.groupNamecardCache=new dm,this.sessionListCache=new _m,this.joinedGroupPreviewCache=new fm,this.contactCache=new sm,this.userInfoRuntimeStore=new Lm,this.loadPromise=this.loadFromStorage()}getConfig(){return this.config}async prepare(){await this.loadPromise}loadConversationSummaries(){return this.conversationCache.getAll()}loadSessionList(){return this.sessionListCache.exportItems()}loadJoinedGroupPreviewSnapshot(){return this.joinedGroupPreviewCache.getSnapshot()}applyJoinedGroupPreviewSnapshot(e){this.joinedGroupPreviewCache.setSnapshot(e),this.scheduleFlush(["joinedGroupPreview"])}async commitJoinedGroupPreviewSnapshot(e){this.activeFlushPromise&&await this.activeFlushPromise;const t=this.getDomainRevision("joinedGroupPreview"),r=new fm;if(r.setSnapshot(e),await this.store.writeStrictAsync(this.joinedGroupPreviewKey,r.exportRecord()),this.getDomainRevision("joinedGroupPreview")!==t)return this.ensureFlushScheduled(),this.loadJoinedGroupPreviewSnapshot();this.joinedGroupPreviewCache.setSnapshot(e),this.mutationRevision+=1,this.domainRevisions.set("joinedGroupPreview",this.mutationRevision);const s=this.pendingDirtyRevisions.get("joinedGroupPreview");return void 0!==s&&s<=this.mutationRevision&&this.pendingDirtyRevisions.delete("joinedGroupPreview"),await this.metadataStore.touchLastFlush(),this.loadJoinedGroupPreviewSnapshot()}async removeJoinedGroupPreview(e){const t=this.loadJoinedGroupPreviewSnapshot(),r=t.items.filter(t=>t.groupId!==e);return r.length===t.items.length?t:(this.applyJoinedGroupPreviewSnapshot({items:r,meta:{...t.meta}}),await this.flushPending(),this.loadJoinedGroupPreviewSnapshot())}loadSessionListCheckpoint(){return this.sessionListCheckpoint}async flushPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),null!==this.flushIdleHandle&&"undefined"!=typeof cancelIdleCallback&&(cancelIdleCallback(this.flushIdleHandle),this.flushIdleHandle=null),await this.flushNow(),this.activeFlushPromise&&await this.activeFlushPromise,this.pendingDirtyRevisions.size>0&&await this.flushNow()}resetSessionListCheckpoint(){this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.scheduleFlush(["sessionList"])}loadUserInfoSummaries(){return this.userInfoCache.getAll()}loadGroupNamecards(e){return e?this.groupNamecardCache.getByGroupId(e,Date.now(),!1):this.groupNamecardCache.getAll()}loadContactSnapshot(e="cache"){const t=this.contactCache.buildSnapshot(this.userInfoCache.getAll(),e);return{...t,items:t.items.map(e=>({...e,userInfo:this.userInfoRuntimeStore.get(e.userId,!1)?.profile??e.userInfo}))}}loadContactRelationRecords(){return this.contactCache.getAll()}loadContactVersionState(){return this.contactCache.getVersionState()}loadContactCacheMeta(){return this.contactCache.getMeta()}markConversationAccess(e){const t=Date.now();this.conversationCache.updateLastAccess(e,t)&&this.scheduleFlush(["conversation"])}setCurrentConversation(e){this.currentConversation={conversationId:e.conversationId,type:e.type}}resetCurrentConversation(){this.currentConversation=null}getCurrentConversation(){return this.currentConversation}clearConversationUnreadMessageCount(e){const t=e.readAt??Date.now();let r=!1,s=!1;const n=this.conversationCache.getAll().map(n=>n.conversationId!==e.conversationId||n.type!==e.type?n:(r=!0,0===n.unreadCount?n:(s=!0,{...n,unreadCount:0,lastUpdate:t})));let i=!1;const o=this.sessionListCache.getAll().map(s=>s.conversationId!==e.conversationId||s.conversationType!==e.type?s:(r=!0,0===s.unreadCount&&s.readAt===t?s:(i=!0,{...s,unreadCount:0,readAt:t,updatedAt:t})));return s||i?(s&&this.conversationCache.setAll(n),i&&this.sessionListCache.setAll(o),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0,matched:r}):{items:this.sessionListCache.exportItems(),changed:!1,matched:r}}clearAllConversationUnreadMessageCount(e){const t=e?.readAt??Date.now(),r=this.conversationCache.getAll(),s=r.map(e=>0===e.unreadCount?e:{...e,unreadCount:0,lastUpdate:t}),n=this.sessionListCache.getAll(),i=n.map(e=>0===e.unreadCount&&e.readAt===t?e:{...e,unreadCount:0,readAt:t,updatedAt:t}),o=!this.isConversationListEqual(r,s),a=!this.isSessionListEqual(n,i);return o||a?(o&&this.conversationCache.setAll(s),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationPinnedMutation(e){const t=Date.now(),r=this.conversationCache.getAll(),s=this.conversationCache.getAll().map(r=>r.conversationId!==e.conversationId||r.type!==e.type?r:{...r,isPinned:e.isPinned,pinnedTime:e.isPinned?e.pinnedTime??t:0,lastUpdate:t}),n=this.sessionListCache.getAll(),i=n.map(r=>r.conversationId!==e.conversationId||r.conversationType!==e.type?r:{...r,isPinned:e.isPinned,pinnedTimestamp:e.isPinned?e.pinnedTime??t:0,updatedAt:t}),o=!this.isConversationListEqual(r,s),a=!this.isSessionListEqual(n,i);return o||a?(o&&this.conversationCache.setAll(s),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}deleteConversation(e){const t=this.conversationCache.getAll(),r=this.sessionListCache.getAll();if("number"==typeof e.deletedAt&&this.getConversationLatestUpdate(t,r,e.conversationId,e.type)>e.deletedAt)return{items:this.sessionListCache.exportItems(),changed:!1};if("number"==typeof e.deletedAt){const t=this.buildConversationKey(e.conversationId,e.type),r=this.conversationDeletionTimestamps.get(t)??0;this.conversationDeletionTimestamps.set(t,Math.max(r,e.deletedAt))}const s=t.filter(t=>t.conversationId!==e.conversationId||t.type!==e.type),n=r.filter(t=>t.conversationId!==e.conversationId||t.conversationType!==e.type),i=s.length!==t.length,o=n.length!==r.length;return i||o?(i&&this.conversationCache.setAll(s),o&&this.sessionListCache.setAll(n),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}clearConversations(){const e=this.conversationCache.getAll().length>0,t=this.sessionListCache.getAll().length>0;return e||t?(e&&this.conversationCache.setAll([]),t&&this.sessionListCache.setAll([]),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationMarkMutation(e){const t=new Set(e.conversations.filter(e=>e.applied).map(e=>`${e.conversationType}:${e.conversationId}`));if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const r=Date.now(),s=t=>"addMark"===e.operation?t.includes(e.mark)?t:[...t,e.mark]:t.filter(t=>t!==e.mark),n=this.conversationCache.getAll(),i=n.map(e=>{const n=`${e.type}:${e.conversationId}`;if(!t.has(n))return e;const i=s(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,lastUpdate:r}}),o=this.sessionListCache.getAll(),a=o.map(e=>{const n=`${e.conversationType}:${e.conversationId}`;if(!t.has(n))return e;const i=s(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,updatedAt:r}}),c=!this.isConversationListEqual(n,i),d=!this.isSessionListEqual(o,a);return c||d?(c&&this.conversationCache.setAll(i),d&&this.sessionListCache.setAll(a),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}replaceSessionList(e,t,r){const s=Date.now(),n=e.map(e=>({...e,updatedAt:e.lastMessageAt??s})),i=Nm({snapshot:n,existing:this.sessionListCache.getAll(),syncStartedAt:r?.syncStartedAt});this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(i,s)),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}mergeSessionListIncremental(e,t){this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(this.buildIncrementalSessionListRecords(e))),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}async commitSessionListSync(e){this.activeFlushPromise&&await this.activeFlushPromise,this.sessionListCommitInProgress=!0;let t=[],r=this.getDomainRevision("sessionList");try{let s=!1;for(;!s;){const n=this.getDomainRevision("sessionList");t=this.buildSessionListSyncCandidate(e),await this.writeSessionListStorageRecord(t,e.checkpoint,!0),r=this.getDomainRevision("sessionList"),r===n&&(s=!0)}this.sessionListCache.setAll(t),this.sessionListCheckpoint=e.checkpoint;const n=this.pendingDirtyRevisions.get("sessionList");return void 0!==n&&n<=r&&this.pendingDirtyRevisions.delete("sessionList"),await this.metadataStore.touchLastFlush(),{items:this.sessionListCache.exportItems(),checkpoint:this.sessionListCheckpoint}}finally{this.sessionListCommitInProgress=!1,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}setUserInfoSummaries(e){const t=Date.now();this.userInfoCache.setAll(e,t),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}upsertRuntimeUserInfos(e){0!==e.length&&this.userInfoRuntimeStore.setAll(e)}getRuntimeUserInfo(e,t=!1){return this.userInfoRuntimeStore.get(e,t)?.profile??null}applyUserInfoNotifyPatch(e){const t=this.userInfoCache.getByIds([e.userId],Date.now(),!1)[0],r=t?Mm(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,r)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([Um(t)])}getUserInfoSummaries(e,t){const r=Date.now(),s=this.userInfoCache.getByIds(e,r,t);return t&&this.scheduleFlush(["userInfo"]),s}removeUserInfo(e){this.userInfoCache.remove(e),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}getGroupNamecard(e,t,r){const s=this.groupNamecardCache.get(e,t,Date.now(),r);return r&&s&&this.scheduleFlush(["groupNamecard"]),s}setGroupNamecards(e){const t=Date.now();this.groupNamecardCache.setAll(e,t),"number"==typeof this.config.maxGroupNamecardCount&&this.groupNamecardCache.trimMax(this.config.maxGroupNamecardCount),this.scheduleFlush(["groupNamecard"])}removeGroupNamecards(e){this.groupNamecardCache.remove(e),this.scheduleFlush(["groupNamecard"])}setContactVersionState(e){this.contactCache.setVersionState(e),this.scheduleFlush(["contactVersion"])}markContactCacheIncomplete(e){this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:e}),this.scheduleFlush(["contactMeta"])}applyContactSync(e){const t=this.loadContactSnapshot("cache"),r=Date.now();this.userInfoCache.setAll(e.userInfos.map(e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext,lastAccess:r,lastUpdate:r})),r),"full"===e.mode?this.contactCache.replaceAll(e.relations):this.contactCache.upsert(e.relations),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.contactCache.setVersionState({version:e.version,lastVersionCheckAt:r,lastVersionSource:"sync_page"}),this.contactCache.updateMeta({cacheIntegrity:"complete",lastSyncTs:e.lastSyncTs,lastSuccessfulVersion:e.version,lastSyncMode:e.mode}),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactRelation","contactVersion","contactMeta"]);const s=this.loadContactSnapshot("sync");return{snapshot:s,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(s)}}refreshSessionListDisplayFromUserInfos(e){const t=new Map;for(const d of e){if(!d.userId)continue;const e=t.get(d.userId);"number"==typeof e&&"number"==typeof d.lastModified&&e>=d.lastModified||t.set(d.userId,d.lastModified)}if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const r=Date.now(),s=this.loadContactSnapshot("cache").items,n=new Map(s.map(e=>[e.userId,e])),i=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e])),o=this.sessionListCache.getAll().map(e=>{let s=e;if("singleChat"===e.conversationType&&!this.shouldSkipSessionUserDisplayRefresh(e.conversationId,t,i)){const t=n.get(e.conversationId),o=this.resolveSessionDisplayUserInfo(e.conversationId,i),a=this.buildSingleSessionDisplayFields(e.conversationId,t,o,e.conversationName,e.conversationAvatar);e.conversationName===a.conversationName&&e.conversationAvatar===a.conversationAvatar||(s={...s,conversationName:a.conversationName,conversationAvatar:a.conversationAvatar,updatedAt:r})}const o=s.lastMessage;if(o&&!this.shouldSkipSessionUserDisplayRefresh(o.sender.userId,t,i)){const e=n.get(o.sender.userId),t=this.resolveSessionDisplayUserInfo(o.sender.userId,i),a=this.buildSessionMessageSender(o.sender.userId,o.sender,e,t);this.isSenderEqual(o.sender,a)||(s={...s,lastMessage:{...o,sender:a},updatedAt:r})}return s}),a=this.sessionListCache.getAll(),c=!this.isSessionListEqual(a,o);return c&&(this.sessionListCache.setAll(o),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:c}}refreshSessionListDisplayFromJoinedGroups(e,t){const r=new Map;for(const a of e){const e=a.groupId.trim();e&&r.set(e,a)}if(0===r.size)return{items:this.sessionListCache.exportItems(),changed:!1};const s=Date.now(),n=this.sessionListCache.getAll().map(e=>{if("groupChat"!==e.conversationType)return e;const n=r.get(e.conversationId);if(!n)return e;const i=Boolean(e.conversationName.trim())&&e.conversationName!==e.conversationId;if(t?.onlyWhenNameMissing&&i)return e;const o=n.name?.trim(),a=o||e.conversationName,c=n.avatarUrl??e.conversationAvatar,d=this.mapJoinedGroupRemindTypeToSession(n.remindType),u=void 0!==d&&d!==e.remindType;return a!==e.conversationName||c!==e.conversationAvatar||u?{...e,conversationName:a,conversationAvatar:c,remindType:u?d:e.remindType,updatedAt:s}:e}),i=this.sessionListCache.getAll(),o=!this.isSessionListEqual(i,n);return o&&(this.sessionListCache.setAll(n),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:o}}removeContact(e){return this.applyContactLocalPatch(()=>this.contactCache.remove(e))}updateContactRemark(e,t){return this.applyContactLocalPatch(()=>this.contactCache.updateRemark(e,t,Date.now()))}applyContactRosterNotice(e){const t=this.loadContactSnapshot("cache"),r=Date.now(),s="add"===e.action?this.contactCache.addByNotice(e.userId,r):this.contactCache.remove(e.userId),n="string"==typeof e.rosterVersion&&e.rosterVersion.trim().length>0&&this.contactCache.updateVersionFromNotice(e.rosterVersion,r);(s||n)&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactVersion","contactMeta"]));const i=this.loadContactSnapshot("cache");return{snapshot:i,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(i)}}updateConversationsFromServer(e,t){const r=Date.now(),s=this.conversationCache.getAll(),n=this.mergeConversationLists(s,e,r,t?.syncStartedAt),i=!this.isConversationListEqual(s,n);return this.conversationCache.setAll(n),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:n,changed:i}}applyIncomingMessageToConversations(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.conversationCache.getAll(),changed:!1};const r=Date.now(),s=this.conversationCache.getAll(),n=s.findIndex(e=>e.conversationId===t.conversationId&&e.type===t.type),i=n>=0?s[n]:void 0,o=this.buildConversationFromMessage(e,i,r);if(!o)return{items:s,changed:!1};const a=[o,...s.filter((e,t)=>t!==n)];return this.isConversationListEqual(s,a)?{items:s,changed:!1}:(this.conversationCache.setAll(a),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:this.conversationCache.getAll(),changed:!0})}applyIncomingMessageToSessionList(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.sessionListCache.exportItems(),changed:!1};const r=this.sessionListCache.getAll(),s=r.find(e=>e.conversationId===t.conversationId&&e.conversationType===t.type),n=this.conversationCache.getAll().find(e=>e.conversationId===t.conversationId&&e.type===t.type)??this.buildConversationFromMessage(e,void 0,Date.now());if(!n)return{items:this.sessionListCache.exportItems(),changed:!1};const i=(e=>{const t=wm(e.nextRecord),r=e.existing.filter(e=>wm(e)!==t);return Em([e.nextRecord,...r])})({existing:r,nextRecord:this.buildSessionListRecordFromConversation(n,e,s,Date.now())});return this.isSessionListEqual(r,i)?{items:this.sessionListCache.exportItems(),changed:!1}:(this.sessionListCache.setAll(i),this.scheduleFlush(["sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0})}async loadFromStorage(){const e=Date.now(),t=await this.readDump(this.conversationKey);this.conversationCache.load(t,e);const r=await this.readDump(this.userInfoKey);this.userInfoCache.load(r,e);const s=await this.readDump(this.groupNamecardKey);this.groupNamecardCache.load(s,e);const n=await this.readValue(this.sessionListKey,null),i=n&&pu(n)&&Array.isArray(n.items)?n.items:[];this.sessionListCache.load(i,e);const o=(n&&pu(n)&&pu(n.checkpoint)?n.checkpoint:null)??await this.readValue(this.sessionListCheckpointKey,null);this.sessionListCheckpoint=this.normalizeSessionListCheckpoint(o);const a=await this.readValue(this.joinedGroupPreviewKey,null);this.joinedGroupPreviewCache.load(a);const c=await this.readDump(this.contactRelationKey),d=await this.readValue(this.contactVersionKey,null),u=await this.readValue(this.contactMetaKey,null);this.contactCache.load(c,d,u),this.refreshContactCacheIntegrity(!1),await this.metadataStore.load()}async readDump(e){const t=await this.store.readAsync(e,{items:[]});return t&&pu(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&pu(e)?{lastSyncTime:"number"==typeof e.lastSyncTime?e.lastSyncTime:0,lastSyncFinishedTs:"number"==typeof e.lastSyncFinishedTs?e.lastSyncFinishedTs:0,sessionsLastSyncTs:"number"==typeof e.sessionsLastSyncTs?e.sessionsLastSyncTs:0,lastSuccessfulAt:"number"==typeof e.lastSuccessfulAt?e.lastSuccessfulAt:0}:{lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0}}scheduleFlush(e){this.markDirty(e),this.ensureFlushScheduled()}markDirty(e){if(0!==e.length){this.mutationRevision+=1;for(const t of e)this.domainRevisions.set(t,this.mutationRevision),this.pendingDirtyRevisions.set(t,this.mutationRevision)}}getDomainRevision(e){return this.domainRevisions.get(e)??0}ensureFlushScheduled(){null===this.flushTimer&&null===this.flushIdleHandle&&("undefined"==typeof requestIdleCallback?this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flushNow()},this.config.flushIntervalMs):this.flushIdleHandle=requestIdleCallback(()=>{this.flushIdleHandle=null,this.flushNow()},{timeout:this.config.flushIntervalMs}))}takePendingDirtyBatch(){const e=this.pendingDirtyRevisions;return this.pendingDirtyRevisions=new Map,e}restoreDirtyBatch(e){for(const[t,r]of e){const e=this.pendingDirtyRevisions.get(t)??0;this.pendingDirtyRevisions.set(t,Math.max(r,e))}}addQuotaCleanupDomains(e,t){"none"!==t&&(this.mutationRevision+=1,this.domainRevisions.set(t,this.mutationRevision),this.domainRevisions.set("contactMeta",this.mutationRevision),e.set(t,this.mutationRevision),e.set("contactMeta",this.mutationRevision))}async flushNow(){if(this.activeFlushPromise)return void(await this.activeFlushPromise);const e=this.takePendingDirtyBatch();if(this.sessionListCommitInProgress){const t=e.get("sessionList");void 0!==t&&(e.delete("sessionList"),this.restoreDirtyBatch(new Map([["sessionList",t]])))}if(0===e.size)return;const t=this.flushDirtyBatch(e);this.activeFlushPromise=t;try{await t}finally{this.activeFlushPromise=null,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}async flushDirtyBatch(e){try{const s=6;for(let n=0;n<=s;n+=1)try{return await this.writeDirtyDomains(e),void(await this.metadataStore.touchLastFlush())}catch(t){if(!Kc(t))return this.restoreDirtyBatch(e),void Vs("Cache flush failed",t);const s=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(e,s),"none"===s)return void Vs("Cache flush failed: no cache entry can be evicted",t);try{await this.writeDomain(s)}catch(r){if(!Kc(r))return this.restoreDirtyBatch(e),void Vs("Cache quota cleanup persistence failed",r)}}Vs("Cache flush failed after quota cleanup attempts")}finally{}}async writeDirtyDomains(e){for(const t of km)e.has(t)&&await this.writeDomain(t)}async writeDomain(e){switch(e){case"conversation":return void(await this.store.writeAsync(this.conversationKey,{items:this.conversationCache.getAll()}));case"userInfo":return void(await this.store.writeAsync(this.userInfoKey,{items:this.userInfoCache.getAll()}));case"groupNamecard":return void(await this.store.writeAsync(this.groupNamecardKey,{items:this.groupNamecardCache.getAll()}));case"sessionList":return void(await this.writeSessionListStorageRecord());case"joinedGroupPreview":return void(await this.store.writeAsync(this.joinedGroupPreviewKey,this.joinedGroupPreviewCache.exportRecord()));case"contactRelation":return void(await this.store.writeAsync(this.contactRelationKey,{items:this.contactCache.getAll()}));case"contactVersion":return void(await this.store.writeAsync(this.contactVersionKey,this.contactCache.getVersionState()));case"contactMeta":await this.store.writeAsync(this.contactMetaKey,this.contactCache.getMeta())}}async writeSessionListStorageRecord(e=this.sessionListCache.getAll(),t=this.sessionListCheckpoint,r=!1){const s={items:e,checkpoint:t};r?await this.store.writeStrictAsync(this.sessionListKey,s):await this.store.writeAsync(this.sessionListKey,s),await this.store.remove(this.sessionListCheckpointKey)}buildIncrementalSessionListRecords(e){const t=this.sessionListCache.getAll(),r=new Map;for(const n of t)r.set(`${n.conversationType}:${n.conversationId}`,n);const s=Date.now();return(e=>{const t=e.incoming.filter(e=>Cm(e)>0),r=new Map;for(const n of e.incoming)r.set(wm(n),n);const s=t.length>0?e.existing.filter(e=>!r.has(wm(e))&&0===Cm(e)):e.existing.filter(e=>!r.has(wm(e)));return Em([...s,...e.incoming])})({existing:t,incoming:this.filterItemsAgainstConversationDeletions(e).map(e=>{const t=`${e.conversationType}:${e.conversationId}`;return{...e,updatedAt:e.lastMessageAt??r.get(t)?.updatedAt??s}})})}buildSessionListSyncCandidate(e){const t=Date.now();if("incremental"===e.mode)return this.hydrateSessionListRecordsFromLocalProfiles(this.buildIncrementalSessionListRecords(e.items),t);const r=this.filterItemsAgainstConversationDeletions(e.items).map(e=>({...e,updatedAt:e.lastMessageAt??t}));return this.hydrateSessionListRecordsFromLocalProfiles(Nm({snapshot:r,existing:this.sessionListCache.getAll(),syncStartedAt:e.syncStartedAt}),t)}filterItemsAgainstConversationDeletions(e){return e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.conversationType),r=this.conversationDeletionTimestamps.get(t);if(void 0===r)return!0;return Math.max(e.lastMessageAt??0,e.lastMessage?.timestamp??0)>r})}getConversationLatestUpdate(e,t,r,s){const n=e.find(e=>e.conversationId===r&&e.type===s),i=t.find(e=>e.conversationId===r&&e.conversationType===s);return Math.max(n?.lastUpdate??0,n?.lastMessage?.timestamp??0,i?.updatedAt??0,i?.lastMessageAt??0,i?.lastMessage?.timestamp??0)}handleQuotaExceeded(){const e=Date.now(),t=1e3*this.config.ttlSeconds;if(this.groupNamecardCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard";const r=this.groupNamecardCache.getAll().length;if(r>0){const e=this.calculateEvictCount(r,.2);if(this.groupNamecardCache.evictByLru(e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard"}if(this.userInfoCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"userInfo";const s=this.evictByPolicy();return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),s}evictByPolicy(){const e=this.userInfoCache.getAll().length;if(e>0){const t=this.calculateEvictCount(e,.2);return t>0?(this.userInfoCache.evictByLru(t),"userInfo"):"none"}const t=this.conversationCache.getAll().length,r=this.calculateEvictCount(t,.05);return r>0?(this.conversationCache.evictByLru(r),"conversation"):"none"}calculateEvictCount(e,t){if(e<=0)return 0;const r=Math.floor(e*t);return Math.max(r,1)}mergeConversationLists(e,t,r,s){const n=new Map,i=new Map;for(const d of e){const e=this.buildConversationKey(d.conversationId,d.type);n.set(e,d.lastAccess),i.set(e,d)}const o=[],a=new Set;for(const d of t){const e=this.buildConversationKey(d.conversationId,d.type);a.add(e);const t=n.get(e)??r;o.push({...d,marks:Array.isArray(d.marks)?d.marks:[],lastAccess:t,lastUpdate:r})}const c=e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.type);return!a.has(t)&&("number"==typeof s&&e.lastUpdate>s)});return[...o,...c]}isConversationListEqual(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){const s=e[r],n=t[r];if(!s||!n)return!1;if(this.buildConversationSignature(s)!==this.buildConversationSignature(n))return!1}return!0}buildConversationSignature(e){const t=e.lastMessage,r=t?`${t.msgId}:${t.type}:${t.timestamp}:${JSON.stringify(t.body)}`:"none",s=e.isPinned?"1":"0",n="number"==typeof e.pinnedTime?e.pinnedTime:0,i=e.marks.join(",");return`${e.type}:${e.conversationId}:${e.unreadCount}:${s}:${n}:${i}:${r}`}buildConversationKey(e,t){return`${t}:${e}`}areConversationMarksEqual(e,t){return e.length===t.length&&e.every((e,r)=>e===t[r])}buildConversationFromMessage(e,t,r=Date.now()){const s=this.resolveConversationFromMessage(e);if(!s)return null;const n=e.msgServerId||e.msgLocalId,i=t?.lastMessage?.msgId!==n&&this.shouldIncreaseUnreadForMessage(e)?(t?.unreadCount??0)+1:t?.unreadCount??0,o="SEND"===e.direct?r:t?.lastAccess??r;return{conversationId:s.conversationId,type:s.type,lastMessage:this.buildMessageSnippet(e),unreadCount:i,isPinned:t?.isPinned,pinnedTime:t?.pinnedTime,marks:t?.marks??[],lastAccess:o,lastUpdate:r}}resolveConversationFromMessage(e){if(e.isChatThread||"cmd"===e.type)return null;if("string"!=typeof e.conversationId||!e.conversationId)return null;if("singleChat"===e.conversationType){const t="RECEIVE"===e.direct&&e.from.startsWith(`${this.userId}/`)&&e.sender.userId===this.userId,r="SEND"===e.direct||t?e.conversationId:"string"==typeof e.sender.userId?e.sender.userId:"";return r?{conversationId:r,type:"singleChat"}:null}return"groupChat"===e.conversationType?{conversationId:e.conversationId,type:"groupChat"}:"chatRoom"===e.conversationType?{conversationId:e.conversationId,type:"chatRoom"}:null}buildMessageSnippet(e){const t=(e=>{const t=Wu(e);return{userInfoUpdateTime:t?.userInfoUpdateTime,namecardUpdateTime:"groupChat"===e.conversationType?t?.namecardUpdateTime:void 0}})(e);return{msgId:e.msgServerId||e.msgLocalId,type:e.type,body:this.normalizeMessageBody(e.body),timestamp:e.timestamp,userInfoUpdateTime:t.userInfoUpdateTime,namecardUpdateTime:t.namecardUpdateTime,modifiedInfo:e.modifiedInfo}}normalizeMessageBody(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}buildSessionListRecordFromConversation(e,t,r,s=Date.now()){const n=new Map(this.loadContactSnapshot("cache").items.map(e=>[e.userId,e])),i=n.get(e.conversationId),o=this.userInfoRuntimeStore.get(e.conversationId,!1)?.profile,a=this.userInfoCache.getByIds([e.conversationId],s,!1)[0],c=o??(a?{userId:a.userId,nickname:a.nickname,avatarUrl:a.avatarUrl,sign:a.sign,ext:a.ext}:null),d=e.lastMessage,u=r?.conversationName,l=r?.conversationAvatar,h="string"==typeof t.sender.userId?t.sender.userId:"",p=this.resolveSessionDisplayUserInfo(h),m=this.buildSessionMessageSender(h,t.sender,n.get(h),p),f="singleChat"===e.type?"SEND"===t.direct?e.conversationId:this.userId:e.conversationId,g="singleChat"===e.type?this.buildSingleSessionDisplayFields(e.conversationId,i,c,u,l):"chatRoom"===e.type?this.buildChatRoomSessionDisplayFields(e.conversationId,u,l):this.buildGroupSessionDisplayFields(e.conversationId,u,l);return{conversationId:e.conversationId,conversationType:e.type,unreadCount:this.resolveSessionListUnreadCount(e,t,r),lastMessage:d?{msgServerId:d.msgId,from:h,to:f,sender:m,conversationId:e.conversationId,conversationType:e.type,type:t.type,sendStatus:t.sendStatus,timestamp:d.timestamp,direct:t.direct,body:d.body}:null,lastMessageAt:d?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:r?.readAt,remindType:r?.remindType??"DEFAULT",conversationName:g.conversationName,conversationAvatar:g.conversationAvatar,updatedAt:s}}resolveSessionListUnreadCount(e,t,r){const s=r?.unreadCount,n=t.msgServerId||t.msgLocalId;return r?.lastMessage?.msgServerId!==n&&this.shouldIncreaseUnreadForMessage(t)?"number"==typeof s?Math.max(e.unreadCount,s+1):e.unreadCount:"number"==typeof s?Math.max(e.unreadCount,s):e.unreadCount}shouldIncreaseUnreadForMessage(e){if("RECEIVE"!==e.direct||!1===e.isOnline)return!1;const t=this.resolveConversationFromMessage(e);return!t||!this.currentConversation||(this.currentConversation.conversationId!==t.conversationId||this.currentConversation.type!==t.type)}buildSingleSessionDisplayFields(e,t,r,s,n){const i=t?.remark?.trim(),o=t?.userInfo.avatarUrl??r?.avatarUrl??n;if(i)return{conversationName:i,conversationAvatar:o};const a=t?.userInfo.nickname?.trim()||r?.nickname?.trim();return a?{conversationName:a,conversationAvatar:o}:s?{conversationName:s,conversationAvatar:o}:{conversationName:e,conversationAvatar:o}}shouldSkipSessionUserDisplayRefresh(e,t,r){if(!t.has(e))return!0;const s=t.get(e),n=r.get(e);return"number"==typeof s&&"number"==typeof n?.lastUpdate&&n.lastUpdate>s}hydrateSessionListRecordsFromLocalProfiles(e,t=Date.now()){const r=this.loadContactSnapshot("cache").items,s=new Map(r.map(e=>[e.userId,e])),n=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e]));return e.map(e=>{const r=e.lastMessage;if(!r)return e;const i=r.sender.userId,o=s.get(i),a=this.resolveSessionDisplayUserInfo(i,n),c="singleChat"===e.conversationType&&i===e.conversationId?this.buildSingleChatPeerMessageSender(i,r.sender,o,a):this.buildSessionMessageSender(i,r.sender,o,a);return this.isSenderEqual(r.sender,c)?e:{...e,lastMessage:{...r,sender:c},updatedAt:t}})}resolveSessionDisplayUserInfo(e,t){const r=this.userInfoRuntimeStore.get(e,!1)?.profile;if(r)return r;const s=t?.get(e)??this.userInfoCache.getByIds([e],Date.now(),!1)[0];return s?Mm(s):null}buildSessionMessageSender(e,t,r,s){const n=r?.remark?.trim();return{userId:e,nickname:n||r?.userInfo.nickname?.trim()||s?.nickname?.trim()||t?.nickname?.trim()||void 0,avatarUrl:r?.userInfo.avatarUrl??s?.avatarUrl??t?.avatarUrl}}buildSingleChatPeerMessageSender(e,t,r,s){const n=this.buildSessionMessageSender(e,void 0,r,s);return{userId:e,nickname:t?.nickname?.trim()||n.nickname,avatarUrl:t?.avatarUrl||n.avatarUrl}}isSenderEqual(e,t){return e.userId===t.userId&&e.nickname===t.nickname&&e.avatarUrl===t.avatarUrl}buildGroupSessionDisplayFields(e,t,r){return t?{conversationName:t,conversationAvatar:r}:{conversationName:e}}mapJoinedGroupRemindTypeToSession(e){if("DEFAULT"===e||"ALL"===e||"AT"===e||"NONE"===e)return e}buildChatRoomSessionDisplayFields(e,t,r){return t?{conversationName:t,conversationAvatar:r}:{conversationName:e}}isSessionListEqual(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){const s=e[r],n=t[r];if(!s||!n)return!1;if(this.buildSessionListSignature(s)!==this.buildSessionListSignature(n))return!1}return!0}buildSessionListSignature(e){const t=e.lastMessage,r=t?`${t.msgServerId}:${t.from}:${t.to}:${t.conversationId}:${t.conversationType}:${t.type}:${t.sendStatus??""}:${t.direct??""}:${t.sender.userId}:${t.sender.nickname??""}:${t.sender.avatarUrl??""}:${t.timestamp}:${JSON.stringify(t.body)}`:"none",s=`${e.conversationName}:${e.conversationAvatar??""}`;return[e.conversationType,e.conversationId,e.unreadCount,e.isPinned?"1":"0",e.pinnedTimestamp??0,e.marks.join(","),e.readAt??0,e.remindType,e.lastMessageAt??0,s,r].join(":")}refreshContactCacheIntegrity(e=!0){const t=this.contactCache.computeIntegrity(this.userInfoCache.getAll());this.contactCache.setMeta(t),e&&this.scheduleFlush(["contactMeta"])}buildContactSnapshotSignature(e){const t=e.items.map(e=>`${e.userId}:${e.userInfo.nickname??""}:${e.userInfo.avatarUrl??""}:${e.userInfo.sign??""}:${e.userInfo.ext??""}:${e.remark}:${e.addTs}`).join("|");return`${e.version}:${e.complete?"1":"0"}:${t}`}applyContactLocalPatch(e){const t=this.loadContactSnapshot("cache"),r=e();return r&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactMeta"])),{snapshot:this.loadContactSnapshot("cache"),changed:r&&this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(this.loadContactSnapshot("cache"))}}}class Pm{constructor(){this.handlers=new Map}addEventHandler(e,t){this.handlers.set(e,t)}removeEventHandler(e){this.handlers.delete(e)}dispatch(e,t){const r=[],s=[];for(const i of this.handlers.entries()){const[e]=i;e.startsWith("__internal")?r.push(i):s.push(i)}const n=this.dispatchToHandlers(e,t,r);n?n.then(()=>{this.dispatchToHandlers(e,t,s)}):this.dispatchToHandlers(e,t,s)}dispatchToHandlers(e,t,r){let s=null;for(const[,n]of r){const r=n[e];r&&(s=s?s.then(async()=>{await this.invokeHandler(e,t,r)}):this.invokeHandler(e,t,r))}return s}invokeHandler(e,t,r){try{const s=r(t);return this.isPromiseLike(s)?Promise.resolve(s).then(()=>{}).catch(t=>{this.reportHandlerError(e,t)}):null}catch(s){return this.reportHandlerError(e,s),null}}reportHandlerError(e,t){e!==V.LOG&&Ks(`Event handler error for ${e}`,t)}isPromiseLike(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}}const xm={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function Fm(e,t){const r=t.initialDelay*Math.pow(t.backoffMultiplier,e-1),s=Math.min(r,t.maxDelay);if(t.jitter){const e=.2*s,t=(2*Math.random()-1)*e;return Math.max(0,s+t)}return s}function Bm(e){return new Promise(t=>setTimeout(t,e))}const Gm=e=>{const t={...e};return delete t.type,t},qm=(e,t)=>{const r=e.lastMessage;if(!r)return null;const s=((e,t)=>{const r=t.getCurrentUserId?.()??"",s="singleChat"===e.type?e.conversationId:"";return{from:s,to:"singleChat"===e.type?r:e.conversationId,sender:{userId:s}}})(e,t);return{msgServerId:r.msgId,from:s.from,to:s.to,sender:s.sender,conversationId:e.conversationId,conversationType:e.type,type:"string"==typeof r.type&&r.type.length>0?r.type:"text",timestamp:r.timestamp,body:Gm(r.body),modifiedInfo:r.modifiedInfo,userInfoUpdateTime:r.userInfoUpdateTime,namecardUpdateTime:r.namecardUpdateTime}},$m=async(e,t)=>{const r=(e=>{const t=e.groupManager;return"function"==typeof t?.getGroupInfoList?t:null})(t);if(!r)return new Map;const s=[...new Set(e.filter(e=>"groupChat"===e.type).map(e=>e.conversationId))];if(0===s.length)return new Map;const n=[];for(let a=0;a<s.length;a+=50)n.push(s.slice(a,a+50));const i=new Map;let o=0;return await Promise.all(Array.from({length:Math.min(3,n.length)},async()=>await(async()=>{for(;o<n.length;){const e=o;o+=1;const t=n[e];if(t)try{const e=await r.getGroupInfoList({groupIds:t});for(const t of e)t.groupId&&i.set(t.groupId,t)}catch{}}})())),i},jm=async(e,t)=>{const r=await $m(e,t);return e.map(e=>((e,t,r)=>{const s=t.getContactSnapshot()?.items.find(t=>t.userId===e.conversationId),n=((e,t)=>{const r=e.getCacheManager();if(!r)return null;const s=r.getRuntimeUserInfo(t,!1);if(s)return s;const n=r.getUserInfoSummaries([t],!1)[0];return n?{userId:n.userId,nickname:n.nickname,avatarUrl:n.avatarUrl,sign:n.sign,ext:n.ext}:null})(t,e.conversationId),i="singleChat"===e.type?((e,t,r)=>{const s=t?.remark?.trim();if(s)return{conversationName:s,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl};const n=t?.userInfo.nickname?.trim()||r?.nickname?.trim();return n?{conversationName:n,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl}:{conversationName:e,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl}})(e.conversationId,s,n):"groupChat"===e.type?(o=e.conversationId,a=r.get(e.conversationId),a?.name?{conversationName:a.name,conversationAvatar:a.avatarUrl}:{conversationName:o}):(e=>({conversationName:e}))(e.conversationId);var o,a;return{conversationId:e.conversationId,conversationType:e.type,unreadCount:e.unreadCount,lastMessage:qm(e,t),lastMessageAt:e.lastMessage?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:void 0,remindType:"DEFAULT",conversationName:i.conversationName,conversationAvatar:i.conversationAvatar}})(e,t,r))};class Vm{constructor(e=`session-list-${Bh()}`){this.status="idle",this.seenBatchKeys=new Set,this.itemsByConversation=new Map,this.batchCount=0,this.requestId=e,this.startedAt=Date.now()}getRequestId(){return this.requestId}getStartedAt(){return this.startedAt}start(){"idle"===this.status&&(this.status="connecting")}markSyncing(){if("completed"===this.status||"failed"===this.status||"cancelled"===this.status)throw new ut("Session-list sync session cannot re-enter syncing state after completion",ot.CONTACT_SYNC_CURSOR_INVALID);this.status="syncing"}pushBatch(e){if(e.requestId!==this.requestId)throw new ut("Session-list sync requestId mismatch",ot.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.requestId,received:e.requestId}});if(this.isTerminal())throw new ut("Session-list sync batch received after terminal state",ot.CONTACT_SYNC_CURSOR_INVALID,{details:{requestId:e.requestId,status:this.status}});const t=(r=e.requestId,s=e.batchSequence,`${r}:${s}`);var r,s;if(this.seenBatchKeys.has(t))return{accepted:!1,done:e.isLastBatch};this.markSyncing(),this.seenBatchKeys.add(t);for(const n of e.sessions)this.itemsByConversation.set(`${n.conversationType}:${n.conversationId}`,n);return this.batchCount+=1,e.isLastBatch&&(this.status="completed",this.finishedAt=Date.now()),{accepted:!0,done:e.isLastBatch}}fail(){this.status="failed",this.finishedAt=Date.now()}cancel(){this.status="cancelled",this.finishedAt=Date.now()}getItems(){return[...this.itemsByConversation.values()]}getBatchCount(){return this.batchCount}getStatus(){return this.status}buildSnapshot(){return{requestId:this.requestId,status:this.status,pageCount:this.batchCount,startedAt:this.startedAt,finishedAt:this.finishedAt,seenBatchKeys:[...this.seenBatchKeys]}}isTerminal(){return"completed"===this.status||"failed"===this.status||"cancelled"===this.status}}const Km=0,zm=5,Hm=10,Wm=11,Jm=1,Qm=2,Zm=1,Ym=2,Xm=3,ef=e=>e===Jm?"groupChat":e===Qm?"chatRoom":"singleChat",tf=()=>Kd().lookupType("easemob.pb.MessageBody"),rf=e=>{const t=tf().toObject(tf().decode(e),{longs:Number,bytes:Uint8Array}),r=Array.isArray(t.contents)?t.contents:[],s=(n=r[0])&&"object"==typeof n&&!Array.isArray(n)?n:{};var n;const i="number"==typeof s.type?s.type:Dt,o="string"==typeof s.remotePath&&s.remotePath.length>0||"string"==typeof s.title&&s.title.length>0||"string"==typeof s.summary&&s.summary.length>0||"number"==typeof s.combineLevel&&s.combineLevel>0,a=Object.prototype.hasOwnProperty.call(s,"subType")&&0===s.subType;return i===jt||i===Dt&&(a||o)?{type:"combine",title:"string"==typeof s.title?s.title:"",summary:"string"==typeof s.summary?s.summary:"",filename:"string"==typeof s.displayName?s.displayName:"combine",filetype:"application/octet-stream",url:"string"==typeof s.remotePath?s.remotePath:void 0,secret:"string"==typeof s.secretKey?s.secretKey:void 0,fileLength:"number"==typeof s.fileLength?s.fileLength:void 0,combineLevel:"number"==typeof s.combineLevel?s.combineLevel:0}:i===Dt?{type:"text",content:"string"==typeof s.text?s.text:""}:1===i?{type:"image",filename:"string"==typeof s.displayName?s.displayName:"image",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:2===i?{type:"video",filename:"string"==typeof s.displayName?s.displayName:"video",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:3===i?{type:"location",latitude:"number"==typeof s.latitude?s.latitude:0,longitude:"number"==typeof s.longitude?s.longitude:0,address:"string"==typeof s.address?s.address:void 0}:4===i?{type:"voice",filename:"string"==typeof s.displayName?s.displayName:"voice",remotePath:"string"==typeof s.remotePath?s.remotePath:"",duration:"number"==typeof s.duration?s.duration:0}:5===i?{type:"file",filename:"string"==typeof s.displayName?s.displayName:"file",remotePath:"string"==typeof s.remotePath?s.remotePath:""}:6===i?{type:"cmd",action:"string"==typeof s.action?s.action:""}:7===i?{type:"custom",event:"string"==typeof s.customEvent?s.customEvent:""}:{}},sf=e=>{const t=e.session_id??"",r=(e=>{if(!e)return null;try{const t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{return null}return null})(e.metadata),s="string"==typeof r?.nickname?r.nickname:void 0,n="string"==typeof r?.remark?r.remark:void 0,i="string"==typeof r?.avatarurl?r.avatarurl:"string"==typeof r?.avatarUrl?r.avatarUrl:void 0;return n?{conversationName:n,conversationAvatar:i}:s?{conversationName:s,conversationAvatar:i}:{conversationName:t,conversationAvatar:i}},nf=e=>{const t={...e};return delete t.type,t},of=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,af=(e,t,r)=>{if(!e)return null;const s=(e=>{if(!e)return"";const t=e.lastIndexOf("_");return t>=0?e.slice(t+1):e})(e.from?.name),n={userId:s};return"singleChat"===r.conversationType&&s===r.conversationId&&r.singleChatPeerDisplay&&(r.singleChatPeerDisplay.conversationName!==s&&(n.nickname=r.singleChatPeerDisplay.conversationName),r.singleChatPeerDisplay.conversationAvatar&&(n.avatarUrl=r.singleChatPeerDisplay.conversationAvatar)),{msgServerId:e.id??"",from:s,to:of({conversationId:r.conversationId,conversationType:r.conversationType,from:s,currentUserId:r.currentUserId}),sender:n,conversationId:r.conversationId,conversationType:r.conversationType,type:(i=t.type,"text"===i||"image"===i||"file"===i||"voice"===i||"video"===i||"location"===i||"custom"===i||"cmd"===i||"combine"===i?i:"text"),timestamp:e.timestamp??0,body:nf(t)};var i},cf=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r},df=(e,t)=>e.sessions.map(e=>{const r=(e=>{if(!e||0===e.byteLength)return{};try{return rf(e)}catch{return{}}})(e.last_message?.payload),s=e.session_id??"",n=ef(e.session_type),i=(e=>{const t=e.session_id??"",r=ef(e.session_type);return"groupChat"===r||"chatRoom"===r?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:sf(e)})(e);return{conversationId:s,conversationType:n,unreadCount:e.unread_count??0,lastMessage:af(e.last_message,r,{conversationId:s,conversationType:n,currentUserId:t,singleChatPeerDisplay:"singleChat"===n?i:void 0}),lastMessageAt:e.updated_at,isPinned:"number"==typeof e.pinned_time?e.pinned_time>0:void 0,pinnedTimestamp:e.pinned_time,marks:cf(e.marks),readAt:e.read_receipt,remindType:(o=e.remind_type,o===Zm?"ALL":o===Ym?"AT":o===Xm?"NONE":"DEFAULT"),conversationName:i.conversationName,conversationAvatar:i.conversationAvatar};var o}),uf={nested:{easemob:{nested:{sessionlist:{nested:{GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},request_id:{type:"string",id:3},protocol_version:{type:"int32",id:4}}},JID:{fields:{app_key:{type:"string",id:1},name:{type:"string",id:2},domain:{type:"string",id:3},client_resource:{type:"string",id:4}}},Meta:{fields:{id:{type:"uint64",id:1},from:{type:"JID",id:2},timestamp:{type:"uint64",id:4},payload:{type:"bytes",id:6}}},SessionItem:{fields:{session_id:{type:"string",id:1},session_type:{type:"int32",id:2},last_message:{type:"Meta",id:3},updated_at:{type:"int64",id:6},pinned_time:{type:"int64",id:7},unread_count:{type:"uint32",id:8},marks:{rule:"repeated",type:"string",id:9},read_receipt:{type:"int64",id:10},remind_type:{type:"int32",id:11},group_name:{type:"string",id:12},group_avatar:{type:"string",id:13},metadata:{type:"string",id:14}}},GetSessionListRequest:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},last_sync_time:{type:"int64",id:6},need_empty_session:{type:"bool",id:7},need_session_mark:{type:"bool",id:8}}},GetSessionListResponse:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},sessions:{rule:"repeated",type:"SessionItem",id:3},is_last_batch:{type:"bool",id:4},last_sync_finished_ts:{type:"int64",id:5}}},ErrorDetail:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},code:{type:"uint32",id:3},message:{type:"string",id:4}}}}}}}}};let lf=null,hf=!1;const pf=()=>lf||(hf||(fa.util.Long=Dn,fa.configure(),hf=!0),Va(),lf=fa.Root.fromJSON(uf),ja(lf),lf),mf=e=>pf().lookupType(e),ff=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}if("bigint"==typeof e)return Number(e);if(e&&"object"==typeof e&&"toString"in e&&"function"==typeof e.toString){const t=Number(e.toString());return Number.isFinite(t)?t:void 0}},gf=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:ff(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:ff(t.protocol_version)??ff(t.protocolVersion)??0}},yf=e=>{if(!e||"object"!=typeof e)return;const t=e;return{appKey:"string"==typeof t.app_key?t.app_key:"string"==typeof t.appKey?t.appKey:void 0,name:"string"==typeof t.name?t.name:void 0,domain:"string"==typeof t.domain?t.domain:void 0,clientResource:"string"==typeof t.client_resource?t.client_resource:"string"==typeof t.clientResource?t.clientResource:void 0}},vf=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==ff(t.id)?String(ff(t.id)):void 0,from:yf(t.from),timestamp:ff(t.timestamp),payload:t.payload instanceof Uint8Array?t.payload:Array.isArray(t.payload)?Uint8Array.from(t.payload.filter(e=>"number"==typeof e)):void 0}};class If{constructor(){this.requestType=mf("easemob.sessionlist.GetSessionListRequest"),this.responseType=mf("easemob.sessionlist.GetSessionListResponse"),this.errorType=mf("easemob.sessionlist.ErrorDetail")}encodeRequest(e){const t=this.requestType.create({type:e.type,header:e.header?{resource:e.header.resource,timestamp:e.header.timestamp,request_id:e.header.requestId,protocol_version:e.header.protocolVersion}:void 0,org:e.org,app:e.app,username:e.username,last_sync_time:e.lastSyncTime??0,need_empty_session:e.includeEmpty??!1,need_session_mark:e.includeMark??!0});return this.requestType.encode(t).finish()}decode(e){const t=this.tryDecodeError(e);if(t)return t;const r=this.tryDecodeResponse(e);if(r)return r;const s=this.tryDecodeRequest(e);return s||{type:Km}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=ff(t.type);return r!==Hm?null:{type:r,header:gf(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:ff(t.last_sync_time)??0,includeEmpty:!0===t.need_empty_session,includeMark:!0===t.need_session_mark}}catch{return null}}tryDecodeResponse(e){try{const t=this.responseType.toObject(this.responseType.decode(e),{longs:String,bytes:Uint8Array}),r=ff(t.type);return r!==Wm?null:{type:r,header:gf(t.header),sessions:Array.isArray(t.sessions)?t.sessions.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{session_id:"string"==typeof t.session_id?t.session_id:void 0,session_type:ff(t.session_type),last_message:vf(t.last_message),updated_at:ff(t.updated_at),pinned_time:ff(t.pinned_time),unread_count:ff(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:ff(t.read_receipt),remind_type:ff(t.remind_type),group_name:"string"==typeof t.group_name?t.group_name:void 0,group_avatar:"string"==typeof t.group_avatar?t.group_avatar:void 0,metadata:"string"==typeof t.metadata?t.metadata:void 0}})(e)):[],isLastBatch:!0===t.is_last_batch,lastSyncFinishedTs:ff(t.last_sync_finished_ts)}}catch{return null}}tryDecodeError(e){try{const t=this.errorType.toObject(this.errorType.decode(e),{longs:String,bytes:Uint8Array}),r=ff(t.type);return r!==zm?null:{type:r,header:gf(t.header),code:ff(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const bf=async e=>{const t=e.client.getCacheManager(),r=e.client.getRestContext(),s=e.client.getSessionListSyncWsUrls();if(!t||0===s.length)throw new ht("session-list sync websocket is unavailable",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{protocol:"session-list",stage:"socket_connect"}});const[n,i]=r.appKey.split("#");if(!n||!i)throw new mt("session-list appKey is invalid",{code:ot.VALIDATION_INVALID_FORMAT,details:{appKey:r.appKey}});const o=t.loadSessionListCheckpoint(),a=(e=>({type:10,header:{resource:e.resource,timestamp:Date.now(),requestId:e.requestId,protocolVersion:e.protocolVersion??1},org:e.org,app:e.app,username:e.username,lastSyncTime:e.lastSyncTime,includeEmpty:e.params?.includeEmpty??!1,includeMark:!0}))({requestId:e.session.getRequestId(),resource:r.clientResource,org:n,app:i,username:r.userId,lastSyncTime:(c=o.sessionsLastSyncTs,Math.max(0,c-2e4)),params:e.params});var c;const d=new If;let u=0,l=o.sessionsLastSyncTs;return await e.client.getSharedSyncWebSocketSession().request({dataType:"conversation",label:"session-list-sync",requestId:e.session.getRequestId(),encode:()=>d.encodeRequest(a),decode:e=>{const t=d.decode(e);return{type:t.type,requestId:"header"in t?t.header?.requestId:void 0,frame:t}},onFrame:t=>{if(5===t.type&&"code"in t&&"message"in t)throw 1002===(s=t).code?new pt(s.message,{code:ot.AUTH_TOKEN_EXPIRED,details:{protocol:"session-list",responseCode:s.code}}):1003===s.code?new ut(s.message,ot.SERVER_BUSY,{details:{protocol:"session-list",responseCode:s.code}}):1501===s.code||1001===s.code?new mt(s.message,{code:ot.VALIDATION_INVALID_FORMAT,details:{protocol:"session-list",responseCode:s.code}}):1503===s.code?new ut(s.message,ot.OPERATION_UNSUPPORTED,{details:{protocol:"session-list",responseCode:s.code}}):(s.code,new ut(s.message,ot.REST_BUSINESS_UNKNOWN,{details:{protocol:"session-list",responseCode:s.code}}));var s;if(11!==t.type)throw new ut("session-list response type is invalid",ot.MESSAGE_DECODE_FAILED,{details:{responseType:t.type}});const n=t,i=n.header?.requestId;if(i&&i!==e.session.getRequestId())return;u+=1,js("Decoded session-list sync raw response",{requestId:e.session.getRequestId(),batchSequence:u,response:n});const o=df(n,r.userId),a=e.session.pushBatch({requestId:e.session.getRequestId(),batchSequence:u,sessions:o,isLastBatch:!0===n.isLastBatch,lastSyncFinishedTs:n.lastSyncFinishedTs});if("number"==typeof n.lastSyncFinishedTs&&(l=n.lastSyncFinishedTs),!a.done)return;return{done:!0,result:{items:e.session.getItems(),lastSyncFinishedTs:l}}}})},_f=e=>new mt(`${e} must be a local paging cursor returned by SDK`,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:`${e} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),Tf=(e,t,r)=>{const s=e+t;return s<r?String(s):""},Cf=e=>({...e}),Sf=e=>{const t=(e=>e?{msgId:e.msgServerId,type:"string"==typeof e.body.type?e.body.type:"unknown",body:e.body,timestamp:e.timestamp,modifiedInfo:e.modifiedInfo,userInfoUpdateTime:e.userInfoUpdateTime,namecardUpdateTime:e.namecardUpdateTime}:null)(e.lastMessage),r=e.lastMessageAt??e.lastMessage?.timestamp??0;return{conversationId:e.conversationId,type:e.conversationType,lastMessage:t,unreadCount:e.unreadCount,isPinned:e.isPinned,pinnedTime:e.pinnedTimestamp,marks:e.marks,lastAccess:r,lastUpdate:r}},Ef=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,wf=e=>{if(!Number.isInteger(e.pageSize)||e.pageSize<=0)throw new mt("pageSize must be a positive integer",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const t=((e,t)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw _f(t);const r=Number.parseInt(e,10);if(!Number.isSafeInteger(r)||r<0)throw _f(t);return r})(e.cursor,"cursor"),r=[];for(const s of e.items){if("chatRoom"===s.conversationType)continue;const e=Ef(s.remindType);e&&r.push({conversationId:s.conversationId,conversationType:s.conversationType,remindType:e})}return{conversations:r.slice(t,t+e.pageSize),cursor:Tf(t,e.pageSize,r.length)}},Rf=()=>Date.now(),Af={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Nf=(e,t)=>({status:e,determinedAt:Rf(),reason:t}),Of=e=>e instanceof ut&&(e.code===ot.SERVER_BUSY||1103===e.code),Mf=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:Of(e)});class Uf{constructor(e){this.running=null,this.currentSession=null,this.activeFinish=null,this.cancelled=!1,this.capabilityState={status:"unknown"},this.client=e}getCapabilityState(){return this.capabilityState}cancel(){this.cancelForTeardown()?.()}cancelForTeardown(){this.cancelled=!0,this.currentSession?.cancel();const e=this.activeFinish;return this.activeFinish=null,e?()=>{e({dataType:"conversation",status:"failed",error:{dataType:"conversation",code:ot.SESSION_LIST_CANCELLED,stage:"cancelled",message:"session-list sync cancelled",retryable:!1}})}:null}refresh(e){return this.cancelled?Promise.resolve([]):(this.running||(this.currentSession=new Vm,this.currentSession.start(),this.running=this.runRefresh(this.currentSession,{includeEmpty:e.includeEmpty,includeMark:!0}),this.running.finally(()=>{this.running=null,this.currentSession=null})),this.running)}async runRefresh(e,t){const r=this.client.getCacheManager();if(!r)return[];let s=!1;const n=e=>{s||(s=!0,this.client.emitSyncDataFinished(e))};this.activeFinish=n;try{this.client.emitSyncDataStart("conversation");const s=await this.tryDirectFallback(r);if(this.cancelled)return[];if(s)return this.client.emitConversationListUpdate("conversation",!0),n({dataType:"conversation",status:"success"}),s;const o=r.loadSessionListCheckpoint().sessionsLastSyncTs>0?"incremental":"full";let a=0;const c=await async function(e,t,r={}){const s={...xm,...r};let n;for(let o=1;o<=s.maxAttempts;o++)try{return await e()}catch(i){if(n=i,!t(i))throw i;if(o>=s.maxAttempts)throw i;const e=Fm(o,s);await Bm(e)}throw n}(async()=>{if(this.cancelled)throw new ut("session-list sync controller is cancelled");a+=1;const r=1===a?e:this.createRetrySession();r.start();try{return await bf({client:this.client,session:r,params:t})}catch(s){throw this.cancelled||r.fail(),s}},e=>!this.cancelled&&Of(e),Af);if(this.cancelled)return[];const d={result:c,syncStartedAt:e.getStartedAt()},u=d.result.items;this.capabilityState={status:"available",determinedAt:Rf()};const l={lastSyncTime:d.result.lastSyncFinishedTs,lastSyncFinishedTs:d.result.lastSyncFinishedTs,sessionsLastSyncTs:d.result.lastSyncFinishedTs,lastSuccessfulAt:Rf()};try{if(await r.commitSessionListSync({items:u,mode:o,checkpoint:l,syncStartedAt:d.syncStartedAt}),this.cancelled)return[]}catch(i){if(this.cancelled)return[];e.fail();const t=new yt("Session-list final persistence failed",{details:{cause:i instanceof Error?i.message:String(i)}});return this.client.emitConversationListUpdate("conversation",!0),n({dataType:"conversation",status:"failed",error:Mf(t)}),r.loadSessionList()}const h=r.loadSessionList();return r.updateConversationsFromServer(h.map(Sf),{syncStartedAt:d.syncStartedAt}),await r.flushPending(),this.cancelled?[]:(this.client.emitConversationListUpdate("conversation","full"===o),n({dataType:"conversation",status:"success"}),h)}catch(i){if(this.cancelled)return[];const t=i instanceof ut?i:new ut(i instanceof Error?i.message:String(i));e.fail();const s=(e=>e.code===ot.OPERATION_UNSUPPORTED||e.code===ot.AUTH_UNAUTHORIZED?{capabilityState:Nf("unsupported",e.message),shouldUseFallback:!0}:e.code===ot.AUTH_TOKEN_EXPIRED||e.code===ot.AUTH_BIND_ANOTHER_DEVICE?{shouldUseFallback:!0}:e.code===ot.SERVER_BUSY||1103===e.code?{shouldUseFallback:!0,shouldRetry:!0}:e.code===ot.CONTACT_SYNC_CURSOR_INVALID?{shouldUseFallback:!0,shouldResetCheckpoint:!0}:{shouldUseFallback:!0})(t);s.capabilityState&&(this.capabilityState=s.capabilityState),s.shouldResetCheckpoint&&r.resetSessionListCheckpoint();const o=await this.buildFallbackSessionList(r);return this.cancelled?[]:(s.shouldUseFallback&&r.replaceSessionList(o),this.client.emitConversationListUpdate("conversation",!0),n({dataType:"conversation",status:"failed",error:Mf(t)}),o)}finally{this.activeFinish===n&&(this.activeFinish=null)}}async tryDirectFallback(e){if("unsupported"===(t=this.capabilityState).status||"unconfigured"===t.status){const t=await this.buildFallbackSessionList(e);return this.cancelled||e.replaceSessionList(t),t}var t;const r=this.client.hasSessionListSyncWsUrl(),s=this.client.isSessionListDnsProbeAvailable();if(!r&&!s){this.capabilityState=Nf("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return this.cancelled||e.replaceSessionList(t),t}return null}createRetrySession(){return new Vm}async buildFallbackSessionList(e){return await(async(e,t)=>await jm(e,t))(e.loadConversationSummaries(),this.client)}}const Lf=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),kf=async e=>{if("string"==typeof e||Lf(e)||ArrayBuffer.isView(e))return(e=>"string"==typeof e?(new TextEncoder).encode(e):Lf(e)?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength))(e);if((e=>"undefined"!=typeof Blob&&e instanceof Blob&&"function"==typeof e.arrayBuffer||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(e))return new Uint8Array(await e.arrayBuffer());throw new ut("sync websocket frame payload type is invalid",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",payloadType:typeof e}})},Df=e=>{const t=Math.max(e-1,0),r=1e3*Math.pow(2,t);return Math.min(r,5e3)},Pf=async e=>{await new Promise(t=>{setTimeout(t,e)})},xf=e=>e instanceof Error?e:new Error(String(e));class Ff{constructor(e){this.pending=new Map,this.socket=null,this.state="idle",this.connectPromise=null,this.activeUrl="",this.urlIndex=0,this.attempt=0,this.connectTimer=null,this.idleTimer=null,this.retryTimer=null,this.completeCloseTimer=null,this.cancelled=!1,this.getUrls=e.getUrls,this.socketAdapter=e.socketAdapter}async request(e){if(this.cancelled)throw new ut("sync websocket session is cancelled",ot.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",requestId:e.requestId}});if(this.pending.has(e.requestId))throw new ut("sync websocket requestId is duplicated",ot.VALIDATION_INVALID_FORMAT,{details:{stage:"request_send",requestId:e.requestId}});this.clearCompleteCloseTimer();const t=new Promise((t,r)=>{this.pending.set(e.requestId,{...e,resolve:t,reject:r})});t.catch(()=>{});try{await this.ensureConnected(),this.sendPendingRequest(this.pending.get(e.requestId))}catch(r){this.rejectPending(e.requestId,xf(r))}return await t}cancel(e="sync-websocket-cancelled"){this.cancelled=!0;const t=new ut("sync websocket cancelled",ot.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",reason:e}});this.rejectAll(t),this.closeSocket(4001,e),this.clearTimers(),this.connectPromise=null,this.state="idle"}close(e="sync-websocket-closed"){this.closeSocket(1e3,e),this.clearTimers(),this.connectPromise=null,this.state="idle"}async ensureConnected(){if("open"!==this.state||this.socket?.readyState!==ln){if(this.connectPromise)return await this.connectPromise;this.connectPromise=this.connectWithRetry();try{await this.connectPromise}finally{this.connectPromise=null}}}async connectWithRetry(){let e=null;for(;!this.cancelled&&this.pending.size>0&&this.attempt<3;){this.attempt+=1,this.attempt>1&&Vs("sync websocket retry started",this.buildLogContext({reason:e?.message}));try{return void(await this.openSocket())}catch(t){if(e=xf(t),this.cancelled||0===this.pending.size)throw e;if(this.attempt>=3)throw Vs("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),e;const r=Df(this.attempt);Vs("sync websocket retry scheduled",this.buildLogContext({delayMs:r,reason:e.message})),await Pf(r)}}throw new ht("sync websocket retry exhausted",{code:ot.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect",reason:e?.message??"unknown"}})}async openSocket(){const e=await this.getUrls();if(0===e.length)throw new ht("sync websocket urls are unavailable",{code:ot.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});const t=e[this.urlIndex%e.length];if(this.urlIndex+=1,!t)throw new ht("sync websocket url is invalid",{code:ot.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});this.activeUrl=t,this.state="connecting",Vs("sync websocket connect started",this.buildLogContext());const r=xd(this.socketAdapter);let s=null;try{const e=await Promise.race([r.connect({url:t}),new Promise((e,t)=>{s=setTimeout(()=>{t(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},5e3)})]);s&&clearTimeout(s),this.socket=e,e.onMessage(t=>{this.socket===e&&this.handleMessage(t)}),e.onError(()=>{this.socket===e&&this.handleSocketFailure(this.buildConnectionError("sync websocket runtime error","sync_page"))}),e.onClose(t=>{if(this.socket===e)return"closing"===this.state||0===this.pending.size?(this.clearTimers(),this.socket=null,void(this.state="idle")):void this.handleSocketFailure(this.buildConnectionError("sync websocket socket closed","sync_page",{closeCode:t.code,closeReason:t.reason}))}),this.state="open",this.resetIdleTimer(),Vs("sync websocket connected",this.buildLogContext())}catch(n){if(s&&clearTimeout(s),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),n instanceof ht)throw n;throw this.buildConnectionError("sync websocket socket create failed","socket_connect",{cause:n instanceof Error?n.message:String(n)})}}async handleMessage(e){try{this.resetIdleTimer();const t=await kf(e);if(!(await this.routeFrame(t)))return}catch(t){const e=xf(t);this.rejectAll(e),this.closeSocket(4e3,"sync-websocket-frame-failed"),this.clearTimers(),this.state="idle"}}async routeFrame(e){const t=[];let r=null;for(const n of this.pending.values())try{const t=n.decode(e);if(t.requestId&&t.requestId===n.requestId){try{const e=await n.onFrame(t.frame,this.socket);e?.done&&(this.pending.delete(n.requestId),n.resolve(e.result),this.closeIfComplete())}catch(s){this.pending.delete(n.requestId),n.reject(xf(s)),this.closeIfComplete()}return!0}t.requestId||1!==t.type||r||(r={pending:n,frame:t.frame})}catch(s){t.push(xf(s))}if(r)return await r.pending.onFrame(r.frame,this.socket),!0;if(this.pending.size>0&&t.length===this.pending.size)throw new ut("sync websocket frame decode failed",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:t[0]?.message}});return Vs("sync websocket frame ignored",this.buildLogContext({reason:t[0]?.message??"requestId not matched"})),!1}handleSocketFailure(e){if(this.closeSocket(4e3,"sync-websocket-failed"),this.clearTimers(),this.state="idle",!this.cancelled&&0!==this.pending.size)return this.attempt>=3?(Vs("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),void this.rejectAll(e)):void(this.connectPromise=this.connectWithRetry().then(()=>{this.resendPendingRequests()}).catch(e=>{this.rejectAll(xf(e))}).finally(()=>{this.connectPromise=null}))}resendPendingRequests(){for(const e of this.pending.values())this.sendPendingRequest(e)}sendPendingRequest(e){if(e&&this.socket&&this.socket.readyState===ln)try{this.socket.send(e.encode()).catch(t=>{this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}),Vs("sync websocket request sent",this.buildLogContext({requestId:e.requestId,dataTypes:[e.dataType]})),this.resetIdleTimer()}catch(t){this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}}rejectPending(e,t){const r=this.pending.get(e);r&&(this.pending.delete(e),r.reject(t),this.closeIfComplete())}rejectAll(e){const t=[...this.pending.values()];this.pending.clear(),t.forEach(t=>{t.reject(e)})}closeIfComplete(){this.pending.size>0||(this.clearCompleteCloseTimer(),this.completeCloseTimer=setTimeout(()=>{this.completeCloseTimer=null,this.pending.size>0||(Vs("sync websocket closed after complete",this.buildLogContext()),this.close("sync-websocket-complete"))},0))}resetIdleTimer(){this.clearIdleTimer(),0!==this.pending.size&&(this.idleTimer=setTimeout(()=>{this.handleSocketFailure(this.buildConnectionError("sync websocket socket idle timeout","sync_page"))},1e4))}clearTimers(){this.clearConnectTimer(),this.clearIdleTimer(),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.clearCompleteCloseTimer()}clearConnectTimer(){this.connectTimer&&(clearTimeout(this.connectTimer),this.connectTimer=null)}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}clearCompleteCloseTimer(){this.completeCloseTimer&&(clearTimeout(this.completeCloseTimer),this.completeCloseTimer=null)}closeSocket(e,t){const r=this.socket;this.socket=null,!r||r.readyState>=hn||(this.state="closing",r.close(e,t))}buildConnectionError(e,t,r={}){return new ht(e,{code:ot.CONTACT_SYNC_SOCKET_FAILED,details:{stage:t,url:this.activeUrl,...r}})}buildLogContext(e={}){return{attempt:this.attempt,maxAttempts:3,url:ct(this.activeUrl),pendingCount:this.pending.size,dataTypes:[...new Set([...this.pending.values()].map(e=>e.dataType))],...e}}}const Bf=(e,t)=>{if(!e.matchField)return!1;const r=t[e.matchField];return void 0!==e.matchPattern?"string"==typeof r&&r.includes(e.matchPattern):void 0===e.matchValue?void 0!==r:r===e.matchValue||!("string"!=typeof r&&"number"!=typeof r||"string"!=typeof e.matchValue&&"number"!=typeof e.matchValue)&&String(r)===String(e.matchValue)};function Gf(e,t,r){if(!e)return;const s=r&&"object"==typeof r?r:{},n="string"==typeof s.error?s.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)(s),o="string"==typeof s.error_description?s.error_description:"string"==typeof s.message?s.message:"string"==typeof s.desc?s.desc:void 0,a=(e,t=!1)=>{const r=(e,r,s)=>({reasonKey:e,entry:r,matchedBy:t?"common":s});if(n&&e[n])return r(n,e[n],"key");for(const[n,i]of Object.entries(e))if(Bf(i,s))return r(n,i,"field");if(void 0!==i)for(const[s,n]of Object.entries(e)){if(n.code===i||n.canonicalCode===i)return r(s,n,"code");if(Array.isArray(n.aliases)&&n.aliases.includes(String(i)))return r(s,n,"alias")}if(o)for(const[s,n]of Object.entries(e))if(Array.isArray(n.aliases)&&n.aliases.includes(o))return r(s,n,"alias")},c=t?e.apis[t]:void 0,d=c?a(c.errors):void 0;if(d)return d;for(const u of Object.values(e.common)){const e=a(u.errors,!0);if(e)return e}}function qf(e){const t=e.entry?.code??ot.REST_BUSINESS_UNKNOWN,r=e.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:e.apiName,entry:e.entry,mapped:e.mapped,reasonKey:e.reasonKey});return new It(r,{code:t,details:{api:e.apiName,serverCode:e.serverCode,serverMessage:e.serverMessage,httpStatus:e.httpStatus,mapped:e.mapped??Boolean(e.entry),reasonKey:e.reasonKey,matchedBy:e.matchedBy,retryable:e.entry?.retryable,canonicalCode:e.entry?.canonicalCode??e.entry?.code}})}const $f={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"}},jf=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase();class Vf{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=gp(t?.requestAdapter),this.includeRequestId=t?.includeRequestId??!1,this.defaultHeaders={Accept:"application/json",...t?.headers}}sanitizeUrl(e){try{const t=new URL(e),r=t.searchParams;for(const e of r.keys())r.set(e,"***");const s=r.toString(),n=s?`?${s}`:"";return`${t.origin}${t.pathname}${n}`}catch{return e.split("?")[0]??e}}setAuthToken(e){this.defaultHeaders.Authorization=`Bearer ${e}`}removeAuthToken(){delete this.defaultHeaders.Authorization}buildHttpStatusFallbackError(e,t,r,s){const n={...t.operation?{api:t.operation}:{},url:t.url,method:t.method,httpStatus:e,serverCode:r,serverMessage:s,mapped:!1};if(400===e)return new mt("Invalid request parameters",{code:ot.VALIDATION_UNKNOWN,details:{...n,canonicalCode:ot.VALIDATION_UNKNOWN}});if(401===e){const e=[r,s].some(e=>"string"==typeof e&&/token[ _-]?(?:has[ _-]?)?expired/i.test(e)),t=e?ot.AUTH_TOKEN_EXPIRED:ot.AUTH_UNAUTHORIZED;return new pt(e?"Authentication token expired":"Authentication failed",{code:t,details:{...n,reasonKey:e?"token_expired":"unauthorized",canonicalCode:t}})}return 403===e?new pt("Access forbidden",{code:ot.AUTH_FORBIDDEN,details:{...n,canonicalCode:ot.AUTH_FORBIDDEN}}):429===e?new It("REST rate limit exceeded",{code:ot.SERVICE_LIMIT_EXCEEDED,details:{...n,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:ot.SERVICE_LIMIT_EXCEEDED}}):e>=500?new It("REST business error: request failed",{code:ot.REST_BUSINESS_UNKNOWN,details:{...n,retryable:!0,reasonKey:"server_unknown_error",canonicalCode:ot.REST_BUSINESS_UNKNOWN}}):void 0}async request(e,t={}){const r=`${this.baseUrl}${e}`,s=t.method??"GET",n=Date.now(),i=this.sanitizeUrl(r);js("REST request",{method:s,url:i,operation:t.operation});const o=t.operation?(e=>{const t=$f[e];if(t)return t;const r=(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_${jf(e)}`,operationType:r}})(t.operation):void 0,a=o?Uh(o):void 0,c=a?.startRequest({requestName:o?.operationName,method:s,url:r});let d=0;const u={...this.defaultHeaders,...t.headers};if(this.includeRequestId&&(u[ru]=tu()),t.body&&"GET"!==s){const e=Object.keys(u).some(e=>"content-type"===e.toLowerCase());"string"==typeof t.body?e||(u["Content-Type"]="application/x-www-form-urlencoded"):e||(u["Content-Type"]="application/json")}else if("GET"===s)for(const h of Object.keys(u))"content-type"===h.toLowerCase()&&delete u[h];try{const e=await this.requestAdapter.request({url:r,method:s,headers:u,body:t.body,timeoutMs:t.timeout??this.timeout});d=e.status;const o=((e,t)=>{if("string"!=typeof e)return e;const r=Object.entries(t).find(([e])=>"content-type"===e.toLowerCase()),s=e.trim();if(!(r?.[1].includes("application/json")||s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]")))return e;try{return JSON.parse(s)}catch{return e}})(e.data,e.headers),l=Date.now()-n;(e.status<200||e.status>=300)&&(Vs("REST response error",{method:s,url:i,status:e.status,duration:l}),this.handleErrorPayload(e.status,e.statusText??"",o,{operation:t.operation,url:r,method:s})),js("REST response",{method:s,url:i,status:e.status,duration:l});const h=(e=>{if(Array.isArray(e))return e.length;if(!e||"object"!=typeof e)return;const t=e;for(const r of["entities","data","items","messages","conversations","results"]){const e=t[r];if(Array.isArray(e))return e.length}})(o);return c?.finish({code:e.status,success:!0,resultCount:h}),a?.finish({code:0,success:!0,resultCount:h}),o}catch(l){const e=0!==d?d:l instanceof ut?l.code:-1,n=l instanceof Error?l.message:String(l);if(c?.finish({code:e,success:!1,description:n}),a?.finish({code:e,success:!1,description:n}),l instanceof ut)throw l;const o=(e=>{if(!e||"object"!=typeof e)return;const t=e.details;if(!t||"object"!=typeof t)return;const r=t.reason;return"abort"===r||"network"===r||"timeout"===r?r:void 0})(l);if(l instanceof Error&&"AbortError"===l.name||"timeout"===o)throw Vs("REST request timeout",{method:s,url:i,timeout:t.timeout??this.timeout}),new vt(`Request timeout: ${r}`,{code:ot.REST_TIMEOUT,details:{url:r,method:s,timeout:t.timeout??this.timeout}});throw Vs("REST request failed",{method:s,url:i}),new vt(`Request failed: ${r}`,{code:ot.REST_NETWORK_ERROR,details:{url:r,method:s,...o?{reason:o}:{}}})}}handleErrorPayload(e,t,r,s){const n=r&&"object"==typeof r?r:{},i=((e,t)=>{if(!e.error||"object"!=typeof e.error||Array.isArray(e.error))return;const r=e.error,s=r.code;if("number"!=typeof s&&"string"!=typeof s)return;const n=String(s);return/^\d{7}$/.test(n)&&Number(n.slice(0,3))===t?r:void 0})(n,e),o=i?{...n,code:i.code,message:i.message}:r,a=Gf(this.errorMap,s.operation,o),c="string"==typeof n.error?n.error:void 0,d="number"==typeof n.error_code||"string"==typeof n.error_code?n.error_code:"number"==typeof n.errorCode||"string"==typeof n.errorCode?n.errorCode:"number"==typeof n.code||"string"==typeof n.code?n.code:"string"==typeof n.error?n.error:"number"==typeof i?.code||"string"==typeof i?.code?i.code:void 0,u="string"==typeof n.message?n.message:"string"==typeof n.error_description?n.error_description:"string"==typeof n.desc?n.desc:"string"==typeof i?.message?i.message:void 0,l=!!(401!==e&&403!==e||void 0!==c&&"unauthorized"!==c&&"auth_failed"!==c&&"forbidden"!==c)&&(void 0!==c||"string"==typeof n.error_description||"string"==typeof n.message||"string"==typeof n.desc);if(s.operation&&a)throw qf({apiName:s.operation,entry:a.entry,serverCode:d,serverMessage:u,httpStatus:e,mapped:!0,reasonKey:a.reasonKey,matchedBy:a.matchedBy});const h=this.buildHttpStatusFallbackError(e,s,d,u);if(h)throw h;if(s.operation&&l)throw qf({apiName:s.operation,serverCode:d,serverMessage:u,httpStatus:e,mapped:!1,reasonKey:c});throw new vt(`HTTP ${e}: ${t}`,{code:ot.REST_HTTP_ERROR,details:{url:s.url,method:s.method,httpStatus:e}})}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,r){return this.request(e,{...r,method:"POST",body:t})}put(e,t,r){return this.request(e,{...r,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t})}}const Kf=async(e,t,r)=>{const{orgName:s,appName:n}=fs(e.appKey),i=`/${s}/${n}/user/${encodeURIComponent(e.userId)}/roster/metadata/version`,o=new Vf(e.restBaseUrl,{requestAdapter:r,includeRequestId:!0});o.setAuthToken(e.token);try{return((e,t)=>{const r=Date.now(),s=e=>{const s="string"==typeof e.version?e.version:"string"==typeof e.rosterVersion?e.rosterVersion:"";return{version:s,requiresSync:("boolean"==typeof e.requiresSync?e.requiresSync:"boolean"==typeof e.needSync?e.needSync:"boolean"==typeof e.need_sync?e.need_sync:void 0)??s!==t,checkedAt:"number"==typeof e.checkedAt?e.checkedAt:"number"==typeof e.timestamp?e.timestamp:r}};if(pu(e))return pu(e.data)?s(e.data):s(e);throw new mt("Invalid contact metadata response",{code:ot.VALIDATION_INVALID_FORMAT,details:{payload:e}})})(await o.get(i),t)}catch(a){if(a instanceof mt)throw a;const e=a instanceof ut&&a.details?a.details:{};throw new vt("Contact metadata request failed",{code:ot.CONTACT_SYNC_METADATA_FAILED,details:{stage:"metadata",cause:a instanceof Error?a.message:String(a),httpStatus:"number"==typeof e.httpStatus?e.httpStatus:void 0,sourceCode:a instanceof ut?a.code:void 0}})}};var zf,Hf,Wf;(Hf=zf||(zf={})).assertEqual=e=>{},Hf.assertIs=function(e){},Hf.assertNever=function(e){throw new Error},Hf.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},Hf.getValidEnumValues=e=>{const t=Hf.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(const s of t)r[s]=e[s];return Hf.objectValues(r)},Hf.objectValues=e=>Hf.objectKeys(e).map(function(t){return e[t]}),Hf.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},Hf.find=(e,t)=>{for(const r of e)if(t(r))return r},Hf.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,Hf.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},Hf.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(Wf||(Wf={})).mergeShapes=(e,t)=>({...e,...t});const Jf=zf.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Qf=e=>{switch(typeof e){case"undefined":return Jf.undefined;case"string":return Jf.string;case"number":return Number.isNaN(e)?Jf.nan:Jf.number;case"boolean":return Jf.boolean;case"function":return Jf.function;case"bigint":return Jf.bigint;case"symbol":return Jf.symbol;case"object":return Array.isArray(e)?Jf.array:null===e?Jf.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?Jf.promise:"undefined"!=typeof Map&&e instanceof Map?Jf.map:"undefined"!=typeof Set&&e instanceof Set?Jf.set:"undefined"!=typeof Date&&e instanceof Date?Jf.date:Jf.object;default:return Jf.unknown}},Zf=zf.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Yf extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},s=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)r._errors.push(t(n));else{let e=r,s=0;for(;s<n.path.length;){const r=n.path[s];s===n.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(n))):e[r]=e[r]||{_errors:[]},e=e[r],s++}}};return s(this),r}static assert(e){if(!(e instanceof Yf))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,zf.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const s of this.issues)if(s.path.length>0){const r=s.path[0];t[r]=t[r]||[],t[r].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Yf.create=e=>new Yf(e);const Xf=(e,t)=>{let r;switch(e.code){case Zf.invalid_type:r=e.received===Jf.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Zf.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,zf.jsonStringifyReplacer)}`;break;case Zf.unrecognized_keys:r=`Unrecognized key(s) in object: ${zf.joinValues(e.keys,", ")}`;break;case Zf.invalid_union:r="Invalid input";break;case Zf.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${zf.joinValues(e.options)}`;break;case Zf.invalid_enum_value:r=`Invalid enum value. Expected ${zf.joinValues(e.options)}, received '${e.received}'`;break;case Zf.invalid_arguments:r="Invalid function arguments";break;case Zf.invalid_return_type:r="Invalid function return type";break;case Zf.invalid_date:r="Invalid date";break;case Zf.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:zf.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Zf.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case Zf.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case Zf.custom:r="Invalid input";break;case Zf.invalid_intersection_types:r="Intersection results could not be merged";break;case Zf.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Zf.not_finite:r="Number must be finite";break;default:r=t.defaultError,zf.assertNever(e)}return{message:r}};let eg=Xf;function tg(e,t){const r=eg,s=(e=>{const{data:t,path:r,errorMaps:s,issueData:n}=e,i=[...r,...n.path||[]],o={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let a="";const c=s.filter(e=>!!e).slice().reverse();for(const d of c)a=d(o,{data:t,defaultError:a}).message;return{...n,path:i,message:a}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Xf?void 0:Xf].filter(e=>!!e)});e.common.issues.push(s)}class rg{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if("aborted"===s.status)return sg;"dirty"===s.status&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const s of t){const e=await s.key,t=await s.value;r.push({key:e,value:t})}return rg.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:t,value:n}=s;if("aborted"===t.status)return sg;if("aborted"===n.status)return sg;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!s.alwaysSet||(r[t.value]=n.value)}return{status:e.value,value:r}}}const sg=Object.freeze({status:"aborted"}),ng=e=>({status:"dirty",value:e}),ig=e=>({status:"valid",value:e}),og=e=>"aborted"===e.status,ag=e=>"dirty"===e.status,cg=e=>"valid"===e.status,dg=e=>"undefined"!=typeof Promise&&e instanceof Promise;var ug,lg;(lg=ug||(ug={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},lg.toString=e=>"string"==typeof e?e:e?.message;class hg{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const pg=(e,t)=>{if(cg(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Yf(e.common.issues);return this._error=t,this._error}}};function mg(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:n}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??s??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??r??n.defaultError}},description:n}}class fg{get description(){return this._def.description}_getType(e){return Qf(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Qf(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new rg,ctx:{common:e.parent.common,data:e.data,parsedType:Qf(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(dg(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Qf(e)},s=this._parseSync({data:e,path:r.path,parent:r});return pg(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Qf(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return cg(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>cg(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Qf(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await(dg(s)?s:Promise.resolve(s));return pg(r,n)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const n=e(t),i=()=>s.addIssue({code:Zf.custom,...r(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(i(),!1)):!!n||(i(),!1)})}refinement(e,t){return this._refinement((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1))}_refinement(e){return new fy({schema:this,typeName:wy.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return gy.create(this,this._def)}nullable(){return yy.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yg.create(this)}promise(){return py.create(this,this._def)}or(e){return ty.create([this,e],this._def)}and(e){return sy.create(this,e,this._def)}transform(e){return new fy({...mg(this._def),schema:this,typeName:wy.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new vy({...mg(this._def),innerType:this,defaultValue:t,typeName:wy.ZodDefault})}brand(){return new _y({typeName:wy.ZodBranded,type:this,...mg(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Iy({...mg(this._def),innerType:this,catchValue:t,typeName:wy.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ty.create(this,e)}readonly(){return Cy.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const gg=/^c[^\s-]{8,}$/i,yg=/^[0-9a-z]+$/,vg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ig=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,bg=/^[a-z0-9_-]{21}$/i,_g=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Tg=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Cg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Sg;const Eg=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,wg=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Rg=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ag=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ng=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Og=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Mg="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ug=new RegExp(`^${Mg}$`);function Lg(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function kg(e){return new RegExp(`^${Lg(e)}$`)}function Dg(e){let t=`${Mg}T${Lg(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Pg(e,t){return!("v4"!==t&&t||!Eg.test(e))||!("v6"!==t&&t||!Rg.test(e))}function xg(e,t){if(!_g.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(s));return"object"==typeof n&&null!==n&&((!("typ"in n)||"JWT"===n?.typ)&&(!!n.alg&&(!t||n.alg===t)))}catch{return!1}}function Fg(e,t){return!("v4"!==t&&t||!wg.test(e))||!("v6"!==t&&t||!Ag.test(e))}class Bg extends fg{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==Jf.string){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.string,received:t.parsedType}),sg}const t=new rg;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("max"===s.kind)e.data.length>s.value&&(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("length"===s.kind){const n=e.data.length>s.value,i=e.data.length<s.value;(n||i)&&(r=this._getOrReturnCtx(e,r),n?tg(r,{code:Zf.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&tg(r,{code:Zf.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)Cg.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"email",code:Zf.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)Sg||(Sg=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Sg.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"emoji",code:Zf.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)Ig.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"uuid",code:Zf.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)bg.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"nanoid",code:Zf.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)gg.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"cuid",code:Zf.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)yg.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"cuid2",code:Zf.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)vg.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"ulid",code:Zf.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),tg(r,{validation:"url",code:Zf.invalid_string,message:s.message}),t.dirty()}else if("regex"===s.kind){s.regex.lastIndex=0;s.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"regex",code:Zf.invalid_string,message:s.message}),t.dirty())}else if("trim"===s.kind)e.data=e.data.trim();else if("includes"===s.kind)e.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),t.dirty());else if("toLowerCase"===s.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===s.kind)e.data=e.data.toUpperCase();else if("startsWith"===s.kind)e.data.startsWith(s.value)||(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.invalid_string,validation:{startsWith:s.value},message:s.message}),t.dirty());else if("endsWith"===s.kind)e.data.endsWith(s.value)||(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty());else if("datetime"===s.kind){Dg(s).test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.invalid_string,validation:"datetime",message:s.message}),t.dirty())}else if("date"===s.kind){Ug.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.invalid_string,validation:"date",message:s.message}),t.dirty())}else if("time"===s.kind){kg(s).test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.invalid_string,validation:"time",message:s.message}),t.dirty())}else"duration"===s.kind?Tg.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"duration",code:Zf.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?Pg(e.data,s.version)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"ip",code:Zf.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?xg(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"jwt",code:Zf.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?Fg(e.data,s.version)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"cidr",code:Zf.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?Ng.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"base64",code:Zf.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?Og.test(e.data)||(r=this._getOrReturnCtx(e,r),tg(r,{validation:"base64url",code:Zf.invalid_string,message:s.message}),t.dirty()):zf.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:Zf.invalid_string,...ug.errToObj(r)})}_addCheck(e){return new Bg({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ug.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ug.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ug.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ug.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ug.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ug.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ug.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ug.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ug.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ug.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ug.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ug.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ug.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...ug.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...ug.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ug.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ug.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...ug.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ug.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ug.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ug.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ug.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ug.errToObj(t)})}nonempty(e){return this.min(1,ug.errToObj(e))}trim(){return new Bg({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Bg({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Bg({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function Gg(e,t){const r=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=r>s?r:s;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}Bg.create=e=>new Bg({checks:[],typeName:wy.ZodString,coerce:e?.coerce??!1,...mg(e)});class qg extends fg{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==Jf.number){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.number,received:t.parsedType}),sg}let t;const r=new rg;for(const s of this._def.checks)if("int"===s.kind)zf.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),tg(t,{code:Zf.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty());else if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),tg(t,{code:Zf.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),tg(t,{code:Zf.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==Gg(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),tg(t,{code:Zf.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),tg(t,{code:Zf.not_finite,message:s.message}),r.dirty()):zf.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ug.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ug.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ug.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ug.toString(t))}setLimit(e,t,r,s){return new qg({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:ug.toString(s)}]})}_addCheck(e){return new qg({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ug.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ug.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ug.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ug.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ug.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ug.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ug.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ug.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ug.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&zf.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}qg.create=e=>new qg({checks:[],typeName:wy.ZodNumber,coerce:e?.coerce||!1,...mg(e)});class $g extends fg{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Jf.bigint)return this._getInvalidInput(e);let t;const r=new rg;for(const s of this._def.checks)if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),tg(t,{code:Zf.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),tg(t,{code:Zf.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),tg(t,{code:Zf.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):zf.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.bigint,received:t.parsedType}),sg}gte(e,t){return this.setLimit("min",e,!0,ug.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ug.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ug.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ug.toString(t))}setLimit(e,t,r,s){return new $g({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:ug.toString(s)}]})}_addCheck(e){return new $g({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ug.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ug.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ug.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ug.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ug.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}$g.create=e=>new $g({checks:[],typeName:wy.ZodBigInt,coerce:e?.coerce??!1,...mg(e)});class jg extends fg{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==Jf.boolean){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.boolean,received:t.parsedType}),sg}return ig(e.data)}}jg.create=e=>new jg({typeName:wy.ZodBoolean,coerce:e?.coerce||!1,...mg(e)});class Vg extends fg{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==Jf.date){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.date,received:t.parsedType}),sg}if(Number.isNaN(e.data.getTime())){return tg(this._getOrReturnCtx(e),{code:Zf.invalid_date}),sg}const t=new rg;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),tg(r,{code:Zf.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):zf.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Vg({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:ug.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ug.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Vg.create=e=>new Vg({checks:[],coerce:e?.coerce||!1,typeName:wy.ZodDate,...mg(e)});class Kg extends fg{_parse(e){if(this._getType(e)!==Jf.symbol){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.symbol,received:t.parsedType}),sg}return ig(e.data)}}Kg.create=e=>new Kg({typeName:wy.ZodSymbol,...mg(e)});class zg extends fg{_parse(e){if(this._getType(e)!==Jf.undefined){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.undefined,received:t.parsedType}),sg}return ig(e.data)}}zg.create=e=>new zg({typeName:wy.ZodUndefined,...mg(e)});class Hg extends fg{_parse(e){if(this._getType(e)!==Jf.null){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.null,received:t.parsedType}),sg}return ig(e.data)}}Hg.create=e=>new Hg({typeName:wy.ZodNull,...mg(e)});class Wg extends fg{constructor(){super(...arguments),this._any=!0}_parse(e){return ig(e.data)}}Wg.create=e=>new Wg({typeName:wy.ZodAny,...mg(e)});class Jg extends fg{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ig(e.data)}}Jg.create=e=>new Jg({typeName:wy.ZodUnknown,...mg(e)});class Qg extends fg{_parse(e){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.never,received:t.parsedType}),sg}}Qg.create=e=>new Qg({typeName:wy.ZodNever,...mg(e)});class Zg extends fg{_parse(e){if(this._getType(e)!==Jf.undefined){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.void,received:t.parsedType}),sg}return ig(e.data)}}Zg.create=e=>new Zg({typeName:wy.ZodVoid,...mg(e)});class Yg extends fg{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==Jf.array)return tg(t,{code:Zf.invalid_type,expected:Jf.array,received:t.parsedType}),sg;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(tg(t,{code:e?Zf.too_big:Zf.too_small,minimum:n?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(tg(t,{code:Zf.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(tg(t,{code:Zf.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>s.type._parseAsync(new hg(t,e,t.path,r)))).then(e=>rg.mergeArray(r,e));const n=[...t.data].map((e,r)=>s.type._parseSync(new hg(t,e,t.path,r)));return rg.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new Yg({...this._def,minLength:{value:e,message:ug.toString(t)}})}max(e,t){return new Yg({...this._def,maxLength:{value:e,message:ug.toString(t)}})}length(e,t){return new Yg({...this._def,exactLength:{value:e,message:ug.toString(t)}})}nonempty(e){return this.min(1,e)}}function Xg(e){if(e instanceof ey){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=gy.create(Xg(s))}return new ey({...e._def,shape:()=>t})}return e instanceof Yg?new Yg({...e._def,type:Xg(e.element)}):e instanceof gy?gy.create(Xg(e.unwrap())):e instanceof yy?yy.create(Xg(e.unwrap())):e instanceof ny?ny.create(e.items.map(e=>Xg(e))):e}Yg.create=(e,t)=>new Yg({type:e,minLength:null,maxLength:null,exactLength:null,typeName:wy.ZodArray,...mg(t)});class ey extends fg{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=zf.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Jf.object){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.object,received:t.parsedType}),sg}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof Qg&&"strip"===this._def.unknownKeys))for(const a in r.data)n.includes(a)||i.push(a);const o=[];for(const a of n){const e=s[a],t=r.data[a];o.push({key:{status:"valid",value:a},value:e._parse(new hg(r,t,r.path,a)),alwaysSet:a in r.data})}if(this._def.catchall instanceof Qg){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of i)o.push({key:{status:"valid",value:t},value:{status:"valid",value:r.data[t]}});else if("strict"===e)i.length>0&&(tg(r,{code:Zf.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const s=r.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new hg(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>rg.mergeObjectSync(t,e)):rg.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return ug.errToObj,new ey({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const s=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:ug.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ey({...this._def,unknownKeys:"strip"})}passthrough(){return new ey({...this._def,unknownKeys:"passthrough"})}extend(e){return new ey({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ey({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:wy.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ey({...this._def,catchall:e})}pick(e){const t={};for(const r of zf.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new ey({...this._def,shape:()=>t})}omit(e){const t={};for(const r of zf.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new ey({...this._def,shape:()=>t})}deepPartial(){return Xg(this)}partial(e){const t={};for(const r of zf.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new ey({...this._def,shape:()=>t})}required(e){const t={};for(const r of zf.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof gy;)e=e._def.innerType;t[r]=e}return new ey({...this._def,shape:()=>t})}keyof(){return uy(zf.objectKeys(this.shape))}}ey.create=(e,t)=>new ey({shape:()=>e,unknownKeys:"strip",catchall:Qg.create(),typeName:wy.ZodObject,...mg(t)}),ey.strictCreate=(e,t)=>new ey({shape:()=>e,unknownKeys:"strict",catchall:Qg.create(),typeName:wy.ZodObject,...mg(t)}),ey.lazycreate=(e,t)=>new ey({shape:e,unknownKeys:"strip",catchall:Qg.create(),typeName:wy.ZodObject,...mg(t)});class ty extends fg{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const s of e)if("dirty"===s.result.status)return t.common.issues.push(...s.ctx.common.issues),s.result;const r=e.map(e=>new Yf(e.ctx.common.issues));return tg(t,{code:Zf.invalid_union,unionErrors:r}),sg});{let e;const s=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},n=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map(e=>new Yf(e));return tg(t,{code:Zf.invalid_union,unionErrors:n}),sg}}get options(){return this._def.options}}function ry(e,t){const r=Qf(e),s=Qf(t);if(e===t)return{valid:!0,data:e};if(r===Jf.object&&s===Jf.object){const r=zf.objectKeys(t),s=zf.objectKeys(e).filter(e=>-1!==r.indexOf(e)),n={...e,...t};for(const i of s){const r=ry(e[i],t[i]);if(!r.valid)return{valid:!1};n[i]=r.data}return{valid:!0,data:n}}if(r===Jf.array&&s===Jf.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const n=ry(e[s],t[s]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===Jf.date&&s===Jf.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}ty.create=(e,t)=>new ty({options:e,typeName:wy.ZodUnion,...mg(t)});class sy extends fg{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(og(e)||og(s))return sg;const n=ry(e.value,s.value);return n.valid?((ag(e)||ag(s))&&t.dirty(),{status:t.value,value:n.data}):(tg(r,{code:Zf.invalid_intersection_types}),sg)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}sy.create=(e,t,r)=>new sy({left:e,right:t,typeName:wy.ZodIntersection,...mg(r)});class ny extends fg{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Jf.array)return tg(r,{code:Zf.invalid_type,expected:Jf.array,received:r.parsedType}),sg;if(r.data.length<this._def.items.length)return tg(r,{code:Zf.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),sg;!this._def.rest&&r.data.length>this._def.items.length&&(tg(r,{code:Zf.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new hg(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>rg.mergeArray(t,e)):rg.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new ny({...this._def,rest:e})}}ny.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ny({items:e,typeName:wy.ZodTuple,rest:null,...mg(t)})};class iy extends fg{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Jf.object)return tg(r,{code:Zf.invalid_type,expected:Jf.object,received:r.parsedType}),sg;const s=[],n=this._def.keyType,i=this._def.valueType;for(const o in r.data)s.push({key:n._parse(new hg(r,o,r.path,o)),value:i._parse(new hg(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?rg.mergeObjectAsync(t,s):rg.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new iy(t instanceof fg?{keyType:e,valueType:t,typeName:wy.ZodRecord,...mg(r)}:{keyType:Bg.create(),valueType:e,typeName:wy.ZodRecord,...mg(t)})}}class oy extends fg{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Jf.map)return tg(r,{code:Zf.invalid_type,expected:Jf.map,received:r.parsedType}),sg;const s=this._def.keyType,n=this._def.valueType,i=[...r.data.entries()].map(([e,t],i)=>({key:s._parse(new hg(r,e,r.path,[i,"key"])),value:n._parse(new hg(r,t,r.path,[i,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of i){const s=await r.key,n=await r.value;if("aborted"===s.status||"aborted"===n.status)return sg;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of i){const s=r.key,n=r.value;if("aborted"===s.status||"aborted"===n.status)return sg;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}oy.create=(e,t,r)=>new oy({valueType:t,keyType:e,typeName:wy.ZodMap,...mg(r)});class ay extends fg{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Jf.set)return tg(r,{code:Zf.invalid_type,expected:Jf.set,received:r.parsedType}),sg;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(tg(r,{code:Zf.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&(tg(r,{code:Zf.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const r=new Set;for(const s of e){if("aborted"===s.status)return sg;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}const o=[...r.data.values()].map((e,t)=>n._parse(new hg(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>i(e)):i(o)}min(e,t){return new ay({...this._def,minSize:{value:e,message:ug.toString(t)}})}max(e,t){return new ay({...this._def,maxSize:{value:e,message:ug.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ay.create=(e,t)=>new ay({valueType:e,minSize:null,maxSize:null,typeName:wy.ZodSet,...mg(t)});class cy extends fg{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}cy.create=(e,t)=>new cy({getter:e,typeName:wy.ZodLazy,...mg(t)});class dy extends fg{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return tg(t,{received:t.data,code:Zf.invalid_literal,expected:this._def.value}),sg}return{status:"valid",value:e.data}}get value(){return this._def.value}}function uy(e,t){return new ly({values:e,typeName:wy.ZodEnum,...mg(t)})}dy.create=(e,t)=>new dy({value:e,typeName:wy.ZodLiteral,...mg(t)});class ly extends fg{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return tg(t,{expected:zf.joinValues(r),received:t.parsedType,code:Zf.invalid_type}),sg}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return tg(t,{received:t.data,code:Zf.invalid_enum_value,options:r}),sg}return ig(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ly.create(e,{...this._def,...t})}exclude(e,t=this._def){return ly.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}ly.create=uy;class hy extends fg{_parse(e){const t=zf.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Jf.string&&r.parsedType!==Jf.number){const e=zf.objectValues(t);return tg(r,{expected:zf.joinValues(e),received:r.parsedType,code:Zf.invalid_type}),sg}if(this._cache||(this._cache=new Set(zf.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=zf.objectValues(t);return tg(r,{received:r.data,code:Zf.invalid_enum_value,options:e}),sg}return ig(e.data)}get enum(){return this._def.values}}hy.create=(e,t)=>new hy({values:e,typeName:wy.ZodNativeEnum,...mg(t)});class py extends fg{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Jf.promise&&!1===t.common.async)return tg(t,{code:Zf.invalid_type,expected:Jf.promise,received:t.parsedType}),sg;const r=t.parsedType===Jf.promise?t.data:Promise.resolve(t.data);return ig(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}py.create=(e,t)=>new py({type:e,typeName:wy.ZodPromise,...mg(t)});class fy extends fg{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===wy.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,n={addIssue:e=>{tg(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===s.type){const e=s.transform(r.data,n);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return sg;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?sg:"dirty"===s.status||"dirty"===t.value?ng(s.value):s});{if("aborted"===t.value)return sg;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?sg:"dirty"===s.status||"dirty"===t.value?ng(s.value):s}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,n);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===s.status?sg:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?sg:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===s.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!cg(e))return sg;const i=s.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>cg(e)?Promise.resolve(s.transform(e.value,n)).then(e=>({status:t.value,value:e})):sg)}zf.assertNever(s)}}fy.create=(e,t,r)=>new fy({schema:e,typeName:wy.ZodEffects,effect:t,...mg(r)}),fy.createWithPreprocess=(e,t,r)=>new fy({schema:t,effect:{type:"preprocess",transform:e},typeName:wy.ZodEffects,...mg(r)});class gy extends fg{_parse(e){return this._getType(e)===Jf.undefined?ig(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}gy.create=(e,t)=>new gy({innerType:e,typeName:wy.ZodOptional,...mg(t)});class yy extends fg{_parse(e){return this._getType(e)===Jf.null?ig(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}yy.create=(e,t)=>new yy({innerType:e,typeName:wy.ZodNullable,...mg(t)});class vy extends fg{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===Jf.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}vy.create=(e,t)=>new vy({innerType:e,typeName:wy.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...mg(t)});class Iy extends fg{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return dg(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Yf(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new Yf(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Iy.create=(e,t)=>new Iy({innerType:e,typeName:wy.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...mg(t)});class by extends fg{_parse(e){if(this._getType(e)!==Jf.nan){const t=this._getOrReturnCtx(e);return tg(t,{code:Zf.invalid_type,expected:Jf.nan,received:t.parsedType}),sg}return{status:"valid",value:e.data}}}by.create=e=>new by({typeName:wy.ZodNaN,...mg(e)});class _y extends fg{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ty extends fg{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?sg:"dirty"===e.status?(t.dirty(),ng(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?sg:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Ty({in:e,out:t,typeName:wy.ZodPipeline})}}class Cy extends fg{_parse(e){const t=this._def.innerType._parse(e),r=e=>(cg(e)&&(e.value=Object.freeze(e.value)),e);return dg(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function Sy(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Ey(e,t={},r){return e?Wg.create().superRefine((s,n)=>{const i=e(s);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Sy(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Sy(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}}):Wg.create()}var wy,Ry;Cy.create=(e,t)=>new Cy({innerType:e,typeName:wy.ZodReadonly,...mg(t)}),(Ry=wy||(wy={})).ZodString="ZodString",Ry.ZodNumber="ZodNumber",Ry.ZodNaN="ZodNaN",Ry.ZodBigInt="ZodBigInt",Ry.ZodBoolean="ZodBoolean",Ry.ZodDate="ZodDate",Ry.ZodSymbol="ZodSymbol",Ry.ZodUndefined="ZodUndefined",Ry.ZodNull="ZodNull",Ry.ZodAny="ZodAny",Ry.ZodUnknown="ZodUnknown",Ry.ZodNever="ZodNever",Ry.ZodVoid="ZodVoid",Ry.ZodArray="ZodArray",Ry.ZodObject="ZodObject",Ry.ZodUnion="ZodUnion",Ry.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Ry.ZodIntersection="ZodIntersection",Ry.ZodTuple="ZodTuple",Ry.ZodRecord="ZodRecord",Ry.ZodMap="ZodMap",Ry.ZodSet="ZodSet",Ry.ZodFunction="ZodFunction",Ry.ZodLazy="ZodLazy",Ry.ZodLiteral="ZodLiteral",Ry.ZodEnum="ZodEnum",Ry.ZodEffects="ZodEffects",Ry.ZodNativeEnum="ZodNativeEnum",Ry.ZodOptional="ZodOptional",Ry.ZodNullable="ZodNullable",Ry.ZodDefault="ZodDefault",Ry.ZodCatch="ZodCatch",Ry.ZodPromise="ZodPromise",Ry.ZodBranded="ZodBranded",Ry.ZodPipeline="ZodPipeline",Ry.ZodReadonly="ZodReadonly";const Ay=Bg.create,Ny=qg.create,Oy=jg.create;Wg.create;const My=Jg.create,Uy=Qg.create,Ly=Yg.create,ky=ey.create,Dy=ty.create;sy.create,ny.create;const Py=iy.create,xy=ly.create;py.create,gy.create,yy.create;class Fy{static validate(e,t){try{return{success:!0,data:e.parse(t)}}catch(r){if(r instanceof Yf){const e=r.errors.map(e=>({path:e.path.length>0?e.path.join("."):"root",message:e.message,rule:e.code})),t=`Validation failed: ${e.map(e=>`${e.path}: ${e.message}`).join("; ")}`,s=r.errors.some(e=>"invalid_type"===e.code&&"undefined"===e.received)?ot.VALIDATION_REQUIRED:ot.VALIDATION_INVALID_FORMAT;return{success:!1,error:new mt(t,{code:s,details:{fields:e}})}}return{success:!1,error:new mt("Unknown validation error",{code:ot.VALIDATION_UNKNOWN,details:{fields:[]}})}}}static validateOrThrow(e,t){const r=this.validate(e,t);if(r.success&&void 0!==r.data)return r.data;if(r.error)throw r.error;throw new mt("Unknown validation error",{code:ot.VALIDATION_UNKNOWN,details:{fields:[]}})}static safeParse(e,t){return this.validate(e,t)}}const By=e=>Ay().regex(/^https?:\/\/\S+$/i,e),Gy=ky({appKey:Ay().min(1,"appKey is required").optional(),appId:Ay().min(1,"appId is required").optional(),enableUserInfoSync:Oy().optional(),enableSyncData:Ly(xy(["conversation","contact","group"])).optional(),enableDeliveryReceipt:Oy().optional(),deleteConversationOnGroupDestroyed:Oy().optional(),syncConversationListConfig:ky({includeEmpty:Oy().optional()}).strict().optional(),useCustomAttachmentUpload:Oy().optional(),useFixedDeviceId:Oy().optional(),deviceId:Ay().min(1,"deviceId is required").optional(),serviceConfig:ky({dnsConfigUrls:Ly(By("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:ky({restApiUrl:By("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:(qy="serviceConfig.serverUrls.wsUrl must be a valid URL",Ay().regex(/^wss?:\/\/\S+$/i,qy)).optional()}).optional()}).optional(),useReplacedMessageContents:Oy().optional(),customDeviceName:Ay().min(1,"customDeviceName is required").optional(),customOSPlatform:Ny().int("customOSPlatform must be an integer").min(1,"customOSPlatform must be between 1 and 100").max(100,"customOSPlatform must be between 1 and 100").optional(),uiKitVersion:Ay().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:Ay().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:Ly(My()).optional(),platformAdapterOptions:ky({prefer:xy(["web","wechat-miniapp","qq-miniapp","toutiao-miniapp","baidu-miniapp","alipay-miniapp","dingtalk-miniapp","lark-miniapp","kuaishou-miniapp","jd-miniapp","360-miniapp","harmony-miniapp","quickapp","uniapp","react-native","electron-renderer","electron-main","unknown"]).optional(),runtimeInput:Ey(e=>"object"==typeof e&&null!==e).optional(),transportAdapter:Ey(e=>"object"==typeof e&&null!==e).optional(),overrides:Ey(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{const r=Number(void 0!==e.appKey)+Number(void 0!==e.appId);0===r?t.addIssue({code:Zf.custom,path:["appKey"],message:"appKey or appId is required"}):r>1&&t.addIssue({code:Zf.custom,path:["appId"],message:"appKey and appId cannot be used together"}),"enableMd5Check"in e&&t.addIssue({code:Zf.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:Zf.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:Zf.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:Zf.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:Zf.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:Zf.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:Zf.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const s=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,n=s?.serverUrls&&"object"==typeof s.serverUrls?s.serverUrls:void 0;s?.dnsConfigUrls&&n&&t.addIssue({code:Zf.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),n&&(void 0!==e.appId&&t.addIssue({code:Zf.custom,path:["serviceConfig","serverUrls"],message:"serviceConfig.serverUrls cannot be used when initialized with appId"}),n?.restApiUrl||t.addIssue({code:Zf.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),n?.wsUrl||t.addIssue({code:Zf.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))});var qy;const $y=ky({userId:Ay().min(1,"userId is required"),token:Ay().min(1,"token is required")}),jy=ky({timeoutMs:Ny().int("timeoutMs must be an integer").min(5e3,"timeoutMs must be at least 5000").max(Zr,"timeoutMs must be at most 120000").optional()}).strict(),Vy=Ay().trim().min(1,"token is required"),Ky=ky({channelName:Ay().trim().min(1,"channelName is required").optional()}).optional(),zy=Ly(Ny({invalid_type_error:"rtcUid must be a number"}).int("rtcUid must be an integer").min(0,"rtcUid must be greater than or equal to 0").max(Number.MAX_SAFE_INTEGER,"rtcUid must be a safe integer")).nonempty("rtcUids is required").transform(e=>Array.from(new Set(e))),Hy=ky({protocol:Ay(),domain:Ay().optional(),ip:Ay().optional(),port:Dy([Ay(),Ny()]).optional()}).passthrough(),Wy=ky({app_key:Ay().optional(),rest:ky({hosts:Ly(Hy).nonempty()}),"msync-wx":ky({hosts:Ly(Hy).nonempty()}),"sync-ws":ky({hosts:Ly(Hy).nonempty()}).optional(),enableReportLogs:xy(["true","false"]).optional(),reportInterval:Ny().positive().finite().optional(),enableDataReport:xy(["true","false"]).optional(),enableMd5Check:xy(["true","false"]).optional(),uploadinparts_enable:xy(["true","false"]).optional()}).passthrough(),Jy=e=>encodeURIComponent(e).replace(/[!'()~]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g,"+"),Qy=e=>"function"==typeof URLSearchParams?new URLSearchParams(e):(e=>{const t=new Map;if(e)for(const[r,s]of Object.entries(e))t.set(r,s);return{set(e,r){t.set(e,r)},toString:()=>Array.from(t,([e,t])=>`${Jy(e)}=${Jy(t)}`).join("&")}})(e),Zy="5.1.2",Yy=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],Xy=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"];function ev(e){return"object"==typeof e&&null!==e}function tv(e){return Array.isArray(e)?{hosts:e}:function(e){return ev(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function rv(e){if(!ev(e))return Fy.validateOrThrow(Wy,e);const t=tv(e.rest),r=function(e,t,r){for(const s of t){const t=tv(e[s]);if(t)return{key:s,section:t}}for(const[s,n]of Object.entries(e)){if(!r(s))continue;const e=tv(n);if(e)return{key:s,section:e}}}(e,Xy,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),s={...e,rest:t??e.rest,"msync-wx":r?.section},n="true"===(i=e.enableReportLogs)||!0===i?"true":"false"===i||!1===i?"false":void 0;var i;n&&(s.enableReportLogs=n);const o=function(e){if("number"!=typeof e&&"string"!=typeof e)return;if("string"==typeof e&&""===e.trim())return;const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}(e.reportInterval);void 0!==o?s.reportInterval=o:delete s.reportInterval;const a=function(e){if("true"===e||"false"===e)return e}(e.enableDataReport);a?s.enableDataReport=a:delete s.enableDataReport;const c=function(e){if("true"===e||"false"===e)return e}(e.enableMd5Check);c?s.enableMd5Check=c:delete s.enableMd5Check;const d=function(e){if("true"===e||"false"===e)return e}(e.uploadinparts_enable);return d?s.uploadinparts_enable=d:delete s.uploadinparts_enable,r&&"msync-wx"!==r.key&&Vs("DNS config websocket section normalized",{sourceKey:r.key}),Fy.validateOrThrow(Wy,s)}function sv(e,t){const r=e.domain||e.ip;if(!r)throw new mt("DNS host missing domain/ip",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"dns.host",message:"DNS host missing domain/ip",rule:"required"}]}});const s=void 0!==e.port?String(e.port):"";return`${"https"===t?"wss":"ws"}://${s&&"80"!==s&&"443"!==s?`${r}:${s}`:r}/websocket`}function nv(e,t){return"https"===e?"https":"http"===e?"http":t}function iv(e,t){const r=e.domain||e.ip;if(!r)throw new mt("DNS rest host missing domain/ip",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"dns.rest.host",message:"DNS rest host missing domain/ip",rule:"required"}]}});const s=void 0!==e.port?String(e.port):"";return`${t}://${s&&"80"!==s&&"443"!==s?`${r}:${s}`:r}`}function ov(e,t){const r=e.filter(e=>e.protocol===t);return r.length>0?r:"http"===t?e.filter(e=>"https"===e.protocol):[]}function av(e){const t=function(e){return e.filter(e=>Boolean(e.domain))}(e);return t.length>0?t:e.filter(e=>Boolean(e.domain||e.ip))}async function cv(e,t,r,s){const n=new Vf(e,{requestAdapter:r,includeRequestId:!0});let i="/easemob/server.json",o=!0;try{const t=new URL(e),r=""!==t.pathname&&"/"!==t.pathname,s=""!==t.search;(r||s)&&(i="",o=!1)}catch{i="/easemob/server.json",o=!0}if(o){i=`${i}?${(void 0!==t.appId?Qy({app_id:t.appId,sdk_version:Zy,file_version:"1"}):Qy({app_key:t.appKey,_v:String(Date.now())})).toString()}`}return rv(await n.get(i,{timeout:s}))}async function dv(e){const t=e.baseUrls&&e.baseUrls.length>0?e.baseUrls:Yy;if(0===t.length)throw new mt("DNS_CONFIG list is empty",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"serviceConfig.dnsConfigUrls",message:"DNS_CONFIG list is empty",rule:"required"}]}});const r=e.pageProtocol??("undefined"==typeof window||"https:"===window.location?.protocol?"https":"http");let s;for(const o of t){const t=e.loginDeadline,n=t?.remainingMs();if(t&&void 0!==n&&n<=0)throw t.createTimeoutError();try{const t=void 0!==e.appId?{appId:e.appId}:{appKey:e.appKey},s=void 0===n?void 0:Math.min(15e3,n),i=await cv(o,t,e.requestAdapter,s),a=void 0!==e.appId?i.app_key:e.appKey;if("string"!=typeof a||0===a.length)throw new mt("DNS app_key is required for appId initialization",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"dns.app_key",message:"DNS app_key is required for appId initialization",rule:"required"}]}});const c=av(ov(i["msync-wx"].hosts,r));if(0===c.length)throw new mt("DNS msync-wx hosts resolution failed",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const d=c[0];if(!d)throw new mt("DNS msync-wx hosts resolution failed",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const u=ov(i.rest.hosts,r);if(0===u.length)throw new mt("DNS rest hosts resolution failed",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const l=u[0];if(!l)throw new mt("DNS rest hosts resolution failed",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const h=c.map(e=>sv(e,nv(e.protocol,r))),p=sv(d,nv(d.protocol,r));return{appKey:a,websocketUrl:p,websocketUrls:h,baseUrl:o,restBaseUrl:iv(l,nv(l.protocol,r)),dnsConfig:i}}catch(i){if(t&&t.remainingMs()<=0)throw t.createTimeoutError();Vs("DNS config candidate failed",{baseUrl:o,reason:i instanceof Error?i.message:String(i),error:i instanceof Error&&"function"==typeof i.toJSON?i.toJSON():i}),s=i}}const n={stage:"dns"};throw s&&(n.reason=s.message,"code"in s&&"number"==typeof s.code&&(n.causeCode=s.code)),new ht("DNS_CONFIG exhausted",{code:ot.CONNECTION_DNSLIST_FAILED,details:n})}const uv=e=>{const t=(e=>{const t=e.trim(),r=/^(https?):\/\//i.exec(t);if(!r?.[1])throw new mt("REST API URL must use http or https protocol");const s=r[1].toLowerCase(),n=t.slice(r[0].length),i=n.search(/[/?#]/),o=i>=0?n.slice(0,i):n,a=o.lastIndexOf("@"),c=a>=0?o.slice(a+1):o;if(!c)throw new mt("REST API URL host is required");let d,u;if(c.startsWith("[")){const e=c.indexOf("]");if(e<=1)throw new mt("REST API URL IPv6 host is invalid");d=c.slice(0,e+1);const t=c.slice(e+1);if(t){if(!t.startsWith(":"))throw new mt("REST API URL authority is invalid");u=t.slice(1)}}else{const e=c.lastIndexOf(":");if(e>=0){if(c.indexOf(":")!==e)throw new mt("REST API URL IPv6 host must use brackets");d=c.slice(0,e),u=c.slice(e+1)}else d=c}if(!d)throw new mt("REST API URL host is required");if(void 0!==u){const e=Number(u);if(!/^\d+$/.test(u)||e<1||e>65535)throw new mt("REST API URL port is invalid")}return{protocol:s,host:d,port:u}})(e),r="http"===t.protocol&&"80"===t.port||"https"===t.protocol&&"443"===t.port,s="https"===t.protocol?"wss":"ws",n=t.port&&!r?`:${t.port}`:"";return`${s}://${t.host}${n}/ws`},lv=e=>new mt(e,{code:ot.VALIDATION_INVALID_FORMAT,details:{reason:"invalid_rest_response"}}),hv=e=>{if(!pu(e))throw lv("Invalid REST response");return pu(e.data)?e.data:e},pv=(e,t)=>{for(const r of t){const t=e[r];if("number"==typeof t&&Number.isFinite(t))return t;if("string"==typeof t&&t.trim().length>0){const e=Number(t);if(Number.isFinite(e))return e}}},mv=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t)return t}},fv=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}`},gv=async(e,t)=>{const r=await e.get((e=>`${fv(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=hv(e),r=pv(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===r)throw lv("Invalid token expires response");return r})(r)},yv=async(e,t,r)=>{const s=await e.get(((e,t)=>{const r=Qy({channelName:t?.channelName??"*"});return`${fv(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${r.toString()}`})(t,r),{operation:"getRtcTokenInfo"});return(e=>{const t=hv(e);return{appId:mv(t,["app_id","appId"])??"",rtcToken:mv(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:mv(t,["channel_name","channelName"])??"",rtcUid:pv(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:pv(t,["expires_in","expire","expireAt"])??0}})(s)},vv=async(e,t,r)=>{const s=await e.post((e=>`${fv(e)}/rtc_mapper/batch/get`)(t),{data:r},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=hv(e),r={};for(const[s,n]of Object.entries(t)){const e=Number(s);!Number.isSafeInteger(e)||e<0||"string"!=typeof n||(r[e]=n)}return r})(s)},Iv=async(e,t)=>{const r=await e.get((e=>`${fv(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const r=pu(e)&&Array.isArray(e.data)?e.data:[],s=[];for(const n of r){if(!pu(n))continue;const e=mv(n,["res","resource","clientResource"]);e&&e!==t.clientResource&&s.push(`${t.userId}/${e}`)}return s})(r,t)},bv=(...e)=>{const t={},r={};for(const s of e)Object.assign(t,s.common),Object.assign(r,s.apis);return{common:t,apis:r}},_v={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:{}},Tv=e=>({userId:e}),Cv=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Sv=e=>e,Ev=async(e,t)=>{const r=(e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,Cv(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,Sv(t))}for(const o of r)s.has(o)||s.set(o,Tv(o));return s};class wv{constructor(e){this.options=e,this.pendingGroups=new Map,this.readyGroups=[],this.pendingOrder=[],this.activeGroups=new Set,this.timer=null,this.activeGroupCount=0}enqueue(e,t,r){if(!e||!t)return;const s=this.pendingGroups.get(e)??new Map;this.pendingGroups.has(e)||(this.pendingGroups.set(e,s),this.pendingOrder.push(e));const n=s.get(t);s.set(t,{userId:t,namecardUpdateTime:this.resolveMaxVersion(n?.namecardUpdateTime,r)}),this.schedule()}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingGroups.clear(),this.pendingOrder.length=0,this.readyGroups.length=0,this.activeGroups.clear(),this.activeGroupCount=0}getOptions(){return{windowMs:this.options.windowMs,minWindowMs:this.options.minWindowMs,maxBatchSize:this.options.maxBatchSize,maxConcurrency:this.options.maxConcurrency}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flushWindow()},this.resolveWindowDelay()))}flushWindow(){if(0!==this.pendingOrder.length){for(const e of this.pendingOrder){const t=this.pendingGroups.get(e);if(!t||0===t.size)continue;const r=Array.from(t.values()),s=Math.max(1,this.options.maxBatchSize);for(let n=0;n<r.length;n+=s)this.readyGroups.push({groupId:e,targets:r.slice(n,n+s)})}this.pendingGroups.clear(),this.pendingOrder.length=0,this.runReadyGroups()}}runReadyGroups(){for(;this.activeGroupCount<this.options.maxConcurrency&&this.readyGroups.length>0;){const e=this.readyGroups.findIndex(e=>!this.activeGroups.has(e.groupId));if(e<0)return;const t=this.readyGroups.splice(e,1)[0];if(!t)return;this.activeGroupCount+=1,this.activeGroups.add(t.groupId),Promise.resolve(this.options.onFlushGroup(t)).catch(e=>{Vs("Group namecard hydration queue flush failed",{groupId:t.groupId,userIds:t.targets.map(e=>e.userId),error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.activeGroupCount-=1,this.activeGroups.delete(t.groupId),this.runReadyGroups()})}}resolveWindowDelay(){const e=Math.max(0,Math.min(this.options.minWindowMs,this.options.windowMs)),t=Math.max(e,this.options.windowMs),r=t-e;return r<=0?t:e+Math.floor(Math.random()*(r+1))}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class Rv{constructor(e){this.options=e,this.pendingTargets=new Map,this.readyBatches=[],this.timer=null,this.activeCount=0,this.generation=0}enqueue(e,t){e&&(this.mergeWaitingTarget({userId:e,userInfoUpdateTime:t,retryCount:0}),this.pendingTargets.size>=this.options.batchSize?this.flush():this.schedule())}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingTargets.clear(),this.readyBatches.length=0,this.generation+=1}getOptions(){return{windowMs:this.options.windowMs,batchSize:this.options.batchSize,maxConcurrency:this.options.maxConcurrency,maxRetries:this.options.maxRetries}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.options.windowMs))}flush(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),0===this.pendingTargets.size)return;const e=Array.from(this.pendingTargets.values());this.pendingTargets.clear();const t=Math.max(1,this.options.batchSize);for(let r=0;r<e.length;r+=t)this.readyBatches.push(e.slice(r,r+t));this.runReadyBatches()}runReadyBatches(){const e=Math.max(1,this.options.maxConcurrency);for(;this.activeCount<e&&this.readyBatches.length>0;){const e=this.readyBatches.shift();if(!e)return;const r=this.generation;this.activeCount+=1;const s=e.map(({userId:e,userInfoUpdateTime:t})=>({userId:e,userInfoUpdateTime:t}));let n;try{n=Promise.resolve(this.options.onFlush(s))}catch(t){n=Promise.reject(t instanceof Error?t:new Error(String(t)))}n.catch(t=>{const s=e.filter(e=>e.retryCount<Math.max(0,this.options.maxRetries)).map(e=>({...e,retryCount:e.retryCount+1}));if(Vs("User info hydration queue flush failed",{targets:e.map(e=>e.userId),retrying:s.length>0,error:t instanceof Error?t.message:String(t)}),r===this.generation&&0!==s.length){for(const e of s)this.mergeWaitingTarget(e);this.flush()}}).finally(()=>{this.activeCount-=1,this.runReadyBatches()})}}mergeWaitingTarget(e){for(const r of this.readyBatches){const t=r.findIndex(t=>t.userId===e.userId);if(t>=0){const s=r[t];return void(s&&(r[t]=this.mergeTarget(s,e)))}}const t=this.pendingTargets.get(e.userId);this.pendingTargets.set(e.userId,t?this.mergeTarget(t,e):e)}mergeTarget(e,t){return{userId:e.userId,userInfoUpdateTime:this.resolveMaxVersion(e.userInfoUpdateTime,t.userInfoUpdateTime),retryCount:Math.max(e.retryCount,t.retryCount)}}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class Av{constructor(e,t,r=Date.now){this.attemptId=e,this.timeoutMs=t,this.now=r,this.timeoutId=null,this.status="active",this.expiresAt=this.now()+t,this.timeoutPromise=new Promise((e,r)=>{this.timeoutId=setTimeout(()=>{"active"===this.status&&(this.status="expired",this.timeoutId=null,r(this.createTimeoutError()))},t)}),this.timeoutPromise.catch(()=>{})}getStatus(){return this.status}remainingMs(){return"expired"===this.status?0:Math.max(0,this.expiresAt-this.now())}clamp(e){return Math.max(0,Math.min(e,this.remainingMs()))}race(e){return"expired"===this.status||0===this.remainingMs()?(e.catch(()=>{}),this.expire(),Promise.reject(this.createTimeoutError())):"active"!==this.status?e:Promise.race([e,this.timeoutPromise])}markProvisionReceived(){return"active"===this.status&&(this.status="provision-received",this.clearTimer(),!0)}expire(){"active"===this.status&&(this.status="expired",this.clearTimer())}dispose(){"active"===this.status&&(this.status="disposed"),this.clearTimer()}createTimeoutError(){return new ht("Login timeout",{code:ot.CONNECTION_LOGIN_TIMEOUT,details:{stage:"login",timeoutMs:this.timeoutMs,attemptId:this.attemptId,retryable:!0}})}clearTimer(){null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}}const Nv=0,Ov=1,Mv=2,Uv=3,Lv=4,kv=5,Dv=0,Pv=0,xv=1,Fv=1001,Bv=1002,Gv=1003,qv=1004,$v=1005,jv=1101,Vv=bv(_v,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),Kv=class e{constructor(e){this.core=null,this.cacheManager=null,this.cacheUserId=null,this.state=t,this.loginAttempt=0,this.currentUserId=null,this.activeAppKey=null,this.logReportEnabled=!1,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.contactSyncController=null,this.groupSyncController=null,this.syncConversationListConfigController=null,this.syncWebSocketSession=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.conversationListVersion=0,this.conversationListSnapshot=[],this.activeIncomingStreamMessageIds=new Set,this.managerSessionGeneration=0,this.activeManagerSessionContext=null,this.managerSessionEndingPromise=null,this.postLoginTaskContext=null,this.terminalSessionCleanupTask=null,this.config={appKey:e.appKey,appId:e.appId,enableUserInfoSync:e.enableUserInfoSync,enableSyncData:[...e.enableSyncData],enableDeliveryReceipt:e.enableDeliveryReceipt,deleteConversationOnGroupDestroyed:e.deleteConversationOnGroupDestroyed,syncConversationListConfig:{...e.syncConversationListConfig},useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,serviceConfig:{mode:e.serviceConfig.mode,dnsConfigUrls:[...e.serviceConfig.dnsConfigUrls],hasCustomDnsConfigUrls:e.serviceConfig.hasCustomDnsConfigUrls,serverUrls:e.serviceConfig.serverUrls},useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,useReplacedMessageContents:e.useReplacedMessageContents,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,cacheEncryptionMode:e.cacheEncryptionMode,profileSync:{...e.profileSync},platformAdapterOptions:e.platformAdapterOptions},this.activeAppKey=this.config.appKey??null,this.config.platformAdapterOptions&&(this.platformAdapter=Dd(this.config.platformAdapterOptions)),this.managerRegistry=new Map,this.managerCapabilities=new Map,this.eventHub=new Pm,Ls=e=>{this.eventHub.dispatch(V.LOG,e)},this.managerEventContext={addEventHandler:(e,t)=>{this.eventHub.addEventHandler(e,t)},removeEventHandler:e=>{this.eventHub.removeEventHandler(e)},dispatch:(e,t)=>{this.eventHub.dispatch(e,t)}},this.userInfoHydrationQueue=new Rv({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:3,maxRetries:1,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new wv({windowMs:this.config.profileSync.groupNamecardWindowMs,minWindowMs:1e3,maxBatchSize:50,maxConcurrency:this.config.profileSync.groupNamecardMaxConcurrency,onFlushGroup:async e=>{await this.flushGroupNamecardHydrationBatch(e)}}),this.eventHub.addEventHandler("__internal:chat-client",{[o]:e=>{this.updateState(e.state)},[a]:e=>{this.updateState(e.state)},[c]:e=>{this.updateState(e.state),this.isTerminalManagerSessionDisconnect(e)&&this.startTerminalSessionCleanup(e)},[d]:e=>{this.updateState(e.state)},[M]:e=>{this.handleIncomingConversationMessage(e),this.handleIncomingMessageProfileSync(e)},[U]:e=>{this.handleIncomingConversationStreamMessage(e)},[I]:e=>{this.handleOutgoingConversationMessage(e)},[G]:e=>{this.handleMultiDeviceContactEvent(e)},[q]:e=>{if("CONVERSATION_DELETED"===e.operation)return this.handleMultiDeviceConversationEvent(e)},[W]:e=>this.handleIncomingContactRosterEvent("add",e),[Q]:e=>this.handleIncomingContactRosterEvent("add",e),[z]:e=>this.handleIncomingContactRosterEvent("none",e),[J]:e=>this.handleIncomingContactRosterEvent("none",e),[H]:e=>this.handleIncomingContactRosterEvent("remove",e),[f]:async e=>{await this.dispatchRawNotifyToCapability("rawNotify:group",{type:"group",payload:e}),e.eventName===ie&&await this.handleGroupDestroyedConversation(e.payload.groupId)},[g]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatroom",{type:"chatroom",payload:e}),[y]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatThread",{type:"chatThread",payload:e}),[v]:e=>this.dispatchRawNotifyToCapability("rawNotify:userInfo",{type:"userInfo",payload:e})})}static init(t){const r=Fy.validateOrThrow(Gy,t),s=r.customOSPlatform,n=e.normalizeServiceConfig(r.serviceConfig),i={appKey:r.appKey,appId:r.appId,enableUserInfoSync:r.enableUserInfoSync??!1,enableSyncData:e.normalizeSyncDataTypes(r.enableSyncData??["conversation"]),enableDeliveryReceipt:r.enableDeliveryReceipt??!1,deleteConversationOnGroupDestroyed:r.deleteConversationOnGroupDestroyed??!0,syncConversationListConfig:{includeEmpty:r.syncConversationListConfig?.includeEmpty??!1,includeMark:!0},useCustomAttachmentUpload:r.useCustomAttachmentUpload??!1,enableMd5Check:!1,serviceConfig:n,useFixedDeviceId:r.useFixedDeviceId??!0,deviceId:r.deviceId??"webim",useReplacedMessageContents:r.useReplacedMessageContents??!1,customDeviceName:void 0!==s?r.customDeviceName:void 0,customOSPlatform:s,uiKitVersion:r.uiKitVersion,loginExtensionInfo:r.loginExtensionInfo,cacheEncryptionMode:"auto",profileSync:{userInfoWindowMs:7e3,userInfoBatchSize:20,groupNamecardWindowMs:7e3,groupNamecardMaxConcurrency:5},platformAdapterOptions:r.platformAdapterOptions},o=t.managers??[];if(e.instance){if(!e.isSameConfig(e.instance.config,i))throw new mt("ChatClient already initialized with different config",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"config",message:"ChatClient already initialized with different config",rule:"conflict"}],current:e.instance.config,next:i}});return o.length>0&&e.instance.registerManagers(o),e.instance.validateOptionalCapabilityDependencies(),e.instance}return e.instance=new e(i),o.length>0&&e.instance.registerManagers(o),e.instance.validateOptionalCapabilityDependencies(),e.instance}async login(n,i){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});const o=Fy.validateOrThrow($y,n),a=Fy.validateOrThrow(jy,i??{});if(await this.waitForTerminalSessionCleanup(),this.state===r||this.state===s){const e=this.currentUserId&&this.currentUserId!==o.userId;throw new ht(e?"Another user is already logged in":"ChatClient is already connecting or connected",{code:e?ot.USER_ALREADY_LOGIN_ANOTHER:ot.AUTH_ALREADY_LOGIN,details:{stage:"auth",...e?{currentUserId:this.currentUserId,nextUserId:o.userId}:{}}})}const c=++this.loginAttempt,d=new Av(c,a.timeoutMs??3e4);try{let e=this.config.appKey??null;this.activeAppKey=e,Vs("Login started",{userId:o.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const s=this.platformAdapter??Dd(this.config.platformAdapterOptions);this.platformAdapter=s,(e=>{Ah?.reset(),Ah=new Rh(e)})({requestAdapter:s.request,onDiagnostic:(e,t)=>{Vs(e,t)}});const n=(e=>Ah?.startSession(e))({appKey:e??"default#appkey",uid:o.userId,sdkVersion:Zy,platform:s.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),i=s.runtime.getNetworkType?.();i&&i.then(e=>{Mh(e)}).catch(()=>{Mh("unknown")});const a=Uh({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:o.userId});let h,p,m;this.updateState(r),this.logReportEnabled=!1,Bs("unknown");let f,g=!1,y=!1,v=!0;if("dns"===this.config.serviceConfig.mode){const r=a?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const t=await d.race(dv(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:s.request,loginDeadline:d}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:s.request,loginDeadline:d}));e=t.appKey,this.activeAppKey=e,Nh({appKey:e}),Vs("DNS resolved for login",{baseUrl:t.baseUrl,websocketUrl:t.websocketUrl,restBaseUrl:t.restBaseUrl,syncWebSocketSource:"rest"}),h=t.websocketUrl,p=t.websocketUrls;const n=uv(t.restBaseUrl);this.contactSyncWsUrls=[n],this.syncConversationListConfigWsUrls=[n],this.contactSyncDnsResolved=!0,m=t.restBaseUrl,g="true"===t.dnsConfig.enableReportLogs,f=t.dnsConfig.reportInterval,y="true"===t.dnsConfig.enableMd5Check,v="false"!==t.dnsConfig.uploadinparts_enable,r?.finish({code:200,success:!0}),Oh(t.dnsConfig.enableDataReport),js("DNS report switch resolved",{enabled:g})}catch(l){const e=l instanceof ut?l.code:-1,s=l instanceof Error?l.message:String(l);throw r?.finish({code:e,success:!1,description:s}),a?.finish({code:e,success:!1,description:s}),Oh(void 0),Bs("disabled"),this.activeAppKey=this.config.appKey??null,this.updateState(t),d.dispose(),l}}else{const e=this.config.serviceConfig.serverUrls;if(!e?.wsUrl||!e.restApiUrl){const e=new mt("serviceConfig.serverUrls.restApiUrl and serviceConfig.serverUrls.wsUrl are required when serverUrls is configured",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"serviceConfig.serverUrls.restApiUrl",message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured",rule:"required"},{path:"serviceConfig.serverUrls.wsUrl",message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured",rule:"required"}]}});throw a?.finish({code:e.code,success:!1,description:e.message}),Oh(void 0),this.updateState(t),d.dispose(),e}h=e.wsUrl,m=e.restApiUrl;const r=uv(m);y=this.config.enableMd5Check,this.contactSyncWsUrls=[r],this.syncConversationListConfigWsUrls=[r],this.contactSyncDnsResolved=!1,Oh(void 0)}if(!e){const e=new mt("appKey is unavailable after service discovery",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable after service discovery",rule:"required"}]}});throw this.updateState(t),Lh(),d.dispose(),e}Gs({restBaseUrl:m,appKey:e,userId:o.userId,token:o.token,requestAdapter:s.request}),u=f,Rs.updateReportInterval(u),this.logReportEnabled=g,Bs(g?"enabled":"disabled");const I=this.resetCore();if(I?.(),c!==this.loginAttempt){const e=new ht("Login cancelled",{code:ot.CONNECTION_CANCELLED,details:{stage:"auth"}});throw a?.finish({code:ot.CONNECTION_CANCELLED,success:!1,description:e.message}),this.updateState(t),this.activeAppKey=this.config.appKey??null,Lh(),d.dispose(),e}const b=new xp({serverUrl:h,serverUrls:p,userId:o.userId,token:o.token,appKey:e,restBaseUrl:m,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:y,enableMultipartUpload:v,useFixedDeviceId:this.config.useFixedDeviceId,deviceId:this.config.deviceId,customDeviceName:this.config.customDeviceName,customOSPlatform:this.config.customOSPlatform,uiKitVersion:this.config.uiKitVersion,loginExtensionInfo:this.config.loginExtensionInfo,serviceId:n,platformAdapter:s,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub);this.core=b,Gs({resource:b.getClientResource()});const _=a?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:h});try{Vs("Connecting core websocket",{serverUrl:h,restBaseUrl:m,userId:o.userId});try{await d.race(b.connect(d))}finally{d.dispose()}this.throwIfLoginSessionCancelled(c,b),_?.finish({code:200,success:!0}),a?.finish({code:0,success:!0}),Vs("Core websocket connected",{userId:o.userId,resource:b.getClientResource()}),this.currentUserId=o.userId,Nh({uid:o.userId}),this.restBaseUrl=m??null,this.authToken=o.token,this.clientResource=b.getClientResource(),await this.initCacheManager(o.userId),this.throwIfLoginSessionCancelled(c,b),Vs("Cache initialized after login",{userId:o.userId}),this.loadCachedConversations(),this.loadCachedUserInfo(),this.notifyManagersSessionReady(o.userId,this.clientResource),this.startPostLoginTasks(o.userId,c)}catch(l){const e=l instanceof ut?l.code:-1,r=l instanceof Error?l.message:String(l);if(_?.finish({code:e,success:!1,description:r}),a?.finish({code:e,success:!1,description:r}),this.core===b){const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(t),Lh()}finally{e?.()}}throw l}}finally{d.dispose()}var u}startPostLoginTasks(e,t){this.cancelPostLoginTasks();const r={attemptId:t,userId:e,cancelled:!1};this.postLoginTaskContext=r,this.runPostLoginTasks(r).catch(e=>{this.isPostLoginTaskActive(r)&&Vs("Unexpected post-login task failure",{userId:r.userId,reason:e instanceof Error?e.message:String(e)})}).finally(()=>{this.postLoginTaskContext===r&&(this.postLoginTaskContext=null)})}cancelPostLoginTasks(){this.postLoginTaskContext&&(this.postLoginTaskContext.cancelled=!0,this.postLoginTaskContext=null)}isPostLoginTaskActive(e){return!e.cancelled&&this.postLoginTaskContext===e&&e.attemptId===this.loginAttempt&&this.currentUserId===e.userId}async runPostLoginTasks(e){if(!this.isPostLoginTaskActive(e))return;if(await this.runPostLoginTask(e,"self-user-info",async()=>{await this.syncSelfUserInfoAfterLogin()}),!this.isPostLoginTaskActive(e))return;if(this.config.enableSyncData.includes("conversation")&&await this.runPostLoginTask(e,"conversation",async()=>{await this.refreshSessionList(this.config.syncConversationListConfig)}),!this.isPostLoginTaskActive(e))return;const t=this.triggerConfiguredSyncDataAfterLogin(e.userId,e),r=this.logReportEnabled?this.runPostLoginTask(e,"log-report",async()=>{await qs()}):Promise.resolve();await Promise.all([t,r])}async runPostLoginTask(e,t,r){if(this.isPostLoginTaskActive(e))try{await r()}catch(s){if(!this.isPostLoginTaskActive(e))return;Vs("Post-login synchronization step failed",{userId:e.userId,task:t,reason:s instanceof Error?s.message:String(s)})}}async logout(){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});for(this.loginAttempt+=1,this.cancelPostLoginTasks();this.terminalSessionCleanupTask;)await this.terminalSessionCleanupTask;if(this.loginAttempt+=1,this.cancelPostLoginTasks(),await this.notifyManagersSessionEnding("logout"),!this.core){const e=this.detachSessionListSyncController();try{this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("logout"),this.syncWebSocketSession=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.resetManagerSessionRuntimes(),Bs("disabled"),$s(),Lh()}finally{this.contactSyncController=null,this.groupSyncController=null,this.syncWebSocketSession=null,this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.activeAppKey=this.config.appKey??null,this.updateState(t),this.logReportEnabled=!1,e?.()}return}try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await qs()}catch(r){Vs("Report logs on logout failed",r)}await this.core.disconnect()}finally{const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(t),this.logReportEnabled=!1,Bs("disabled"),$s(),Lh()}finally{e?.()}}}getConnectionState(){return this.state}getCurrentUserId(){return this.currentUserId}getClientResource(){return this.clientResource??this.core?.getClientResource()??null}getMessageCreationOptions(){return{useCustomAttachmentUpload:this.config.useCustomAttachmentUpload}}getRestContext(){if(!this.restBaseUrl)throw new mt("restBaseUrl is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"restBaseUrl",message:"restBaseUrl is required",rule:"required"}]}});if(!this.authToken)throw new mt("token is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}});if(!this.currentUserId)throw new mt("userId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"userId",message:"userId is required",rule:"required"}]}});const e=this.clientResource??this.core?.getClientResource();if(!e)throw new mt("clientResource is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"clientResource",message:"clientResource is required",rule:"required"}]}});return{restBaseUrl:this.restBaseUrl,appKey:this.requireActiveAppKey(),userId:this.currentUserId,token:this.authToken,clientResource:e}}async renewToken(e){const t=Fy.validateOrThrow(Vy,e);if(!this.core||!this.currentUserId||this.state!==s)throw new ht("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN,details:{stage:"token",state:this.state}});const r=this.getRestContext(),n={...r},i=new Vf(n.restBaseUrl,{errorMap:Vv,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});i.setAuthToken(t),Vs("Renew token started",{userId:r.userId});const o=await gv(i,n);if(o<=Date.now())throw new ht("Token is expired",{code:ot.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});const a=this.core.renewToken(t,o);return this.authToken=t,Gs({token:t}),Vs("Renew token succeeded",{userId:r.userId,expireAt:o}),a}async getRTCTokenInfo(e){const t=Fy.validateOrThrow(Ky,e),r=this.getRestContext(),s=new Vf(r.restBaseUrl,{errorMap:Vv,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),Vs("Get RTC token info started",{userId:r.userId,hasChannelName:Boolean(t?.channelName)}),yv(s,r,t)}async getUserIdsWithRTCUids(e){const t=Fy.validateOrThrow(zy,e),r=this.getRestContext(),s=new Vf(r.restBaseUrl,{errorMap:Vv,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),Vs("Get userIds with RTC UIDs started",{userId:r.userId,count:t.length}),vv(s,r,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new Vf(e.restBaseUrl,{errorMap:Vv,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return t.setAuthToken(e.token),Vs("Get self ids on other platform started",{userId:e.userId,clientResource:e.clientResource}),Iv(t,e)}getCacheManager(){return this.cacheManager}getManagerByCapability(e){return this.managerCapabilities.get(e)}getUploadAdapter(){return this.platformAdapter?.upload??null}getRequestAdapter(){return this.platformAdapter?.request}addInternalEvent(e,t){this.eventHub.dispatch(e,t)}refreshSessionList(e){return this.cacheManager&&this.currentUserId?this.ensureSessionListSyncController().refresh({includeEmpty:e?.includeEmpty??this.config.syncConversationListConfig.includeEmpty,includeMark:!0}).then(e=>(this.enqueueMissingGroupSessionSenderUserInfos(e),e.map(e=>({...e})))):Promise.resolve([])}getServerUrlsConfig(){return this.config.serviceConfig.serverUrls}getSessionListSyncWsUrls(){return this.buildAuthenticatedSessionListSyncUrls(this.syncConversationListConfigWsUrls)}hasSessionListSyncWsUrl(){return this.syncConversationListConfigWsUrls.length>0}getSharedSyncWebSocketSession(){return this.syncWebSocketSession||(this.syncWebSocketSession=new Ff({socketAdapter:this.platformAdapter?.socket,getUrls:async()=>{const e=this.getSessionListSyncWsUrls();return e.length>0?e:await this.resolveContactSyncUrls()}})),this.syncWebSocketSession}isSessionListDnsProbeAvailable(){return"dns"===this.config.serviceConfig.mode}getSessionListSyncCapabilityState(){return this.syncConversationListConfigController?.getCapabilityState()??null}markConversationAccess(e){this.cacheManager?.markConversationAccess(e)}handleIncomingConversationMessage(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}handleIncomingConversationStreamMessage(e){if(!this.cacheManager)return;const t=e.msgServerId||e.msgLocalId,r=e.stream.status===nt.START_COMPLETED||e.stream.status===nt.FULL||e.stream.status===nt.COMPLETED||e.stream.status===nt.ERROR;if(!this.activeIncomingStreamMessageIds.has(t))return this.applyIncomingConversationMessagePatch(e),void(r||this.activeIncomingStreamMessageIds.add(t));if(!r)return;this.activeIncomingStreamMessageIds.delete(t);this.cacheManager.loadSessionList().some(e=>e.lastMessage?.msgServerId===t)&&this.applyIncomingConversationMessagePatch(e)}applyIncomingConversationMessagePatch(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}handleOutgoingConversationMessage(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}async handleMultiDeviceConversationEvent(e){if("CONVERSATION_DELETED"!==e.operation||!this.cacheManager)return;this.cacheManager.deleteConversation({conversationId:e.conversationId,type:e.conversationType??"singleChat",deletedAt:e.timestamp??Date.now()}).changed&&(await this.cacheManager.flushPending(),this.emitConversationListUpdate("local"))}async handleGroupDestroyedConversation(e){if(!this.config.deleteConversationOnGroupDestroyed||!this.cacheManager)return;this.cacheManager.deleteConversation({conversationId:e,type:"groupChat",deletedAt:Date.now()}).changed&&(await this.cacheManager.flushPending(),this.emitConversationListUpdate("local"))}handleMultiDeviceContactEvent(e){if("CONTACT_REMOVE"!==e.operation||!this.cacheManager)return;this.cacheManager.applyContactRosterNotice({action:"remove",userId:e.targetUserId,rosterVersion:e.rosterVersion}).changed&&this.cacheManager.flushPending()}getContactSnapshot(){return this.cacheManager?this.cacheManager.loadContactSnapshot("cache"):null}handleIncomingContactRosterEvent(e,t){const r=this.resolveContactRosterTargetUserId(t);if(r)return this.cacheManager&&this.currentUserId&&"none"!==e&&this.cacheManager.applyContactRosterNotice({action:e,userId:r,rosterVersion:Zu(t)}),this.hydrateContactRosterPayload(t,r,"remove"!==e)}resolveContactRosterTargetUserId(e){const t=this.currentUserId;return t?e.from===t&&e.to!==t?e.to:e.to===t&&e.from!==t||e.from&&e.from!==t?e.from:e.to&&e.to!==t?e.to:null:null}async hydrateContactRosterPayload(e,t,r){const s=await(async(e,t)=>((e,t,r)=>({userId:r,nickname:t?.nickname??e?.nickname,avatarUrl:t?.avatarUrl??e?.avatarUrl,mail:t?.mail??e?.mail,phone:t?.phone??e?.phone,gender:t?.gender??e?.gender,sign:t?.sign??e?.sign,birth:t?.birth??e?.birth,ext:t?.ext??e?.ext}))(void 0,(await Ev([e],t)).get(e),e))(t,{cacheManager:this.cacheManager,fetchUserInfos:r?async({userIds:e})=>await this.fetchContactEventUserInfos(e):void 0});e.userInfo=s}async fetchContactEventUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoReadCapability();if(!t)return[];try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Vs("Contact roster event user info fetch failed",{userIds:e,error:r}),[]}}isMessageProfileSyncEnabled(){return this.config.enableUserInfoSync}isUserInfoSyncEnabled(){return this.config.enableUserInfoSync}async syncSelfUserInfoAfterLogin(){if(!this.isMessageProfileSyncEnabled()||!this.currentUserId)return;const e=this.getUserInfoReadCapability();if(e)try{0===(await e.getUserInfoByUserId({userIds:[this.currentUserId]})).length&&Vs("Self user info sync returned empty result after login",{userId:this.currentUserId})}catch(t){Vs("Self user info sync failed after login",{userId:this.currentUserId,error:t})}}handleIncomingMessageProfileSync(e){if("RECEIVE"!==e.direct||!this.isMessageProfileSyncEnabled())return;const t=Wu(e),r=e.sender.userId;if(!r||!this.cacheManager)return;const s=this.cacheManager.getUserInfoSummaries([r],!1)[0];if(s&&(e.sender={userId:r,nickname:s.nickname??e.sender.nickname,avatarUrl:s.avatarUrl??e.sender.avatarUrl}),"number"==typeof t?.userInfoUpdateTime?this.shouldHydrateUserInfo(s?.userInfoUpdateTime,t.userInfoUpdateTime)&&this.userInfoHydrationQueue.enqueue(r,t.userInfoUpdateTime):s||this.userInfoHydrationQueue.enqueue(r),"groupChat"!==e.conversationType)return;const n=this.cacheManager.getGroupNamecard(e.conversationId,r,!1);"number"==typeof t?.namecardUpdateTime?this.shouldHydrateGroupNamecard(n?.namecardUpdateTime,t.namecardUpdateTime)&&this.groupNamecardHydrationQueue.enqueue(e.conversationId,r,t.namecardUpdateTime):n||this.groupNamecardHydrationQueue.enqueue(e.conversationId,r)}attachOutgoingMessageProfileVersions(e){if(!this.isMessageProfileSyncEnabled())return void(e=>{zu.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};Hu(e,t)}resolveCurrentUserInfoUpdateTime(){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getUserInfoSummaries([this.currentUserId],!1)[0]?.userInfoUpdateTime}resolveCurrentGroupNamecardUpdateTime(e){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getGroupNamecard(e,this.currentUserId,!1)?.namecardUpdateTime}shouldHydrateUserInfo(e,t){return"number"!=typeof e||e<t}shouldHydrateGroupNamecard(e,t){return"number"!=typeof e||e<t}async flushUserInfoHydrationTargets(e){const t=this.getUserInfoReadCapability();if(!t||0===e.length)return;const r=e.map(e=>e.userId);let s;try{s=await t.getUserInfoByUserId({userIds:r})}catch(d){throw Vs("User info hydration failed",{userIds:r,error:d}),d}const n=this.currentUserId,i=n?s.find(e=>e.userId===n):void 0,o=s.filter(e=>e.userId!==n);i&&this.dispatchOwnInfoUpdated(i),o.length>0&&this.dispatchUserInfoUpdated(o),s.length>0&&this.refreshConversationDisplayFromUserInfos(s.map(e=>({userId:e.userId})),"profile");const a=new Set(s.map(e=>e.userId)),c=r.filter(e=>!a.has(e));c.length>0&&Vs("User info hydration returned partial result",{requestedUserIds:r,missingUserIds:c})}async flushGroupNamecardHydrationBatch(e){const t=this.getGroupNamecardHydrationCapability();if(t&&0!==e.targets.length)try{await t.hydrateMessageProfileGroupNamecards(e.groupId,e.targets)}catch(r){Vs("Group namecard hydration returned partial result",{groupId:e.groupId,requestedUserIds:e.targets.map(e=>e.userId),error:r})}}async refreshContactSnapshot(){if(!this.cacheManager||!this.currentUserId)return;const e=this.ensureContactSyncController();await e.sync()}addEventHandler(e,t){this.eventHub.addEventHandler(e,t)}removeEventHandler(e){this.eventHub.removeEventHandler(e)}use(t){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});return this.registerManagerConstructor(t),this}async sendMessage(t,r){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!t?.sender?.userId)throw new mt("sender.userId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});if(this.currentUserId&&t.sender.userId!==this.currentUserId)throw new mt("sender.userId does not match current user",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"sender.userId",message:"sender.userId does not match current user",rule:"conflict"}]}});if(it(t))throw new ft("Stream message send is not supported",{code:ot.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:t.msgLocalId,retryable:!1}});if(this.core&&this.state!==s&&await this.waitForSendConnectionRecovery(this.core),!this.core||this.state!==s)throw new ft("ChatClient is not connected",{code:ot.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,state:this.state,retryable:!0}});return this.attachOutgoingMessageProfileVersions(t),this.core.sendMessage(t,r)}async waitForSendConnectionRecovery(e){let t=null;const r=e.recoverConnectionForSend().then(()=>!0).catch(e=>(Vs("Send connection recovery failed",{error:e instanceof Error?e.message:String(e)}),!1)),s=new Promise(e=>{t=setTimeout(()=>{e(!1)},1e4)}),n=await Promise.race([r,s]);t&&clearTimeout(t),n||Vs("Send connection recovery wait timed out",{timeoutMs:1e4,state:this.state})}dispatchOwnInfoUpdated(e){this.eventHub.dispatch("onOwnInfoUpdated",e)}dispatchUserInfoUpdated(e){0!==e.length&&this.eventHub.dispatch("onUserInfoUpdated",[...e])}refreshConversationDisplayFromUserInfos(e,t="profile"){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromUserInfos(e).changed&&this.emitConversationListUpdate(t)}refreshConversationDisplayFromJoinedGroups(e,t="profile",r){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromJoinedGroups(e.map(e=>({groupId:e.groupId,name:e.name,avatarUrl:e.avatarUrl,remindType:e.remindType})),r).changed&&this.emitConversationListUpdate(t)}enqueueMissingGroupSessionSenderUserInfos(e){if(!this.isMessageProfileSyncEnabled()||!this.cacheManager||0===e.length)return;const t=new Set;for(const n of e){const e="groupChat"===n.conversationType?n.lastMessage?.sender:null;!e?.userId||e.nickname&&e.avatarUrl||t.add(e.userId)}if(0===t.size)return;const r=this.cacheManager.getUserInfoSummaries([...t],!1),s=new Set(r.map(e=>e.userId));for(const n of t)s.has(n)||this.userInfoHydrationQueue.enqueue(n)}dispatchUserGroupNamecardUpdated(e,t,r){e&&t&&this.eventHub.dispatch(Ce,{groupId:e,userId:t,namecard:r})}async downloadAndParseCombinePayload(t){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN,details:{fields:[{path:"core",message:"ChatClient is not connected",rule:"state"}]}});return this.core.downloadAndParseCombineMessage(t)}async sendMessageAction(t,r){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED});if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN});return this.core.sendMessageAction(t,r)}async sendChatRoomOperation(t,r){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED});if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN});return this.core.sendChatRoomOperation(t,r)}async downloadAttachment(t){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED});if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN});return this.core.downloadAttachment(t)}decodeServerMessageMeta(e){if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN});return this.core.decodeServerMessageMeta(e)}registerManagers(e){if(0===e.length)return;const t=new Set;for(const r of e){const e=this.resolveManagerKey(r);if(t.has(e))throw this.buildManagerValidationError(`Manager key duplicated: ${e}`,ot.VALIDATION_INVALID_FORMAT,"managers.key","conflict",{managerKey:e});t.add(e)}for(const r of e)this.registerManagerInput(r)}registerManagerInput(t){return e.isManagerConstructor(t)?this.registerManagerConstructor(t):this.registerManagerInstance(t)}registerManagerConstructor(e){const t=this.getManagerKeyFromConstructor(e),r=this.managerRegistry.get(t);if(r){if(r.constructor===e)return r;throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromConstructor(e),"constructor-mismatch")}const s=new e;return s.bind(this,this.managerEventContext),this.managerRegistry.set(t,s),this.registerManagerCapabilities(s),this.attachManager(t,s),this.notifyManagerSessionReady(s),s}registerManagerInstance(e){const t=this.getManagerKeyFromInstance(e),r=this.managerRegistry.get(t);if(r){if(r===e)return e;if(r.constructor===e.constructor)throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromInstance(e),"instance-conflict");throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromInstance(e),"constructor-mismatch")}return e.bind(this,this.managerEventContext),this.managerRegistry.set(t,e),this.registerManagerCapabilities(e),this.attachManager(t,e),this.notifyManagerSessionReady(e),e}registerManagerCapabilities(e){for(const t of e.capabilities??[])this.managerCapabilities.set(t,e)}dispatchRawNotifyToCapability(e,t){const r=this.getManagerByCapability(e);return r?.handleRawNotify?.(t)}getUserInfoReadCapability(){const e=this.getManagerByCapability("userInfo:read");return e&&this.hasUserInfoReadCapability(e)?e:null}getGroupNamecardHydrationCapability(){const e=this.getManagerByCapability("group:namecard");return e&&this.hasGroupNamecardHydrationCapability(e)?e:null}validateOptionalCapabilityDependencies(){if(this.config.enableUserInfoSync&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","userInfo:read",["UserInfoManager"]);if(this.config.enableUserInfoSync&&!this.getGroupNamecardHydrationCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","group:namecard",["GroupManager"]);if(this.config.enableSyncData.includes("contact")&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableSyncData: ['contact']","userInfo:read",["UserInfoManager"]);if(this.config.enableSyncData.includes("group")&&!this.managerRegistry.has("groupManager"))throw this.buildMissingCapabilityError("enableSyncData: ['group']","rawNotify:group",["GroupManager"])}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}hasGroupNamecardHydrationCapability(e){return"function"==typeof e.hydrateMessageProfileGroupNamecards}buildMissingCapabilityError(e,t,r){return new mt(`${e} requires explicit manager capability: ${t}`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} requires explicit manager capability: ${t}`,rule:"dependency"}],capability:t,requiredManagers:r}})}resolveManagerKey(t){if(e.isManagerConstructor(t))return this.getManagerKeyFromConstructor(t);if("object"!=typeof t||null===t)throw this.buildManagerValidationError("Manager must be constructor or instance",ot.VALIDATION_INVALID_FORMAT,"managers","type",{receivedType:typeof t});return this.getManagerKeyFromInstance(t)}getManagerKeyFromConstructor(e){const t=e.key;if(!this.isValidManagerKey(t))throw this.buildManagerValidationError("Manager key is required",ot.VALIDATION_REQUIRED,"managers.key","required",{managerType:"constructor",managerName:this.getManagerNameFromConstructor(e)});return t}getManagerKeyFromInstance(e){const t=e.constructor.key;if(!this.isValidManagerKey(t))throw this.buildManagerValidationError("Manager key is required",ot.VALIDATION_REQUIRED,"managers.key","required",{managerType:"instance",managerName:this.getManagerNameFromInstance(e)});return t}attachManager(e,t){Object.prototype.hasOwnProperty.call(this,e)||Object.defineProperty(this,e,{value:t,writable:!1,enumerable:!0})}isValidManagerKey(e){return"string"==typeof e&&e.trim().length>0}getManagerNameFromConstructor(e){return"string"==typeof e.name&&e.name.length>0?e.name:"AnonymousManager"}getManagerNameFromInstance(e){const t=e.constructor;return"string"==typeof t.name&&t.name.length>0?t.name:"AnonymousManager"}buildManagerValidationError(e,t,r,s,n){return new mt(e,{code:t,details:{fields:[{path:r,message:e,rule:s}],...n}})}buildManagerConflictError(e,t,r,s){return this.buildManagerValidationError("Manager key conflict",ot.VALIDATION_INVALID_FORMAT,"managers.key","conflict",{managerKey:e,existingName:t,incomingName:r,reason:s})}static isManagerConstructor(e){return"function"==typeof e}updateState(e){this.state!==e&&(this.state=e)}throwIfLoginSessionCancelled(e,t){if(e!==this.loginAttempt||this.core!==t)throw new ht("Login cancelled",{code:ot.CONNECTION_CANCELLED,details:{stage:"auth"}})}async initCacheManager(e){this.cacheManager&&this.cacheUserId===e||(this.cacheManager=new Dm({appKey:this.requireActiveAppKey(),userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode,storageAdapter:this.platformAdapter?.storage}),this.cacheUserId=e),await this.cacheManager.prepare()}loadCachedConversations(){this.cacheManager&&this.emitConversationListUpdate("conversation",!0)}loadCachedUserInfo(){this.cacheManager&&this.cacheManager.loadUserInfoSummaries()}emitConversationListUpdate(e,t=!1){if(!this.cacheManager)return;const r=this.cacheManager.loadSessionList().map(Cf),s=this.buildConversationListPatch(this.conversationListSnapshot,r,t);(s.reset||0!==s.upserted.length||0!==s.removed.length||s.orderChanged)&&(this.conversationListVersion+=1,this.conversationListSnapshot=r,this.eventHub.dispatch(L,{version:this.conversationListVersion,items:r,reason:e,patch:s}))}buildConversationListPatch(e,t,r){const s=new Map(e.map(e=>[this.buildConversationListKey(e),e])),n=new Map(t.map(e=>[this.buildConversationListKey(e),e])),i=new Set,o=[],a=[];for(const d of t){const e=this.buildConversationListKey(d),t=s.get(e);t&&this.isConversationListItemEqual(t,d)||(o.push(d),i.add(e))}for(const d of e){const e=this.buildConversationListKey(d);n.has(e)||(a.push({conversationId:d.conversationId,conversationType:d.conversationType}),i.add(e))}const c=e.map(e=>this.buildConversationListKey(e)).join("\n")!==t.map(e=>this.buildConversationListKey(e)).join("\n");if(c)for(const d of t)i.add(this.buildConversationListKey(d));return{reset:r,upserted:o,removed:a,affectedKeys:[...i],orderChanged:c}}buildConversationListKey(e){return`${e.conversationType}:${e.conversationId}`}isConversationListItemEqual(e,t){return e.conversationId===t.conversationId&&e.conversationType===t.conversationType&&e.unreadCount===t.unreadCount&&e.lastMessageAt===t.lastMessageAt&&e.isPinned===t.isPinned&&e.pinnedTimestamp===t.pinnedTimestamp&&e.readAt===t.readAt&&e.remindType===t.remindType&&e.conversationName===t.conversationName&&e.conversationAvatar===t.conversationAvatar&&e.marks.length===t.marks.length&&e.marks.every((e,r)=>e===t.marks[r])&&JSON.stringify(e.lastMessage)===JSON.stringify(t.lastMessage)}async triggerContactSync(){this.config.enableSyncData.includes("contact")&&await this.refreshContactSnapshot()}async triggerConfiguredSyncDataAfterLogin(e,t){const r=[];this.config.enableSyncData.includes("contact")&&(Vs("Triggering automatic contact sync after login",{userId:e}),r.push(this.runPostLoginTask(t,"contact",async()=>{await this.triggerContactSync()}))),this.config.enableSyncData.includes("group")&&(Vs("Triggering automatic group sync after login",{userId:e}),r.push(this.runPostLoginTask(t,"group",async()=>{await this.triggerGroupSync()}))),await Promise.all(r)}async triggerGroupSync(){if(!this.config.enableSyncData.includes("group"))return;const e=this.ensureGroupSyncController();await e.sync()}ensureSessionListSyncController(){return this.syncConversationListConfigController||(this.syncConversationListConfigController=new Uf(this)),this.syncConversationListConfigController}ensureContactSyncController(){if(this.contactSyncController)return this.contactSyncController;const e=this.managerRegistry.get("contactManager");if(!e?.createSyncController)throw new mt("ContactManager is required for contact sync",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"contactManager",message:"ContactManager must be registered for enableSyncData: ['contact']",rule:"required"}]}});return this.contactSyncController=e.createSyncController({getContextState:()=>{const e=this.requireCacheManager();return{cacheMeta:e.loadContactCacheMeta(),versionState:e.loadContactVersionState(),cachedSnapshot:e.loadContactSnapshot("cache")}},queryMetadata:async e=>await Kf(this.getRestContext(),e,this.platformAdapter?.request),getSyncUrls:async()=>await this.resolveContactSyncUrls(),getSharedSyncSession:()=>this.getSharedSyncWebSocketSession(),buildRosterRequest:({version:e})=>this.buildContactRosterRequest(e),applySyncResult:e=>{const t=this.requireCacheManager().applyContactSync(e);return this.refreshConversationDisplayFromUserInfos(t.snapshot.items.map(e=>({userId:e.userId})),"profile"),t},onStart:()=>{this.emitSyncDataStart("contact")},onFinish:e=>{this.emitSyncDataFinished({dataType:"contact",status:e?.error?"failed":"success",error:e?.error?{dataType:"contact",code:e.error.code,stage:e.error.stage,message:e.error.message,retryable:e.error.retryable}:void 0})}}),this.contactSyncController}ensureGroupSyncController(){if(this.groupSyncController)return this.groupSyncController;const e=this.managerRegistry.get("groupManager");if(!e?.createSyncController)throw new mt("GroupManager is required for group sync",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"groupManager",message:"GroupManager must be registered for enableSyncData: ['group']",rule:"required"}]}});return this.groupSyncController=e.createSyncController({getRestContext:()=>this.getRestContext(),getSyncUrls:async()=>await this.resolveContactSyncUrls(),getSharedSyncSession:()=>this.getSharedSyncWebSocketSession(),getCacheManager:()=>this.requireCacheManager(),applyRuntimeSnapshot:e=>{const t=this.managerRegistry.get("groupManager");t?.applyJoinedGroupSnapshot?.(e),this.refreshConversationDisplayFromJoinedGroups(e.items,"profile")},getRuntimeSnapshot:()=>{const e=this.managerRegistry.get("groupManager");return e?.getJoinedGroupSnapshotForSync?.()??null},onStart:()=>{this.emitSyncDataStart("group")},onFinish:e=>{this.emitSyncDataFinished({dataType:"group",status:e.status,error:e.error})}}),this.groupSyncController}emitSyncDataStart(e){this.eventHub.dispatch($,{dataType:e})}emitSyncDataFinished(e){this.eventHub.dispatch(j,e)}requireCacheManager(){if(!this.cacheManager)throw new mt("cacheManager is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"cacheManager",message:"cacheManager is required",rule:"required"}]}});return this.cacheManager}async resolveContactSyncUrls(){if(this.contactSyncWsUrls.length>0)return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls);if(this.contactSyncDnsResolved)throw Vs("Derived contact sync websocket is unavailable after DNS precheck",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new ut("Contact sync websocket urls are unavailable",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});if("dns"!==this.config.serviceConfig.mode)throw Vs("Derived contact sync websocket is unavailable for fixed service config",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new ut("Contact sync websocket urls are unavailable",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});try{const e=await dv(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request});this.contactSyncWsUrls=[uv(e.restBaseUrl)],this.contactSyncDnsResolved=!0}catch(e){throw Vs("Automatic contact sync REST endpoint DNS resolve failed",{userId:this.currentUserId,reason:e instanceof Error?e.message:String(e)}),new ut("Contact sync websocket dns resolve failed",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",cause:e instanceof Error?e.message:String(e)}})}return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls)}buildAuthenticatedContactSyncUrls(e){const t=this.requireContactSyncToken();return this.shuffleContactSyncUrls(e.map(e=>this.buildContactSyncSocketUrl(e,t)))}buildAuthenticatedSessionListSyncUrls(e){if(0===e.length)return[];const t=this.requireContactSyncToken();return e.map(e=>this.buildContactSyncSocketUrl(e,t))}requireContactSyncToken(){if(this.authToken)return this.authToken;throw new mt("token is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}})}buildContactSyncSocketUrl(e,t){const r=e.trim();if(!/^wss?:\/\/[^/?#]+/i.test(r))throw new mt("sync websocket URL must use ws or wss protocol");const s=r.indexOf("#"),n=s>=0?r.slice(s):"",i=s>=0?r.slice(0,s):r,o=i.indexOf("?"),a=o>=0?i.slice(0,o):i,c=o>=0?i.slice(o+1):"",d=a.indexOf("://")+3,u=a.indexOf("/",d),l=u<0||"/"===a.slice(u)?`${a}/ws`:a,h=c.split("&").filter(e=>e.length>0&&"token"!==e.split("=",1)[0]),p=encodeURIComponent(t).replace(/%20/g,"+");return h.push(`token=${p}`),`${l}?${h.join("&")}${n}`}shuffleContactSyncUrls(e){const t=[...e];for(let r=t.length-1;r>0;r-=1){const e=Math.floor(Math.random()*(r+1)),s=t[r],n=t[e];s&&n&&(t[r]=n,t[e]=s)}return t}buildContactRosterRequest(e){const t=this.getRestContext(),{orgName:r,appName:s}=fs(t.appKey);return{type:Uv,header:{resource:t.clientResource,timestamp:Date.now(),requestId:`contact-sync-${Date.now()}`,protocolVersion:1},org:r,app:s,username:t.userId,version:e,cursor:0}}detachSessionListSyncController(){const e=this.syncConversationListConfigController;return this.syncConversationListConfigController=null,e?.cancelForTeardown()??null}resetCore(){const e=this.detachSessionListSyncController();try{return this.cancelPostLoginTasks(),this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("reset-core"),this.syncWebSocketSession=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.core?(this.core.destroy(),this.clearCoreSessionState(),this.resetManagerSessionRuntimes(),e):e}catch(r){throw this.clearCoreSessionState(),this.updateState(t),e?.(),r}}clearCoreSessionState(){this.core=null,this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1}requireConfiguredAppKey(){if(this.config.appKey)return this.config.appKey;throw new mt("appKey is unavailable before DNSConfig resolution",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable before DNSConfig resolution",rule:"required"}]}})}requireActiveAppKey(){if(this.activeAppKey)return this.activeAppKey;throw new mt("appKey is unavailable for the current session",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable for the current session",rule:"required"}]}})}resetManagerSessionRuntimes(){for(const t of this.managerRegistry.values())try{t.resetSessionRuntime?.()}catch(e){Vs("Manager session runtime reset failed",{manager:this.getManagerNameFromInstance(t),error:e instanceof Error?e.message:"unknown"})}this.activeManagerSessionContext=null,this.managerSessionEndingPromise=null}notifyManagersSessionReady(e,t){const r={generation:++this.managerSessionGeneration,userId:e,clientResource:t};this.activeManagerSessionContext=r,this.managerSessionEndingPromise=null;for(const s of this.managerRegistry.values())this.notifyManagerSessionReady(s)}notifyManagerSessionReady(e){const t=this.activeManagerSessionContext;if(t&&e.onSessionReady)try{e.onSessionReady(t)}catch(r){Vs("Manager session ready hook failed",{manager:this.getManagerNameFromInstance(e),error:r instanceof Error?r.message:"unknown"})}}notifyManagersSessionEnding(e){const t=this.activeManagerSessionContext;if(!t)return Promise.resolve();if(this.managerSessionEndingPromise)return this.managerSessionEndingPromise;const r={...t,reason:e},s=Array.from(this.managerRegistry.values(),e=>{if(!e.onSessionEnding)return Promise.resolve();try{return Promise.resolve(e.onSessionEnding(r)).catch(t=>{Vs("Manager session ending hook failed",{manager:this.getManagerNameFromInstance(e),error:t instanceof Error?t.message:"unknown"})})}catch(t){return Vs("Manager session ending hook failed",{manager:this.getManagerNameFromInstance(e),error:t instanceof Error?t.message:"unknown"}),Promise.resolve()}}),n=Promise.all(s).then(()=>{});let i=null;const o=new Promise(t=>{i=setTimeout(()=>{Vs("Manager session ending hooks timed out",{timeoutMs:6e3,reason:e}),t()},6e3)});return this.managerSessionEndingPromise=Promise.race([n,o]).then(()=>{null!==i&&clearTimeout(i),this.activeManagerSessionContext?.generation===t.generation&&(this.activeManagerSessionContext=null)}),this.managerSessionEndingPromise}isTerminalManagerSessionDisconnect(e){return e.reason===O||[ot.AUTH_TOKEN_EXPIRED,ot.AUTH_BIND_ANOTHER_DEVICE,ot.AUTH_LOGIN_TOO_MANY_DEVICES,ot.USER_LOGIN_ANOTHER_DEVICE,ot.USER_REMOVED,ot.USER_KICKED_BY_CHANGE_PASSWORD,ot.USER_KICKED_BY_OTHER_DEVICE].includes(e.errorCode??-1)}startTerminalSessionCleanup(e){if(this.terminalSessionCleanupTask)return;Vs("Terminal session cleanup started",{errorCode:e.errorCode,errorMessage:e.errorMessage,reason:e.reason});const t=this.finishTerminalSessionCleanup().catch(e=>{Ks("Terminal session cleanup failed",e instanceof Error?e:new Error(String(e)))}).finally(()=>{this.terminalSessionCleanupTask===t&&(this.terminalSessionCleanupTask=null)});this.terminalSessionCleanupTask=t}async waitForTerminalSessionCleanup(){await(this.terminalSessionCleanupTask??Promise.resolve())}async finishTerminalSessionCleanup(){this.loginAttempt+=1,this.cancelPostLoginTasks(),await this.notifyManagersSessionEnding("terminal-disconnect");try{try{await(this.cacheManager?.flushPending())}catch(e){Vs("Cache flush on terminal disconnect failed",{error:e instanceof Error?e.message:String(e)})}if(this.logReportEnabled)try{await qs()}catch(e){Vs("Report logs on terminal disconnect failed",e)}}finally{const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(t),this.logReportEnabled=!1,Bs("disabled"),$s(),Lh()}finally{e?.()}}Vs("Terminal session cleanup finished")}static isSameConfig(t,r){return t.appKey===r.appKey&&(t.appId===r.appId&&(!!e.isSameStringArray(t.enableSyncData,r.enableSyncData)&&(t.useCustomAttachmentUpload===r.useCustomAttachmentUpload&&(t.enableMd5Check===r.enableMd5Check&&(!!e.isSameServiceConfig(t.serviceConfig,r.serviceConfig)&&(t.useFixedDeviceId===r.useFixedDeviceId&&(t.deviceId===r.deviceId&&(t.useReplacedMessageContents===r.useReplacedMessageContents&&(t.customDeviceName===r.customDeviceName&&(t.customOSPlatform===r.customOSPlatform&&(t.platformAdapterOptions?.prefer===r.platformAdapterOptions?.prefer&&(t.platformAdapterOptions?.runtimeInput===r.platformAdapterOptions?.runtimeInput&&(t.platformAdapterOptions?.transportAdapter===r.platformAdapterOptions?.transportAdapter&&(t.platformAdapterOptions?.overrides===r.platformAdapterOptions?.overrides&&(t.uiKitVersion===r.uiKitVersion&&(t.cacheEncryptionMode===r.cacheEncryptionMode&&(t.enableUserInfoSync===r.enableUserInfoSync&&(t.deleteConversationOnGroupDestroyed===r.deleteConversationOnGroupDestroyed&&(t.syncConversationListConfig.includeEmpty===r.syncConversationListConfig.includeEmpty&&(t.profileSync.userInfoWindowMs===r.profileSync.userInfoWindowMs&&t.profileSync.userInfoBatchSize===r.profileSync.userInfoBatchSize&&t.profileSync.groupNamecardWindowMs===r.profileSync.groupNamecardWindowMs&&t.profileSync.groupNamecardMaxConcurrency===r.profileSync.groupNamecardMaxConcurrency))))))))))))))))))))}static normalizeServiceConfig(t){const r=t?.serverUrls;return{mode:r?"fixed":"dns",dnsConfigUrls:t?.dnsConfigUrls??Yy,hasCustomDnsConfigUrls:Boolean(t?.dnsConfigUrls?.length),serverUrls:r?{restApiUrl:r.restApiUrl,wsUrl:r.wsUrl?e.normalizeFixedWebSocketUrl(r.wsUrl):void 0}:void 0}}static normalizeFixedWebSocketUrl(e){const t=e.search(/[?#]/),r=-1===t?e:e.slice(0,t),s=-1===t?"":e.slice(t),n=r.indexOf("://")+3,i=r.indexOf("/",n);if(-1===i)return`${r}/websocket${s}`;const o=r.slice(i);return/^\/+$/u.test(o)?`${r.slice(0,i)}/websocket${s}`:e}static normalizeSyncDataTypes(e){const t=[];for(const r of e)t.includes(r)||t.push(r);return t}static isSameStringArray(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}static isSameServiceConfig(t,r){if(t.mode!==r.mode)return!1;if(t.dnsConfigUrls.length!==r.dnsConfigUrls.length)return!1;for(let e=0;e<t.dnsConfigUrls.length;e+=1)if(t.dnsConfigUrls[e]!==r.dnsConfigUrls[e])return!1;return e.isSameServerUrls(t.serverUrls,r.serverUrls)}static isSameServerUrls(e,t){return!e&&!t||!(!e||!t)&&(e.restApiUrl===t.restApiUrl&&e.wsUrl===t.wsUrl)}};Kv.instance=null;let zv=Kv;const Hv=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),Wv=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw(e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}))(t);return e.trim()},Jv=e=>`mark_${String(e)}`,Qv=(e,t)=>{if("singleChat"===e||"groupChat"===e||"chatRoom"===e)return e;throw Hv(t,`${t} must be one of singleChat, groupChat, chatRoom`)},Zv=e=>"singleChat"===e?"chat":"groupChat"===e?"groupchat":"chatroom",Yv=e=>"string"==typeof e&&e.length>0?e:void 0,Xv=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}},eI=e=>pu(e)?e:void 0,tI=(e,t)=>{const r=eI(e);if(!r)return;const s=(e=>"string"==typeof e?mu(e,{}):eI(e)??{})(r.payload),n=Array.isArray(s.bodies)?s.bodies:[],i=eI(n[0])??eI(s.body),o=(e=>"txt"===e||"text"===e?"text":"custom"===e?"custom":"cmd"===e?"cmd":"image"===e||"file"===e||"voice"===e||"video"===e||"location"===e||"combine"===e?e:null)(i?.type??s.type);if(!i||!o)return;const a=((e,t)=>{if("text"===e)return{content:Yv(t.msg)??Yv(t.content)??""};if("custom"===e){const e=eI(t.customExts)??eI(t.params)??{},r={};for(const[t,s]of Object.entries(e))"string"==typeof s&&(r[t]=s);return{event:Yv(t.customEvent)??Yv(t.event)??"",params:r}}if("cmd"===e)return{action:Yv(t.action)??""};if("image"===e){const e=Yv(t.url)??Yv(t.remotePath)??"";return{localUrl:"",filename:Yv(t.filename)??Yv(t.displayName),filetype:Yv(t.filetype)??"application/octet-stream",width:Xv(t.width),height:Xv(t.height),isGif:!0===t.isGif||1===t.subType,isOriginalImage:!0===t.isOriginalImage,originalImageUrl:e,bigImageUrl:Yv(t.bigImageUrl),thumbnailUrl:Yv(t.thumbnailUrl)??Yv(t.thumbnailRemotePath),secret:Yv(t.secret)??Yv(t.secretKey),fileLength:Xv(t.fileLength)}}return"file"===e?{url:Yv(t.url)??Yv(t.remotePath),filename:Yv(t.filename)??Yv(t.displayName),filetype:Yv(t.filetype)??"application/octet-stream",fileSize:Xv(t.fileSize),fileLength:Xv(t.fileLength),secret:Yv(t.secret)??Yv(t.secretKey)}:"voice"===e?{url:Yv(t.url)??Yv(t.remotePath),filename:Yv(t.filename)??Yv(t.displayName),filetype:Yv(t.filetype)??"application/octet-stream",duration:Xv(t.duration)??0,fileLength:Xv(t.fileLength),secret:Yv(t.secret)??Yv(t.secretKey)}:"video"===e?{url:Yv(t.url)??Yv(t.remotePath),filename:Yv(t.filename)??Yv(t.displayName),filetype:Yv(t.filetype)??"application/octet-stream",duration:Xv(t.duration)??0,width:Xv(t.width),height:Xv(t.height),fileLength:Xv(t.fileLength),secret:Yv(t.secret)??Yv(t.secretKey),thumbnailUrl:Yv(t.thumbnailUrl)??Yv(t.thumbnailRemotePath)}:"location"===e?{latitude:Xv(t.latitude)??0,longitude:Xv(t.longitude)??0,address:Yv(t.address),buildingName:Yv(t.buildingName)}:null})(o,i);if(!a)return;const c=Yv(s.from)??Yv(r.from)??"",d=Yv(s.to)??t.conversationId,u=eI(s.sender),l={userId:Yv(u?.userId)??c,nickname:Yv(u?.nickname),avatarUrl:Yv(u?.avatarUrl)},h=eI(s.ext)??{},p=(e=>{const t=eI(e);if(!t)return;const r=Yv(t.operatorId)??Yv(t.operator),s=Xv(t.operationCount)??Xv(t.count),n=Xv(t.operationTime)??Xv(t.edit_time);return r&&void 0!==s&&void 0!==n?{operatorId:r,operationCount:s,operationTime:n}:void 0})(s.modifiedInfo??eI(s.meta)?.edit_msg);return{msgServerId:Yv(r.id)??t.messageId,msgLocalId:Yv(r.msgLocalId)??"",from:c,to:d,sender:l,conversationId:t.conversationId,conversationType:t.conversationType,type:o,sendStatus:"sent",ext:h,timestamp:Xv(r.timestamp)??t.timestamp,body:a,direct:c===t.currentUserId?"SEND":"RECEIVE",...p?{modifiedInfo:p}:{}}},rI=e=>`${e.conversationType}:${e.conversationId}`,sI=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},nI=async(e,t,r,s)=>{const n=sI(t),i=(e=>{const t=e,r=t.conversations;if(void 0!==r){if(!Array.isArray(r)||0===r.length)throw Hv("params.conversations","params.conversations must be a non-empty array");return r.map((e,t)=>{if(!pu(e))throw Hv(`params.conversations.${String(t)}`,`params.conversations.${String(t)} must be an object`);return{conversationId:Wv(e.conversationId,`params.conversations.${String(t)}.conversationId`),conversationType:Qv(e.conversationType,`params.conversations.${String(t)}.conversationType`)}})}return[{conversationId:Wv(t.conversationId,"params.conversationId"),conversationType:Qv(t.conversationType,"params.conversationType")}]})(r),o=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0||e>19)throw Hv(t,`${t} must be an integer between 0 and 19`);return e})(r.mark,"params.mark"),a=await e.request(`/${n.orgName}/${n.appName}/sdk/user/${n.encodedUserId}/user_channels/mark?resource=${n.encodedResource}`,{method:s?"POST":"DELETE",body:{mark:Jv(o),targets:i.map(e=>({to:e.conversationId,type:Zv(e.conversationType)}))},operation:s?"addConversationMark":"removeConversationMark"}),c=(e=>{if(!Array.isArray(e))return new Set;const t=new Set;return e.forEach(e=>{if(!pu(e))return;const r="string"==typeof e.to?e.to.trim():"",s=(e=>"chat"===e||"singleChat"===e?"singleChat":"groupchat"===e||"groupChat"===e?"groupChat":"chatroom"===e||"chatRoom"===e?"chatRoom":null)(e.type);r&&s&&t.add(rI({conversationId:r,conversationType:s}))}),t})((pu(a)&&pu(a.data)?a.data:{}).ignore),d=[],u=[];for(const l of i){const e={conversationId:l.conversationId,conversationType:l.conversationType};c.has(rI(l))?u.push({...e,reason:"ignored_by_server"}):d.push(e)}return{succeeded:d,failed:u,mark:o,operation:s?"addMark":"removeMark"}},iI=async(e,t,r,s)=>{const n=sI(t),i=Wv(r.conversationId,"params.conversationId"),o=Qv(r.conversationType,"params.conversationType"),a=Wv(r.messageId,"params.messageId");return await e.request(`/${n.orgName}/${n.appName}/sdk/user/${n.encodedUserId}/user_channel/pin?resource=${n.encodedResource}`,{method:s?"POST":"DELETE",body:{to:i,type:Zv(o),pin_msg_id:a},operation:s?"pinMessage":"unpinMessage"}),{conversationId:i,conversationType:o,messageId:a,operation:s?"pin":"unpin"}},oI=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],aI=(e,t)=>`${e}\0${t}`,cI=(e,t,r)=>{const s={userId:e};for(const n of oI){const e=r?.[n]??t?.[n];void 0!==e&&(s[n]=e)}return s},dI=e=>cI(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),uI=(e,t,r)=>{const s=new Map;if(!e?.getGroupNamecard||!r)return s;for(const n of t){const t=e.getGroupNamecard(n.groupId,n.user.userId,!1);t&&s.set(aI(n.groupId,n.user.userId),t.namecard)}return s},lI=async(e,t)=>{if(0===e.length||!t)return[];try{return await t({userIds:e})}catch(r){return Vs("Group user info hydration failed",{userIds:e,error:r}),[]}},hI=async(e,t)=>{t&&0!==e.size&&await Promise.all([...e.entries()].map(async([e,r])=>{try{await t(e,r)}catch(s){Vs("Group namecard hydration failed",{groupId:e,userIds:r,error:s})}}))},pI=async e=>{const t=(e=>{const t=[],r=new Set;for(const s of e){const e=s.groupId.trim(),n=s.user.userId.trim();if(!e||!n)continue;const i=aI(e,n);r.has(i)||(r.add(i),t.push({groupId:e,user:{...s.user,userId:n}}))}return t})(e.contexts),r=(e=>{const t=[],r=new Set;for(const s of e)r.has(s.user.userId)||(r.add(s.user.userId),t.push(s.user.userId));return t})(t),s=((e,t)=>{const r=new Map;if(!e)return r;for(const n of t){const t=e.getRuntimeUserInfo?.(n,!1)??null;t&&r.set(n,t)}const s=t.filter(e=>!r.has(e));for(const n of e.getUserInfoSummaries?.(s,!1)??[])r.set(n.userId,dI(n));return r})(e.cacheManager,r),n=r.filter(e=>!s.has(e)),i=new Set(n),o=uI(e.cacheManager,t,e.includeNameCard),a=e.includeNameCard?((e,t,r)=>{const s=new Map;for(const n of e){const e=n.user.userId,i=aI(n.groupId,e);if(!t.has(e)||r.has(i))continue;const o=s.get(n.groupId)??[];o.includes(e)||o.push(e),s.set(n.groupId,o)}return s})(t,i,o):new Map,[c]=await Promise.all([lI(n,e.fetchUserInfos),hI(a,e.hydrateGroupNamecards)]),d=new Map(c.map(e=>[e.userId,e])),u=uI(e.cacheManager,t,e.includeNameCard),l=new Map;for(const h of t){const e=h.user.userId,t=aI(h.groupId,e),r=cI(e,h.user,d.get(e)??s.get(e)),n=u.get(t)??o.get(t);l.set(t,void 0!==n?{...r,nameCard:n}:r)}return{usersByContextKey:l,fetchedUserInfos:c,missingUserIds:n.filter(e=>!d.has(e))}},mI=async e=>{const t=await pI({...e,contexts:e.users.map(t=>({groupId:e.groupId,user:t}))}),r=new Map;for(const s of e.users){const n=s.userId.trim();if(!n||r.has(n))continue;const i=t.usersByContextKey.get(aI(e.groupId.trim(),n));i&&r.set(n,i)}return{usersById:r,fetchedUserInfos:t.fetchedUserInfos,missingUserIds:t.missingUserIds}},fI=xy(["singleChat","groupChat","chatRoom"]),gI=Py(My()).refine(e=>(e=>"object"==typeof e&&null!==e&&!Array.isArray(e))(e),"ext must be an object").refine(e=>(e=>{try{return JSON.stringify(e),!0}catch{return!1}})(e),"ext must be JSON serializable"),yI=ky({path:Ay().min(1,"data.path is required"),size:Ny().optional(),name:Ay().optional(),type:Ay().optional()}),vI=ky({uri:Ay().min(1,"data.uri is required"),size:Ny().optional(),name:Ay().optional(),type:Ay().optional()}),II=Dy(["undefined"!=typeof File?((e,t={message:`Input not instance of ${e.name}`})=>Ey(t=>t instanceof e,t))(File):Uy(),yI,vI]),bI=ky({conversationId:Ay().min(1,"conversationId is required"),conversationType:fI,ext:gI.optional(),timestamp:Ny().int().positive("timestamp must be a positive integer").optional(),receiverList:Ly(Ay().min(1,"receiverList item is required")).nonempty("receiverList must not be empty").optional(),deliverOnlineOnly:Oy().optional(),webhookEnv:Ay().optional(),priority:xy(["high","normal","low"]).optional(),needReadReceipt:Oy().optional(),isChatThread:Oy().optional()}),_I=ky({type:Ay().min(1,"messageList.type is required"),sender:ky({userId:Ay().min(1,"messageList.sender.userId is required"),nickname:Ay().optional(),avatarUrl:Ay().optional()}),conversationId:Ay().min(1,"messageList.conversationId is required"),conversationType:fI,timestamp:Ny().int().positive("messageList.timestamp must be positive"),body:Py(My()),combineLevel:Ny().int().min(0).max(10).optional()}).passthrough(),TI=e=>e.superRefine((e,t)=>{e.receiverList&&"singleChat"===e.conversationType&&t.addIssue({code:Zf.custom,message:"receiverList is only allowed for group or chat room conversation",path:["receiverList"]}),e.isChatThread&&"groupChat"!==e.conversationType&&t.addIssue({code:Zf.custom,message:"isChatThread is only allowed for group conversation",path:["isChatThread"]}),e.needReadReceipt&&"chatRoom"===e.conversationType&&t.addIssue({code:Zf.custom,message:"needReadReceipt is not allowed for chatRoom conversation",path:["needReadReceipt"]})}),CI=TI(bI.extend({content:Ay().min(1,"content is required"),targetLanguages:Ly(Ay().min(1)).optional()})),SI=TI(bI.extend({originalUrl:Ay().min(1,"originalUrl is required").optional(),filename:Ay().min(1,"filename is required").optional(),filetype:Ay().min(1,"filetype is required").optional(),width:Ny().positive("width must be positive").optional(),height:Ny().positive("height must be positive").optional(),isGif:Oy().optional(),isOriginalImage:Oy().optional(),fileLength:Ny().positive("fileLength must be positive").optional(),data:II.optional(),thumbnailUrl:Ay().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),EI=TI(bI.extend({originalUrl:Ay().min(1,"originalUrl is required").optional(),filename:Ay().min(1,"filename is required").optional(),filetype:Ay().min(1,"filetype is required").optional(),fileSize:Ny().positive("fileSize must be positive").optional(),fileLength:Ny().positive("fileLength must be positive").optional(),data:II.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),wI=TI(bI.extend({originalUrl:Ay().min(1,"originalUrl is required").optional(),filename:Ay().min(1,"filename is required").optional(),filetype:Ay().min(1,"filetype is required").optional(),duration:Ny().positive("duration must be positive"),fileLength:Ny().positive("fileLength must be positive").optional(),data:II.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),RI=TI(bI.extend({originalUrl:Ay().min(1,"originalUrl is required").optional(),filename:Ay().min(1,"filename is required").optional(),filetype:Ay().min(1,"filetype is required").optional(),duration:Ny().positive("duration must be positive"),width:Ny().positive("width must be positive").optional(),height:Ny().positive("height must be positive").optional(),fileLength:Ny().positive("fileLength must be positive").optional(),thumbnailUrl:Ay().min(1).optional(),data:II.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),AI=TI(bI.extend({latitude:Ny(),longitude:Ny(),address:Ay().min(1).optional(),buildingName:Ay().min(1).optional()})),NI=TI(bI.extend({action:Ay().min(1,"action is required")})),OI=TI(bI.extend({event:Ay().min(1,"event is required"),params:Py(Ay()).optional()})),MI=TI(bI.extend({title:Ay().min(1,"title is required"),summary:Ay().min(1,"summary is required"),compatibleText:Ay().min(1).optional(),messageList:Ly(_I).min(1,"messageList must not be empty").max(300,"messageList max length is 300")})),UI=e=>{const t=e?.userId?.trim();if(!t)throw new mt("sender.userId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});return{userId:t,nickname:e?.nickname,avatarUrl:e?.avatarUrl}},LI=()=>Bh(),kI=(e,t)=>{if(e)return e;if(!t)throw new mt("url or data is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"url",message:"url or data is required",rule:"required"}]}});const r=Fh(t);if(!r)throw new mt("Failed to resolve local url",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"url",message:"Failed to resolve local url",rule:"invalid_format"}]}});return r},DI=e=>!!e.isGif||(e.isOriginalImage??!1),PI=(e,t,r,s,n)=>({msgServerId:"",msgLocalId:n??Bh(),from:t.userId,to:e.conversationId,sender:t,conversationId:e.conversationId,conversationType:e.conversationType,type:r,sendStatus:"sending",ext:e.ext??{},timestamp:e.timestamp??Date.now(),body:s,direct:"SEND",isOnline:!0,receiverList:e.receiverList,deliverOnlineOnly:e.deliverOnlineOnly,webhookEnv:e.webhookEnv,priority:e.priority,needReadReceipt:e.needReadReceipt,isPeerRead:"singleChat"!==e.conversationType&&void 0,isChatThread:e.isChatThread}),xI=(e,t)=>{const r=Fy.validateOrThrow(MI,e),s=r.messageList,n=UI(t);np(s);const i=ip(s);op(i);const o={title:r.title,summary:r.summary,messageList:s,filename:"combine",filetype:"application/octet-stream",combineLevel:i},a=PI(r,n,"combine",o);return((e,t)=>{t&&Yu.set(e,t)})(a,r.compatibleText),a},FI=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}`},BI=e=>{const t=new Uint8Array(fa.util.base64.length(e));return fa.util.base64.decode(e,t,0),t},GI=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),qI=async e=>{try{return await e()}catch(t){if(!(t instanceof It))throw t;const e=(e=>{const t="string"==typeof e.details?.serverMessage?e.details.serverMessage:void 0;switch(e.code){case ot.SERVICE_NOT_ENABLED:case ot.TRANSLATE_SERVICE_NOT_ENABLED:return"Translation service is not enabled";case ot.TRANSLATE_PARAM_INVALID:return t?.includes("too long")?"Translation text is too long":t?.includes("target language")?"Invalid target language":"Invalid translation request";case ot.TRANSLATE_USAGE_LIMIT:return"Translation quota has been reached";case ot.TRANSLATE_FAILED:return"Translation service error";default:return}})(t);if(!e)throw t;throw new It(`REST business error: ${e}`,{code:t.code,details:t.details})}},$I=e=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):"",jI=e=>{if("string"!=typeof e)return"";const t=e.trim();return t&&"undefined"!==t&&"null"!==t?t:""},VI=e=>({userId:e}),KI=(e,t)=>{if(!GI(e)||!GI(e.data))throw qf({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},zI=(e,t)=>{if(!GI(e)||!Array.isArray(e.data))throw qf({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},HI=(e,t)=>Array.isArray(e)?e:zI(e,t),WI={txt:"text",img:"image",video:"video",file:"file",loc:"location",custom:"custom",combine:"combine"},JI={text:"txt",image:"img",video:"video",file:"file",location:"loc",custom:"custom",combine:"combine"},QI={chat:"singleChat",chatroom:"chatRoom",groupchat:"groupChat",singleChat:"singleChat",chatRoom:"chatRoom",groupChat:"groupChat"},ZI=(e,t,r)=>{if(!t)return"";if(t.includes("em-redirect"))return t;const{orgName:s,appName:n}=fs(e.appKey),i=t.indexOf("/chatfiles/"),o=i>=0?t.slice(i):t,a=`${e.restBaseUrl}/${s}/${n}${o}`;return bs(a,r)},YI=e=>{if(!e||"object"!=typeof e)return;if(Array.isArray(e))return e;const t=Object.values(e),r=[];for(const s of t)Array.isArray(s)&&r.push(...s);return r.length>0?r:void 0},XI=(e,t,r)=>{const s=$I(r.contentType??r.type),n=JI[s];if(!n)return null;const i=GI(r.content)?r.content:{},o=((e,t)=>{const r=$I(t.conversationType);if("groupchat"===r||"chatroom"===r)return $I(t.receiverId);const s=$I(t.senderId);return s===e?$I(t.receiverId):s})(t,r),a=QI[$I(r.conversationType)]??"singleChat",c={msgServerId:$I(r.messageId),msgLocalId:$I(r.messageId),from:$I(r.senderId),to:$I(r.receiverId),conversationId:o,conversationType:a,type:n,ext:GI(r.ext)?r.ext:{},timestamp:"number"==typeof r.sentTime?r.sentTime:new Date($I(r.sentTime)).getTime(),sender:{userId:$I(r.senderId)},highlight:YI(r.highlight),text:"string"==typeof r.text?r.text:void 0};let d;const u=$I(i.remotePath??i.url),l=$I(i.secret??i.secretKey);switch(n){case"txt":d={type:"txt",content:$I(i.message??r.text)};break;case"img":{const t=ZI(e,u,l);d={type:"img",url:t,thumb:i.thumb?ZI(e,$I(i.thumb),$I(i.thumb_secret??i.thumbnailSecretKey)):`${t}&thumbnail=true`,secret:l,width:Number(i.width??(GI(i.size)?i.size.width:0))||0,height:Number(i.height??(GI(i.size)?i.size.height:0))||0,fileLength:Number(i.file_length??i.fileLength??0)};break}case"video":d={type:"video",url:ZI(e,u,l),thumb:i.thumb||i.thumbnailRemotePath?ZI(e,$I(i.thumb??i.thumbnailRemotePath),$I(i.thumb_secret??i.thumbnailSecretKey)):"",secret:l,filename:$I(i.filename??i.displayName),duration:Number(i.length??i.duration??0),fileLength:Number(i.file_length??i.fileLength??0)};break;case"file":d={type:"file",url:ZI(e,u,l),secret:l,filename:$I(i.filename??i.displayName),fileLength:Number(i.file_length??i.fileLength??0)};break;case"loc":d={type:"loc",latitude:Number(i.lat??i.latitude??0),longitude:Number(i.lng??i.longitude??0),address:$I(i.addr??i.address),buildingName:$I(i.buildingName)};break;case"custom":d={type:"custom",customEvent:$I(i.customEvent),customExts:GI(i.customExts)?i.customExts:{}};break;default:return null}return{...c,body:d}},eb=async(e,t,r)=>{const s=`${FI(t)}/users/${t.userId}/messages/search/get`,n=((e,t)=>{const{option:r,pageNum:s=1,pageSize:n=20}=e,i=r.keywordList.map(e=>e.trim()).filter(e=>e.length>0),o={searchMode:"default",highlightEnable:!0,page:s,size:n};return 1===i.length?o.keyword=i[0]:(o.keywords=i,o.keywordMatch="and"===r.keywordListMatchType?"all":"any"),r.conversationId&&("singleChat"===r.conversationType?o.participantPairs=[{userId1:t,userId2:r.conversationId}]:"groupChat"===r.conversationType?o.groupIds=[r.conversationId]:"chatRoom"===r.conversationType&&(o.chatroomIds=[r.conversationId])),r.msgTypes&&r.msgTypes.length>0&&(o.contentType=r.msgTypes.map(e=>WI[e]??e).join(",")),void 0!==r.startTime&&(o.startTime=r.startTime),void 0!==r.endTime&&(o.endTime=r.endTime),r.searchScope&&(o.searchExt=r.searchScope),r.direction&&(o.sort="up"===r.direction?"sentTime:asc":"sentTime:desc"),{data:o}})(r,t.userId),i=await e.post(s,n,{operation:"searchMessages"}),o=GI(i)?i:{},a=GI(o.data)?o.data:o,c=GI(a.data)?a.data:a,d=Array.isArray(c.items)?c.items:Array.isArray(c.list)?c.list:[],u=GI(c.pagination)?c.pagination:c,l=Number(u.pageNum??u.page??r.pageNum??1),h=Number(u.pageSize??u.size??r.pageSize??20),p=Number(u.totalPages??0),m=1===u.isFinished||l>=p,f=[];for(const g of d){if(!GI(g))continue;const e=XI(t,t.userId,g);e&&f.push(e)}return{messages:f,pageNum:l,pageSize:h,totalPages:p,isLast:m}},tb=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/api/sdk/v1/${t}/${r}`},rb=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),sb=e=>rb(e)&&"string"==typeof e.path&&e.path.trim().length>0,nb=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||sb(e),ib=e=>{if(!rb(e))return;return{data:rb(e.data)?e.data:void 0,error:rb(e.error)?e.error:void 0}},ob=(e,t)=>{const r=ib(e),s=r?.data?.text;if("string"!=typeof s)throw new ut(`${t} response data is invalid`,ot.REST_BUSINESS_UNKNOWN,{details:{api:t,response:e}});return s},ab=(e,t,r,s="sdk")=>"auth"===s?new pt(e,{code:t,details:r}):"validation"===s?new mt(e,{code:t,details:r}):new ut(e,t,{details:r}),cb=e=>!(void 0===e||rb(e)&&!Array.isArray(e))||(void 0!==e?.format&&"string"!=typeof e.format||(void 0!==e?.sampleRate&&"number"!=typeof e.sampleRate||(void 0!==e?.bitsPerSample&&"number"!=typeof e.bitsPerSample||void 0!==e?.channels&&"number"!=typeof e.channels))),db=e=>{if(!e)return;const t=(e.split("#")[0]?.split("?")[0]??"").split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0},ub=e=>{const{serviceCode:t,serviceMessage:r}=(e=>{const t=e instanceof ut&&rb(e.details)?e.details:void 0,r=ib(t?.rawResponse??t?.response??e),s=t?.serverCode??r?.error?.code,n=t?.serverMessage??r?.error?.message;return{serviceCode:"string"==typeof s||"number"==typeof s?String(s):void 0,serviceMessage:"string"==typeof n?n:void 0}})(e);if(e instanceof bt)return ab("File upload failed",ot.UPLOAD_REQUEST_FAILED,{cause:e.details});if(e instanceof ut&&!t)return e;if(t)switch(t){case"4041001":return ab("File not found",ot.VOICE_TO_TEXT_FILE_NOT_FOUND,{serviceCode:t,serviceMessage:r});case"4001002":return ab("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{serviceCode:t,serviceMessage:r},"validation");case"5021001":return ab("File upload failed",ot.UPLOAD_REQUEST_FAILED,{serviceCode:t,serviceMessage:r});case"4001003":return ab("Voice duration exceeds 60 seconds",ot.VOICE_TO_TEXT_FILE_DURATION_TOO_LONG,{serviceCode:t,serviceMessage:r},"validation");case"4031001":return ab("Voice-to-text service is not enabled",ot.SERVICE_NOT_ENABLED,{serviceCode:t,serviceMessage:r});case"4031002":return ab("Beta service usage limit exceeded",ot.SERVICE_LIMIT_EXCEEDED,{serviceCode:t,serviceMessage:r});case"4001001":return(e=>"string"==typeof e&&e.toLowerCase().includes("uploaded file exceeds"))(r)?ab("File too large",ot.VOICE_TO_TEXT_FILE_TOO_LARGE,{serviceCode:t,serviceMessage:r}):ab(r||"Missing or invalid request parameter",ot.VALIDATION_REQUIRED,{serviceCode:t,serviceMessage:r},"validation");case"5021003":case"5001003":return ab("Voice-to-text failed",ot.VOICE_TO_TEXT_FAILED,{serviceCode:t,serviceMessage:r});case"4011001":return ab(r||"Unauthorized or invalid token",ot.AUTH_UNAUTHORIZED,{serviceCode:t,serviceMessage:r},"auth");default:return ab(r||(e instanceof Error?e.message:"Voice-to-text failed"),ot.VOICE_TO_TEXT_FAILED,{serviceCode:t,serviceMessage:r})}return e instanceof ut?ab(e.message,e.code,e.details):ab(e instanceof Error?e.message:"Voice-to-text failed",ot.VOICE_TO_TEXT_FAILED)},lb=(e,t)=>{if(!rb(r=e)||"string"!=typeof r.filename||"string"!=typeof r.filetype||"number"!=typeof r.duration||"type"in r&&void 0!==r.type&&"voice"!==r.type)throw ab("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody"},"validation");var r;if(cb(t))throw ab("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!e.url)throw ab("File not found",ot.VOICE_TO_TEXT_FILE_NOT_FOUND,{path:"voiceMessageBody.url"});if(!db(e.url))throw ab("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody.url"},"validation");return e},hb=(e,t)=>{if(cb(t))throw ab("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!nb(e))throw ab("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"file"},"validation");return e},pb=async(e,t,r,s)=>{const n=lb(r,s),i=db(n.url);if(!i)throw((e,t,r,s="invalid")=>new mt(e,{code:t,details:{fields:[{path:r,message:e,rule:s}]}}))("File not found",ot.VOICE_TO_TEXT_FILE_NOT_FOUND,"voiceMessageBody.url");try{const r=await e.post(`${tb(t)}/speech/transcriptions`,{data:{fileId:i,username:t.userId,...s?{audio:s}:{}}},{operation:"voiceMessageToText"});return{text:ob(r,"voiceMessageToText")}}catch(o){throw ub(o)}},mb=ky({keywordList:Ly(Ay()).min(1,"keywordList must not be empty").max(5,"keywordList must have at most 5 keywords").refine(e=>e.map(e=>e.trim()).filter(e=>e.length>0).length>0,"keywordList must contain at least one non-empty keyword"),keywordListMatchType:xy(["or","and"]).optional(),conversationId:Ay().min(1).optional(),conversationType:xy(["singleChat","groupChat","chatRoom"]).optional(),msgTypes:Ly(xy(["txt","img","video","file","loc","custom","combine"])).optional(),startTime:Ny().optional(),endTime:Ny().optional(),searchScope:xy(["none","with","only"]).optional(),direction:xy(["up","down"]).optional()}).refine(e=>void 0!==e.conversationId===(void 0!==e.conversationType),{message:"conversationId and conversationType must be provided together"}).refine(e=>void 0!==e.startTime===(void 0!==e.endTime),{message:"startTime and endTime must be provided together"}).refine(e=>void 0===e.startTime||void 0===e.endTime||e.endTime>=e.startTime,{message:"endTime must be >= startTime"}),fb=ky({option:mb,pageNum:Ny().int().min(1).default(1),pageSize:Ny().int().min(1).max(100).default(20)}),gb=bv(_v,{common:{},apis:{sendMessage:{range:"1,4,100,108,110,202,210,213-215,219-222,300-301,303,305,402,405-406,500-501,505-510,602-603,606-607,1200,1299",localErrors:{sendMessage:{operation_cancelled:{code:1,retryable:!1},upload_invalid_appkey:{code:100,retryable:!1},validation_invalid:{code:110,retryable:!1},not_connected:{code:300,retryable:!0},request_timeout:{code:301,retryable:!0},send_failed:{code:303,retryable:!1},upload_failed:{code:402,retryable:!0},file_too_large:{code:405,retryable:!1},file_content_improper:{code:406,retryable:!1},encode_failed:{code:500,retryable:!1}}},errors:{SERVICE_LIMIT_EXCEEDED:{code:4,retryable:!1},TOKEN_EXPIRED:{code:108,retryable:!1},AUTH_FAILED:{code:202,retryable:!1},PERMISSION_DENIED:{code:210,retryable:!1},BIND_ANOTHER_DEVICE:{code:213,retryable:!1},TOO_MANY_DEVICES:{code:214,retryable:!1},USER_MUTED:{code:215,retryable:!1},USER_MUTED_BY_ADMIN:{code:219,retryable:!1},USER_DEVICE_CHANGED:{code:220,retryable:!1},USER_NOT_ON_ROSTER:{code:221,retryable:!1},BLOCKED_BY_RECIPIENT:{code:222,retryable:!1,aliases:["blocked"]},SERVER_SERVING_DISABLED:{code:305,retryable:!1},MESSAGE_INCLUDE_ILLEGAL_CONTENT:{code:501,retryable:!1},SERVICE_NOT_ENABLED:{code:505,retryable:!1},MESSAGE_EXPIRED:{code:506,retryable:!1},MESSAGE_ILLEGAL_WHITELIST:{code:507,retryable:!1},MESSAGE_EXTERNAL_LOGIC_BLOCKED:{code:508,retryable:!1},MESSAGE_CURRENT_LIMITING:{code:509,retryable:!0},MESSAGE_SIZE_LIMIT:{code:510,retryable:!1},GROUP_NOT_JOINED:{code:602,retryable:!1},GROUP_PERMISSION_DENIED:{code:603,retryable:!1},GROUP_NOT_EXIST:{code:606,retryable:!1},GROUP_DISABLED:{code:607,retryable:!1},MESSAGE_BLOCKED:{code:1200,retryable:!1},THIRD_DEFAULT_FAILED:{code:1299,retryable:!1}}},getHistoryMessages:{range:"4,110,202,505",localErrors:{getHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},page_size_exceeded:{code:110,aliases:["pull number cannot be greater","limit is to large"],retryable:!1}}},removeHistoryMessages:{range:"110,112,202,505",localErrors:{removeHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},query_param_reaches_limit:{code:112,aliases:["delete msg list limit"],retryable:!1}}},getGroupMessageReadUsers:{range:"4,110,500",localErrors:{getGroupMessageReadUsers:{validation_invalid:{code:110,retryable:!1}}},errors:{message_not_found:{code:500,retryable:!1}}},recallMessage:{range:"110,201,300,504,505",localErrors:{recallMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},recall_time_limit:{code:504,retryable:!1},recall_disabled:{code:505,retryable:!1}}},updateMessage:{range:"110,111,201,210,300,511",localErrors:{modifyMessage:{validation_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1},not_login:{code:201,retryable:!0},permission_denied:{code:210,retryable:!1},not_connected:{code:300,retryable:!0},edit_failed:{code:511,retryable:!0}}},downloadMessageAttachment:{range:"400,401,403,407",localErrors:{downloadAttachment:{validation_invalid:{code:401,retryable:!1}}},errors:{not_found:{code:400,httpStatus:404,retryable:!1},invalid:{code:401,retryable:!1},download_failed:{code:403,retryable:!0},expired:{code:407,httpStatus:404,retryable:!1}}},downloadAndParseCombineMessage:{range:"110,401,403,500",localErrors:{downloadAndParseCombineMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_param:{code:110,retryable:!1},invalid_type:{code:500,retryable:!1},parse_failed:{code:401,retryable:!0},download_failed:{code:403,retryable:!0}}},addReaction:{range:"110,302,505,600,602,1300-1302",localErrors:{addReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{reaction_already_operated:{code:1301,retryable:!1},reaction_reach_limit:{code:1300,retryable:!1},group_not_joined:{code:602,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1},service_not_enabled:{code:505,retryable:!1},server_busy:{code:302,retryable:!0}}},removeReaction:{range:"110,505,1301,1302",localErrors:{removeReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},getReactionList:{range:"110,505,600",localErrors:{getReactionList:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},group_invalid_id:{code:600,retryable:!1}}},getReactionDetail:{range:"110,505,1302",localErrors:{getReactionDetail:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},pinMessage:{range:"4,110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_limit:{code:4,aliases:["91101"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102"],retryable:!1}}},unpinMessage:{range:"110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getPinnedMessageList:{range:"110,111",errors:{operation_unsupported:{code:111,aliases:["15002"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getSupportedTranslationLanguages:{range:"505",errors:{service_not_enabled:{code:505,aliases:["service not open!"],retryable:!1}}},translateMessage:{range:"505,1110-1113",localErrors:{translateMessage:{validation_invalid:{code:1110,retryable:!1}}},errors:{translate_text_too_long:{code:1110,runtimeMessage:"Translation text is too long",retryable:!1},translate_param_invalid:{code:1110,runtimeMessage:"Invalid target language",retryable:!1},service_not_enabled:{code:1111,runtimeMessage:"Translation service is not enabled",aliases:["service not open!"],retryable:!1},translate_usage_limit:{code:1112,runtimeMessage:"Translation quota has been reached",aliases:["The request has reached the maximum limit"],retryable:!1},translate_failed:{code:1113,runtimeMessage:"Translation service error",aliases:["The request failed, please try again later."],retryable:!1}}},voiceMessageToText:{range:"4,110,202,407-411,505",localErrors:{voiceMessageToText:{validation_invalid:{code:407,retryable:!1},file_not_found:{code:410,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},file_not_found:{code:410,retryable:!1,aliases:["4041001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},voiceFileToText:{range:"4,110,202,402,407-411,505",localErrors:{voiceFileToText:{validation_invalid:{code:407,retryable:!1},upload_required:{code:110,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},upload_failed:{code:402,retryable:!0,aliases:["5021001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},getConversationList:{range:"110",localErrors:{getConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPinnedConversationList:{range:"110",localErrors:{getPinnedConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getConversationListByMark:{range:"110",localErrors:{getConversationListByMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},deleteConversation:{range:"110",localErrors:{deleteConversation:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearConversationUnreadMessageCount:{range:"110,201,300,500",localErrors:{clearConversationUnreadMessageCount:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},clearAllConversationUnreadMessageCount:{range:"201,300,500",errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},sendMessageReadReceipts:{range:"110,300",localErrors:{sendMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_direction:{code:110,retryable:!1},not_connected:{code:300,retryable:!0}}},getGroupMessageReadReceipts:{range:"110,202,210,303",localErrors:{getGroupMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},auth_bad_access_token:{code:202,httpStatus:401,retryable:!1},forbidden_op:{code:210,httpStatus:403,retryable:!1},unknown_exception_error:{code:303,httpStatus:500,retryable:!0}}},setConversationPinned:{range:"110",localErrors:{setConversationPinned:{validation_invalid:{code:110,retryable:!1}}},errors:{}},addConversationMark:{range:"110",localErrors:{addConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},removeConversationMark:{range:"110",localErrors:{removeConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearAllMessagesAndConversations:{range:"",errors:{}},searchMessages:{range:"110,202,303,505",localErrors:{searchMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{parameter_error:{code:110,httpStatus:400,retryable:!1,aliases:["4000005","4000006"]},token_invalid:{code:202,httpStatus:401,retryable:!1,aliases:["4010101"]},service_not_enabled:{code:505,httpStatus:403,retryable:!1,aliases:["4030204"]},app_not_found:{code:110,httpStatus:404,retryable:!1,aliases:["4040302"]},server_error:{code:303,httpStatus:500,retryable:!0,aliases:["5000701","5020801"]}}}}}),yb=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}async sendMessage(e,t){return this.getClientOrThrow().sendMessage(e,t)}createTextMessage(e){return((e,t)=>{const r=Fy.validateOrThrow(CI,e),s=UI(t),n=LI(),i={content:r.content};return r.targetLanguages&&(i.targetLanguages=r.targetLanguages),PI(r,s,"text",i,n)})(e,this.buildMessageSenderOrThrow())}createImageMessage(e){return((e,t,r)=>{const s=Fy.validateOrThrow(SI,e),n=UI(t),i=LI(),o=s.data?kI(void 0,s.data):"",a=s.originalUrl?Ts(s.originalUrl,{deriveVariants:!r?.useCustomAttachmentUpload}):void 0;s.data&&xh.set(i,s.data);const c=s.isGif??!1,d={localUrl:o,filename:s.filename,filetype:s.filetype,width:s.width,height:s.height,isGif:c,isOriginalImage:DI({isGif:c,isOriginalImage:s.isOriginalImage})};return a?.originalImageUrl&&(d.originalImageUrl=a.originalImageUrl,d.bigImageUrl=a.bigImageUrl,d.thumbnailUrl=a.thumbnailUrl),void 0!==s.fileLength&&(d.fileLength=s.fileLength),s.thumbnailUrl&&(d.thumbnailUrl=s.thumbnailUrl),PI(s,n,"image",d,i)})(e,this.buildMessageSenderOrThrow(),this.getClientOrThrow().getMessageCreationOptions())}createFileMessage(e){return((e,t)=>{const r=Fy.validateOrThrow(EI,e),s=UI(t),n=LI(),i=kI(r.originalUrl,r.data);r.data&&xh.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype};return void 0!==r.fileSize&&(o.fileSize=r.fileSize),void 0!==r.fileLength&&(o.fileLength=r.fileLength),PI(r,s,"file",o,n)})(e,this.buildMessageSenderOrThrow())}createVoiceMessage(e){return((e,t)=>{const r=Fy.validateOrThrow(wI,e),s=UI(t),n=LI(),i=kI(r.originalUrl,r.data);r.data&&xh.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.fileLength&&(o.fileLength=r.fileLength),PI(r,s,"voice",o,n)})(e,this.buildMessageSenderOrThrow())}createVideoMessage(e){return((e,t)=>{const r=Fy.validateOrThrow(RI,e),s=UI(t),n=LI(),i=kI(r.originalUrl,r.data);r.data&&xh.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.width&&(o.width=r.width),void 0!==r.height&&(o.height=r.height),void 0!==r.fileLength&&(o.fileLength=r.fileLength),r.thumbnailUrl&&(o.thumbnailUrl=r.thumbnailUrl),PI(r,s,"video",o,n)})(e,this.buildMessageSenderOrThrow())}createLocationMessage(e){return((e,t)=>{const r=Fy.validateOrThrow(AI,e),s=UI(t),n={latitude:r.latitude,longitude:r.longitude};return r.address&&(n.address=r.address),r.buildingName&&(n.buildingName=r.buildingName),PI(r,s,"location",n)})(e,this.buildMessageSenderOrThrow())}createCmdMessage(e){return((e,t)=>{const r=Fy.validateOrThrow(NI,e),s=UI(t),n={action:r.action};return void 0!==r.deliverOnlineOnly&&(n.deliverOnlineOnly=r.deliverOnlineOnly),PI(r,s,"cmd",n)})(e,this.buildMessageSenderOrThrow())}createCustomMessage(e){return((e,t)=>{const r=Fy.validateOrThrow(OI,e),s=UI(t),n={event:r.event};return r.params&&(n.params=r.params),PI(r,s,"custom",n)})(e,this.buildMessageSenderOrThrow())}createCombineMessage(e){return xI(e,this.buildMessageSenderOrThrow())}getConversationList(e){if(void 0!==e?.mark&&(!Number.isInteger(e.mark)||e.mark<0||e.mark>19))throw new mt("filter.mark must be an integer between 0 and 19",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"filter.mark",message:"filter.mark must be an integer between 0 and 19",rule:"invalid_format"}]}});const t=(this.getClientOrThrow().getCacheManager()?.loadSessionList()??[]).filter(t=>null!==t.lastMessage&&((void 0===e?.isPinned||t.isPinned===e.isPinned)&&!(void 0!==e?.mark&&!((e,t)=>e.marks.includes(t))(t,e.mark)))).map(Cf);return this.getClientOrThrow().markConversationAccess(t.map(e=>({conversationId:e.conversationId,type:e.conversationType}))),t}setCurrentConversation(e){this.validateConversationLocator(e),this.getClientOrThrow().getCacheManager()?.setCurrentConversation({conversationId:e.conversationId,type:e.conversationType})}resetCurrentConversation(){this.getClientOrThrow().getCacheManager()?.resetCurrentConversation()}getCurrentConversation(){const e=this.getClientOrThrow().getCacheManager()?.getCurrentConversation()??null;return e?{conversationId:e.conversationId,conversationType:e.type}:null}refreshSessionList(e){return this.getClientOrThrow().refreshSessionList(e)}async deleteConversation(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=sI(t),n=Wv(r.conversationId,"params.conversationId"),i=Qv(r.conversationType,"params.conversationType"),o=r.deleteRoamingMessages??!1;if("boolean"!=typeof o)throw Hv("params.deleteRoamingMessages","params.deleteRoamingMessages must be a boolean");return await e.request(`/${s.orgName}/${s.appName}/user/${s.encodedUserId}/user_channel?resource=${s.encodedResource}`,{method:"DELETE",body:{channel:n,type:"groupChat"===i?"groupChat":Zv(i),delete_roam:o},operation:"deleteConversation"}),{conversationId:n,conversationType:i,operation:"delete"}})(this.getRestClient(t),t,e),s=this.getClientOrThrow(),n=s.getCacheManager()?.deleteConversation({conversationId:r.conversationId,type:r.conversationType});return n?.changed&&s.emitConversationListUpdate("local"),r}async setConversationPinned(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=sI(t),n=Wv(r.conversationId,"params.conversationId"),i=Qv(r.conversationType,"params.conversationType");if("boolean"!=typeof r.pinned)throw Hv("params.pinned","params.pinned must be a boolean");const o="groupChat"===i?"groupChat":Zv(i),a=r.pinned?await e.post(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/top?resource=${s.encodedResource}`,{type:o,to:n},{operation:"setConversationPinned"}):await e.delete(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/top?type=${encodeURIComponent(o)}&to=${encodeURIComponent(n)}&resource=${s.encodedResource}`,{operation:"setConversationPinned"}),c=pu(a)&&pu(a.data)?a.data:{};return{conversationId:n,conversationType:i,operation:"setPinned",isPinned:"boolean"==typeof c.is_top?c.is_top:r.pinned,pinnedTime:"number"==typeof c.update_top_status_time?c.update_top_status_time:r.pinned?Date.now():0}})(this.getRestClient(t),t,e),s=this.getClientOrThrow().getCacheManager(),n=s?.applyConversationPinnedMutation({conversationId:r.conversationId,type:r.conversationType,isPinned:r.isPinned??e.pinned,pinnedTime:r.pinnedTime});return n?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async addConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>nI(e,t,r,!0))(this.getRestClient(t),t,e),s=this.getClientOrThrow().getCacheManager(),n=s?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return n?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async removeConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>nI(e,t,r,!1))(this.getRestClient(t),t,e),s=this.getClientOrThrow().getCacheManager(),n=s?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return n?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async clearAllMessagesAndConversations(){const e=this.getRestContextOrThrow();await(async(e,t)=>{const r=sI(t);await e.post(`/${r.orgName}/${r.appName}/sdk/message/roaming/user/${r.encodedUserId}/delete/all?resource=${r.encodedResource}`,void 0,{operation:"clearAllMessagesAndConversations"})})(this.getRestClient(e),e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversations();r?.changed&&t.emitConversationListUpdate("local")}async pinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>iI(e,t,r,!0))(this.getRestClient(t),t,e))}async unpinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>iI(e,t,r,!1))(this.getRestClient(t),t,e))}async getPinnedMessageList(e){const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=sI(t),n=Wv(r.conversationId,"params.conversationId"),i=Qv(r.conversationType,"params.conversationType"),o=await e.get(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/pin?to=${encodeURIComponent(n)}&type=${encodeURIComponent(Zv(i))}&limit=${String(20)}`,{operation:"getPinnedMessageList"}),a=pu(o)&&pu(o.data)?o.data:{},c=(Array.isArray(a.msg_infos)?a.msg_infos:[]).reduce((e,r)=>{if(!pu(r))return e;const s="string"==typeof r.pin_msg_id?r.pin_msg_id:pu(r.message)&&"string"==typeof r.message.id?r.message.id:"";if(!s)return e;const o="number"==typeof r.pin_opt_at?r.pin_opt_at:0,a=tI(r.message,{messageId:s,conversationId:n,conversationType:i,currentUserId:t.userId,timestamp:o});return a?(e.push({messageId:s,conversationId:n,conversationType:i,operatorId:"string"==typeof r.pin_operator?r.pin_operator:void 0,pinnedAt:o,message:a}),e):e},[]);return{items:c}})(this.getRestClient(t),t,e))}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async clearConversationUnreadMessageCount(e){this.validateUnreadConversationLocator(e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversationUnreadMessageCount({conversationId:e.conversationId,type:e.conversationType});r?.changed&&t.emitConversationListUpdate("local");try{await this.requireConnectedClient().sendMessageAction({kind:"clearConversationUnreadMessageCount",conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:!1},(e,t)=>this.buildActionError(e,t))}catch(s){if(!r?.matched)throw s;Vs("Conversation unread remote sync failed after local clear",{conversationId:e.conversationId,conversationType:e.conversationType,error:s})}}async sendMessageReadReceipts(e){this.validateSendMessageReadReceiptsParams(e),await this.requireConnectedClient().sendMessageAction({kind:"sendMessageReadReceipts",conversationId:e.conversationId,conversationType:e.conversationType,messageIds:e.messageIds},(e,t)=>this.buildActionError(e,t))}async clearAllConversationUnreadMessageCount(){await this.requireConnectedClient().sendMessageAction({kind:"clearAllConversationUnreadMessageCount",conversationId:this.getCurrentUserIdOrThrow(),conversationType:"singleChat",sendToPeer:!1,clearAllUnreadMessageCount:!0},(e,t)=>this.buildActionError(e,t));const e=this.getClientOrThrow(),t=e.getCacheManager()?.clearAllConversationUnreadMessageCount();t?.changed&&e.emitConversationListUpdate("local")}async recallMessage(e){this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId"),await this.requireConnectedClient().sendMessageAction({kind:"recall",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,ext:e.ext},(e,t)=>this.buildActionError(e,t));return{messageId:e.messageId,conversationId:e.conversationId,conversationType:e.conversationType,timestamp:Date.now()}}async modifyMessage(e){if(this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId"),"text"!==e.message.type&&"custom"!==e.message.type)throw new mt("only text and custom messages are editable",{code:ot.OPERATION_UNSUPPORTED});await this.requireConnectedClient().sendMessageAction({kind:"update",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,body:e.message.body,messageType:e.message.type,ext:e.message.ext},(e,t)=>this.buildActionError(e,t));const t=Date.now(),r=this.getCurrentUserIdOrThrow(),s={operatorId:r,operationCount:1,operationTime:t};return{msgServerId:e.messageId,msgLocalId:"",from:r,to:e.conversationId,sender:{userId:r},conversationId:e.conversationId,conversationType:e.conversationType,type:e.message.type,sendStatus:"sent",ext:e.message.ext,timestamp:t,body:e.message.body,direct:"SEND",modifiedInfo:s}}async getHistoryMessages(e){if(this.validateConversationLocator(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r,s)=>{const n=`${FI(t)}/users/${t.userId}/messageroaming`,i=await e.post(n,{queue:"singleChat"===r.conversationType?`${r.conversationId}@easemob.com`:`${r.conversationId}@conference.easemob.com`,start:r.cursor&&r.cursor.length>0?r.cursor:-1,pull_number:r.pageSize??20,is_positive:"down"===r.searchDirection,msgType:(r.messageTypes??[]).join(","),end:-1,startTime:r.startTime??null,endTime:r.endTime??null,userIds:"singleChat"===r.conversationType?null:r.senderIds&&r.senderIds.length>0?r.senderIds:null},{operation:"getHistoryMessages"}),o=KI(i,"getHistoryMessages"),a=Array.isArray(o.msgs)?o.msgs:[],c=[];for(const d of a){if(!GI(d)||"string"!=typeof d.msg||0===d.msg.length)continue;const e=s(BI(d.msg));e&&c.push(e)}return{items:c,cursor:jI(o.next_key),hasMore:!0!==o.is_last&&c.length>0}})(this.getRestClient(t),t,e,e=>this.getClientOrThrow().decodeServerMessageMeta(e)))}async searchMessages(e){const t=Fy.validateOrThrow(fb,e),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>eb(this.getRestClient(r),r,t))}async downloadAttachment(e){return this.getClientOrThrow().downloadAttachment(e.message)}async downloadAndParseCombineMessage(e){return this.getClientOrThrow().downloadAndParseCombinePayload(this.resolveDownloadCombineMessageParams(e))}async removeHistoryMessages(e){if(this.validateConversationLocator(e),!e.messageIds&&!e.beforeTimestamp)throw this.buildValidationError("messageIds or beforeTimestamp is required","removeHistoryMessages");if(e.messageIds&&0===e.messageIds.length)throw this.buildValidationError("messageIds cannot be empty","messageIds");if(void 0!==e.beforeTimestamp&&(!Number.isInteger(e.beforeTimestamp)||e.beforeTimestamp<=0))throw this.buildValidationError("beforeTimestamp must be a positive integer","beforeTimestamp");const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const s="singleChat"===r.conversationType?"userId":"groupId",n="singleChat"===r.conversationType?"chat":"group",i=encodeURIComponent(t.clientResource),o=r.messageIds?`${FI(t)}/sdk/message/roaming/${n}/user/${t.userId}?${s}=${encodeURIComponent(r.conversationId)}&msgIdList=${encodeURIComponent(r.messageIds.join(","))}&resource=${i}`:`${FI(t)}/sdk/message/roaming/${n}/user/${t.userId}/time?${s}=${encodeURIComponent(r.conversationId)}&delTime=${r.beforeTimestamp}&resource=${i}`;await e.delete(o,{operation:"removeHistoryMessages"})})(this.getRestClient(t),t,e))}async getGroupMessageReadUsers(e){if(this.requireNonEmptyString(e.groupId,"groupId"),this.requireNonEmptyString(e.messageId,"messageId"),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow(),r=await this.executeRestOperation(()=>(async(e,t,r)=>{const s=Qy();s.set("limit",String(r.pageSize??10)),r.cursor&&s.set("key",r.cursor);const n=`${FI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/${encodeURIComponent(r.messageId)}?${s.toString()}`,i=await e.get(n,{operation:"getGroupMessageReadUsers"}),o=KI(i,"getGroupMessageReadUsers"),a=GI(o.group_ack)?o.group_ack:o,c=(Array.isArray(a.userlist)?a.userlist:[]).map(e=>GI(e)&&"string"==typeof e.username?{userId:e.username,user:VI(e.username),ackId:"string"==typeof e.meta_id?e.meta_id:void 0,timestamp:"number"==typeof e.timestamp?e.timestamp:void 0,ackContent:"string"==typeof e.ack_content?e.ack_content:void 0}:null).filter(e=>null!==e);return{groupId:r.groupId,messageId:"string"==typeof o.ackmid?o.ackmid:r.messageId,users:c,count:"number"==typeof a.total?a.total:c.length,cursor:jI(a.next_key),hasMore:!0!==a.is_last&&c.length>0}})(this.getRestClient(t),t,e));return await this.hydrateGroupMessageReadUsers(e.groupId,r)}async getGroupMessageReadReceipts(e){this.requireNonEmptyString(e.groupId,"groupId");const t=this.validateMessageIdList(e.messageIds,"messageIds"),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=`${FI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/batch`,n=await e.post(s,{messageIds:r.messageIds},{operation:"getGroupMessageReadReceipts"});return zI(n,"getGroupMessageReadReceipts").map(e=>GI(e)&&"string"==typeof e.ackmid&&"number"==typeof e.total?{messageId:e.ackmid,count:e.total}:null).filter(e=>null!==e)})(this.getRestClient(r),r,{groupId:e.groupId.trim(),messageIds:t}))}async addReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{await e.post(`${FI(t)}/reaction/user/${t.userId}`,{msgId:r.messageId,message:r.reaction},{operation:"addReaction"})})(this.getRestClient(t),t,e))}async removeReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const s=`${FI(t)}/reaction/user/${t.userId}?msgId=${encodeURIComponent(r.messageId)}&message=${encodeURIComponent(r.reaction)}`;await e.delete(s,{operation:"removeReaction"})})(this.getRestClient(t),t,e))}async getReactionList(e){if(!e.messageId||Array.isArray(e.messageId)&&0===e.messageId.length)throw this.buildValidationError("messageId is required","messageId");"groupChat"===e.conversationType&&this.requireNonEmptyString(e.groupId??"","groupId");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=Qy(),n="string"==typeof r.messageId?r.messageId:[...r.messageId].join(",");s.set("msgIdList",n),s.set("msgType","groupChat"===r.conversationType?"group":"chat"),r.groupId&&s.set("groupId",r.groupId);const i=await e.get(`${FI(t)}/reaction/user/${t.userId}?${s.toString()}`,{operation:"getReactionList"});return zI(i,"getReactionList").map(e=>{if(!GI(e)||"string"!=typeof e.msgId)return null;const t=Array.isArray(e.reactionList)?e.reactionList:[];return{messageId:e.msgId,reactions:t.map(e=>GI(e)&&"string"==typeof e.reaction?{reaction:e.reaction,count:"number"==typeof e.count?e.count:0,isAddedBySelf:!0===e.state,userIds:Array.isArray(e.userList)?e.userList.filter(e=>"string"==typeof e):[]}:null).filter(e=>null!==e)}}).filter(e=>null!==e)})(this.getRestClient(t),t,e))}async getReactionDetail(e){if(this.validateReactionParams(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=Qy();s.set("msgId",r.messageId),s.set("message",r.reaction),s.set("cursor",r.cursor??""),s.set("limit",String(r.pageSize??20));const n=await e.get(`${FI(t)}/reaction/user/${t.userId}/detail?${s.toString()}`,{operation:"getReactionDetail"}),i=KI(n,"getReactionDetail"),o=Array.isArray(i.reactionUserList)?i.reactionUserList.map(e=>GI(e)&&"string"==typeof e.userId?{userId:e.userId,user:VI(e.userId),createdAt:"string"==typeof e.createdAt?e.createdAt:void 0}:null).filter(e=>null!==e):[],a=Array.isArray(i.userList)?i.userList.filter(e=>"string"==typeof e).map(e=>({userId:e,user:VI(e)})):[],c=o.length>0?o:a;return{reaction:"string"==typeof i.reaction?i.reaction:r.reaction,count:"number"==typeof i.count?i.count:c.length,isAddedBySelf:!0===i.state,reactionUsers:c,cursor:jI(i.cursor),hasMore:jI(i.cursor).length>0,createdAt:"string"==typeof i.createdAt?i.createdAt:void 0}})(this.getRestClient(t),t,e))}async getSupportedTranslationLanguages(){const e=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t)=>{const r=await qI(()=>e.get(`${FI(t)}/users/${t.userId}/translate/support/language`,{operation:"getSupportedTranslationLanguages"}));return HI(r,"getSupportedTranslationLanguages").map(e=>GI(e)&&"string"==typeof e.code?{code:e.code,name:"string"==typeof e.name?e.name:e.code,nativeName:"string"==typeof e.nativeName?e.nativeName:e.code}:null).filter(e=>null!==e)})(this.getRestClient(e),e))}async translateMessage(e){if("text"!==e.message.type)throw new mt("only text messages can be translated",{code:ot.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"message.type",message:"must be text",rule:"message_type"}]}});const t=e.message.body.content.trim();if(0===t.length)throw new mt("message text is required",{code:ot.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"message.body.content",message:"is required",rule:"required"}]}});if(!Array.isArray(e.targetLanguages)||0===e.targetLanguages.length)throw new mt("targetLanguages is required",{code:ot.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"targetLanguages",message:"is required",rule:"required"}]}});if(e.targetLanguages.some(e=>"string"!=typeof e||0===e.trim().length))throw new mt("targetLanguages contains invalid language code",{code:ot.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"targetLanguages",message:"contains invalid language code",rule:"language_code"}]}});const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=await qI(()=>e.post(`${FI(t)}/users/${t.userId}/translate`,{text:r.text,to:[...r.targetLanguages]},{operation:"translateMessage"})),n=HI(s,"translateMessage"),i=GI(n[0])?n[0]:null;if(!i)throw qf({apiName:"translateMessage",message:"translateMessage response data is invalid",mapped:!1});const o=Array.isArray(i.translations)?i.translations:[],a=GI(i.detectedLanguage)?i.detectedLanguage:void 0;return{detectedLanguage:a&&"string"==typeof a.language?{language:a.language,score:"number"==typeof a.score?a.score:Number(a.score??0)}:void 0,translations:o.map(e=>GI(e)&&"string"==typeof e.text&&"string"==typeof e.to?{text:e.text,to:e.to}:null).filter(e=>null!==e)}})(this.getRestClient(r),r,{text:t,targetLanguages:e.targetLanguages}))}async voiceMessageToText(e,t){lb(e,t);const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>pb(this.getRestClient(r),r,e,t))}async voiceFileToText(e,t){hb(e,t);const r=this.getRestContextOrThrow(),s=this.getClientOrThrow().getUploadAdapter();if(!s)throw new ut("Upload capability is missing for current platform",ot.UPLOAD_REQUIRED_FIELD_MISSING);return this.executeRestOperation(()=>(async(e,t,r,s)=>{const n=hb(r,s),i=os({file:n,fallbackName:sb(n)?"voice.amr":void 0,fallbackMimeType:"audio/amr"});try{const r=await e.upload({url:`${t.restBaseUrl}${tb(t)}/speech/recognitions`,headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json",[ru]:tu()},source:i.source,fields:{username:t.userId,...s?.format?{format:s.format}:{},...void 0!==s?.sampleRate?{sampleRate:String(s.sampleRate)}:{},...void 0!==s?.bitsPerSample?{bitsPerSample:String(s.bitsPerSample)}:{},...void 0!==s?.channels?{channels:String(s.channels)}:{}}});let n=r.body;try{n=JSON.parse(r.body)}catch{n=r.body}if(r.status<200||r.status>=300)throw new ut("Voice-to-text failed",ot.VOICE_TO_TEXT_FAILED,{details:{httpStatus:r.status,rawResponse:n}});return{text:ob(n,"voiceFileToText")}}catch(o){if(o instanceof ut)throw ub(o);throw ub(Pd(o))}})(s,r,e,t))}validateConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType&&"chatRoom"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType")}validateUnreadConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType must be singleChat or groupChat","conversationType")}validateSendMessageReadReceiptsParams(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType");if(e.messageIds.length>50)throw this.buildValidationError("messageIds cannot contain more than 50 items","messageIds");return this.validateMessageIdList(e.messageIds,"messageIds")}validateMessageIdList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError(`${t} cannot be empty`,t);return e.map((e,r)=>{if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t}.${r} is invalid`,`${t}.${r}`);return e.trim()})}resolveDownloadCombineMessageParams(e){if("message"in e){if("combine"!==e.message.type)throw new mt("message must be a combine message",{code:ot.VALIDATION_INVALID_FORMAT});const t=e.message.body;return{url:t.url??"",secret:t.secret,timeoutMs:e.timeoutMs,maxItems:e.maxItems}}return{url:e.url,secret:e.secret,timeoutMs:e.timeoutMs,maxItems:e.maxItems}}validateReactionParams(e){this.requireNonEmptyString(e.messageId,"messageId"),this.requireNonEmptyString(e.reaction,"reaction")}buildActionError(e,t){return e===ot.AUTH_NOT_LOGIN||e===ot.AUTH_UNAUTHORIZED?new pt(t??"authentication failed",{code:e}):e===ot.CONNECTION_WEBSOCKET_ERROR||e===ot.CONNECTION_TIMEOUT?new ht(t??"connection unavailable",{code:e}):107===e||110===e||205===e||500===e||e===ot.VALIDATION_REQUIRED||e===ot.VALIDATION_INVALID_FORMAT?new mt(t??"invalid parameter",{code:e}):e===ot.MESSAGE_RECALL_TIME_LIMIT?new ut(t??"message recall time limit reached",e):e===ot.MESSAGE_EDIT_FAILED?new ut(t??"message update failed",e):e===ot.OPERATION_UNSUPPORTED?new mt(t??"operation unsupported",{code:e}):new ut(t??"message action failed",e)}requireNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} is required`,t)}buildValidationError(e,t){return new mt(e,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:e,rule:"required"}]}})}getEventContextOrThrow(){if(!this.eventContext)throw new mt("ChatManager is not bound to event context",{code:ot.VALIDATION_REQUIRED});return this.eventContext}getClientOrThrow(){if(!this.client)throw new mt("ChatManager is not bound to client",{code:ot.VALIDATION_REQUIRED});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Vf(e.restBaseUrl,{errorMap:gb,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireConnectedClient(){const e=this.getClientOrThrow();if(e.getConnectionState()!==s)throw new ht("client is not connected",{code:ot.CONNECTION_WEBSOCKET_ERROR});return e}getCurrentUserIdOrThrow(){const e=this.getClientOrThrow().getCurrentUserId();if(!e)throw new pt("user is not logged in",{code:ot.AUTH_NOT_LOGIN});return e}buildMessageSenderOrThrow(){const e=this.getClientOrThrow(),t=this.getCurrentUserIdOrThrow(),r=e.getCacheManager()?.getUserInfoSummaries([t],!1)[0];return{userId:t,nickname:r?.nickname,avatarUrl:r?.avatarUrl}}async hydrateGroupMessageReadUsers(e,t){const r=this.getClientOrThrow();if(!r.isUserInfoSyncEnabled()||0===t.users.length)return t;const s=r.getCacheManager(),n=await mI({groupId:e,users:t.users.map(e=>e.user),includeNameCard:!0,cacheManager:s,fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoReadCapability(r);return t?await t.getUserInfoByUserId({userIds:e}):[]},hydrateGroupNamecards:async(e,t)=>{const s=this.getGroupNamecardHydrationCapability(r);s&&await s.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))}});return this.dispatchFetchedUserInfoUpdates(r,n.fetchedUserInfos),{...t,users:t.users.map(e=>{const t=n.usersById.get(e.userId)??e.user;return{...e,user:t}})}}getUserInfoReadCapability(e){const t=e.getManagerByCapability("userInfo:read");return t&&"function"==typeof t.getUserInfoByUserId?t:null}getGroupNamecardHydrationCapability(e){const t=e.getManagerByCapability("group:namecard");return t&&"function"==typeof t.hydrateMessageProfileGroupNamecards?t:null}dispatchFetchedUserInfoUpdates(e,t){if(0===t.length)return;const r=e.getCurrentUserId(),s=t.find(e=>e.userId===r),n=t.filter(e=>e.userId!==r);s&&e.dispatchOwnInfoUpdated(s),e.dispatchUserInfoUpdated(n),t.length>0&&e.refreshConversationDisplayFromUserInfos(t.map(e=>({userId:e.userId})),"profile")}async executeRestOperation(e){try{return await e()}catch(t){throw this.mapRestError(t)}}mapRestError(e){return e instanceof mt||e instanceof pt||e instanceof ht||e instanceof lt?e:e instanceof vt?new lt(e.message,{code:e.code,details:e.details}):e instanceof It||e instanceof ut?e:new ut(String(e),ot.UNKNOWN)}};yb.key="chatManager";let vb=yb;class Ib{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 bb=e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),_b=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),Tb=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw bb(t);return e.trim()},Cb=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw _b(t,`${t} must be a string`);return e},Sb=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw _b(t,`${t} must be an integer between 1 and 50`);return e},Eb=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},wb=e=>pu(e)?e:null,Rb=e=>{const t=wb(e);return t?.data??e},Ab=e=>{const t=wb(e);if(Array.isArray(t?.entities))return t.entities;const r=Rb(e);if(Array.isArray(r))return r;const s=wb(r);return Array.isArray(s?.entities)?s.entities:Array.isArray(s?.affiliations)?s.affiliations:[]},Nb=e=>{const t=wb(e),r=wb(t?.data),s=wb(t?.properties);return("string"==typeof r?.cursor?r.cursor:void 0)??("string"==typeof s?.cursor?s.cursor:void 0)??("string"==typeof t?.cursor?t.cursor:void 0)??""},Ob=e=>{const t=wb(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.msgId?t.msgId:void 0);if(!r)return null;const s="number"==typeof t.timestamp?t.timestamp:0,n=t.payload,i="string"==typeof n?mu(n,{}):wb(n)??{},o=Array.isArray(i.bodies)?i.bodies:[],a=wb(o[0])??{};return{msgId:r,type:("string"==typeof a.type?a.type:void 0)??("string"==typeof i.type?i.type:void 0)??"",body:a,timestamp:s}},Mb=e=>{const t=wb(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),s=("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),n="string"==typeof t.name?t.name:"";return r&&s&&n?{chatThreadId:r,parentId:s,name:n,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:Ob(t.lastMessage??t.last_message)}:null},Ub=e=>({items:Ab(e).map(e=>Mb(e)).filter(e=>null!==e),cursor:Nb(e)}),Lb=async(e,t,r)=>{const s=Eb(t),n=Tb(r,"chatThreadId");return(e=>{const t=Rb(e),r=Array.isArray(t)?t[0]:t,s=Mb(r);if(!s)throw _b("response.data","response.data is invalid");return s})(await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}`,{operation:"getChatThreadInfo"}))},kb=async(e,t,r)=>{const s=Eb(t),n=Tb(r.chatThreadId,"params.chatThreadId"),i=Sb(r.pageSize,"params.pageSize"),o=Cb(r.cursor,"params.cursor"),a=Qy({limit:String(i),cursor:o}),c=await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users?${a.toString()}`,{operation:"getChatThreadMemberList"});return{items:Ab(d=c).map(e=>{if("string"==typeof e)return{memberId:e};const t=wb(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:Nb(d)};var d},Db=async(e,t,r)=>{const s=Eb(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw bb("params.chatThreadIds");if(r.chatThreadIds.length>20)throw _b("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const n=r.chatThreadIds.map((e,t)=>Tb(e,`params.chatThreadIds[${t}]`)),i=await e.post(`/${s.orgName}/${s.appName}/thread/message`,{threadIds:n},{operation:"getChatThreadLastMessageList"});return{items:Ab(i).map(e=>{const t=wb(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:Ob(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},Pb=bv(_v,{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"]}}}}}),xb=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(e){const t=e.trim();if(0===t.length)throw new mt("chatThreadId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadId",message:"chatThreadId is required",rule:"required"}]}});const r=this.registry.get(t);if(r)return r;const s=new Ib(t,this);return this.registry.set(t,s),s}async createChatThread(e){return this.runOperation("createChatThread",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=Eb(t),n=Tb(r.parentId,"params.parentId"),i=Tb(r.name,"params.name"),o=Tb(r.messageId,"params.messageId"),a=await e.post(`/${s.orgName}/${s.appName}/thread?resource=${s.encodedResource}`,{name:i,msg_id:o,group_id:n,owner:t.userId},{operation:"createChatThread"}),c=wb(Rb(a)),d="string"==typeof c?.thread_id?c.thread_id:void 0;if(!d)throw _b("response.data.thread_id","response.data.thread_id is invalid");return{chatThreadId:d}})(this.getRestClient(t),t,e)})}async getChatThreadList(e){return this.runOperation("getChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=Eb(t),n=Tb(r.parentId,"params.parentId"),i=Sb(r.pageSize,"params.pageSize"),o=Cb(r.cursor,"params.cursor"),a=Qy({limit:String(i),cursor:o}),c=await e.get(`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(n)}?${a.toString()}`,{operation:"getChatThreadList"});return Ub(c)})(this.getRestClient(t),t,e)})}async getJoinedChatThreadList(e={}){return this.runOperation("getJoinedChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r={})=>{const s=Eb(t),n=Sb(r.pageSize,"params.pageSize"),i=Cb(r.cursor,"params.cursor"),o=Qy({limit:String(n),cursor:i}),a="string"==typeof r.parentId&&r.parentId.trim().length>0?`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(r.parentId.trim())}/user/${s.encodedUserId}?${o.toString()}`:`/${s.orgName}/${s.appName}/threads/user/${s.encodedUserId}?${o.toString()}`,c=await e.get(a,{operation:"getJoinedChatThreadList"});return Ub(c)})(this.getRestClient(t),t,e)})}async getChatThreadInfo(e){return this.runOperation("getChatThreadInfo",async()=>{const t=this.getRestContextOrThrow();return Lb(this.getRestClient(t),t,e.chatThreadId)})}async joinChatThread(e){return this.runOperation("joinChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Eb(t),n=Tb(r,"chatThreadId");await e.post(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/user/${s.encodedUserId}/join?resource=${s.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 s=Eb(t),n=Tb(r,"chatThreadId");await e.delete(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/user/${s.encodedUserId}/quit?resource=${s.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 s=Eb(t),n=Tb(r,"chatThreadId");await e.delete(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}?resource=${s.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 s=Eb(t),n=Tb(r.chatThreadId,"params.chatThreadId"),i=Tb(r.name,"params.name");await e.put(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}?resource=${s.encodedResource}`,{name:i},{operation:"updateChatThreadName"})})(this.getRestClient(t),t,e)})}async getChatThreadMemberList(e){return this.runOperation("getChatThreadMemberList",async()=>{const t=this.getRestContextOrThrow();return kb(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Eb(t),n=Tb(r.chatThreadId,"params.chatThreadId"),i=Tb(r.memberId,"params.memberId");await e.delete(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users/${encodeURIComponent(i)}?resource=${s.encodedResource}`,{operation:"removeChatThreadMember"})})(this.getRestClient(t),t,e)})}async getChatThreadLastMessageList(e){return this.runOperation("getChatThreadLastMessageList",async()=>{const t=this.getRestContextOrThrow();return Db(this.getRestClient(t),t,e)})}getClientOrThrow(){if(!this.client)throw new mt("ChatThreadManager is not bound to client",{code:ot.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 mt("ChatThreadManager is not bound to event context",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadManager.eventContext",message:"ChatThreadManager is not bound to event context",rule:"required"}]}});return this.eventContext}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Vf(e.restBaseUrl,{errorMap:Pb,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}async runOperation(e,t){try{return await t()}catch(r){if(r instanceof ut)throw r;const t=r instanceof Error?r.message:String(r);throw new ut(`ChatThreadManager ${e} failed: ${t}`,ot.UNKNOWN)}}buildChatThreadPublicEvent(e){const t=e.payload,r="string"==typeof t.id?t.id:"",s="string"==typeof t.muc_parent_id?t.muc_parent_id:"";if(!r||!s)return null;const n="string"==typeof t.msg_parent_id?t.msg_parent_id:void 0,i="string"==typeof t.name?t.name:void 0,o="number"==typeof t.message_count?t.message_count:void 0,a=t.last_message&&"object"==typeof t.last_message?this.tryBuildThreadMessageSnippet(t.last_message):void 0,c="number"==typeof t.timestamp?t.timestamp:0,d="string"==typeof t.from?t.from:void 0,u={chatThreadId:r,parentId:s,name:i??"",messageId:n,messageCount:o,lastMessage:a};switch(t.operation){case"create":return{eventName:"onChatThreadCreated",payload:{chatThreadId:r,parentId:s,operatorId:d,chatThreadName:i,messageId:n,thread:u,timestamp:c}};case"update":case"update_msg":return{eventName:"onChatThreadUpdated",payload:{chatThreadId:r,parentId:s,operatorId:d,chatThreadName:i,messageId:n,messageCount:o,lastMessage:a,thread:u,timestamp:c}};case"delete":return{eventName:"onChatThreadDestroyed",payload:{chatThreadId:r,parentId:s,operatorId:d,timestamp:c}};case"kick":return{eventName:"onChatThreadUserRemoved",payload:{chatThreadId:r,parentId:s,operatorId:d,memberId:t.userIds?.[0],timestamp:c}};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}}};xb.key="chatThreadManager";let Fb=xb;class Bb{constructor(e,t){this.chatRoomId=e,this.manager=t}getInfo(){return this.manager.getChatRoomInfo({chatRoomId:this.chatRoomId})}refresh(){return this.getInfo()}updateInfo(e){return this.manager.updateChatRoomInfo({chatRoomId:this.chatRoomId,...e})}leaveChatRoom(){return this.manager.leaveChatRoom(this.toTarget())}getMembers(e={}){return this.manager.getMemberList({chatRoomId:this.chatRoomId,...e})}removeMembers(e){return this.manager.removeMembers(this.toUserBatchParams(e))}getAdminList(){return this.manager.getAdminList(this.toTarget())}addAdmin(e){return this.manager.addAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}removeAdmin(e){return this.manager.removeAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}getMuteList(e){return this.manager.getMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteMembers({chatRoomId:this.chatRoomId,userIds:e.userIds,duration:e.duration})}unmuteMembers(e){return this.manager.unmuteMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllMembers(this.toTarget())}checkIfInMuteList(){return this.manager.checkIfInMuteList(this.toTarget())}getBlocklist(e){return this.manager.getBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInAllowList(this.toTarget())}getAnnouncement(){return this.manager.getAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateAnnouncement({chatRoomId:this.chatRoomId,announcement:e.announcement})}getAttributes(e={}){return this.manager.getAttributes({chatRoomId:this.chatRoomId,keys:e.keys})}setAttributes(e){return this.manager.setAttributes({chatRoomId:this.chatRoomId,attributes:e.attributes,autoDelete:e.autoDelete,isForced:e.isForced})}removeAttributes(e){return this.manager.removeAttributes({chatRoomId:this.chatRoomId,keys:e.keys,isForced:e.isForced})}toTarget(){return{chatRoomId:this.chatRoomId}}toUserBatchParams(e){return{chatRoomId:this.chatRoomId,userIds:e.userIds}}}const Gb=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],qb=e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t},$b=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),jb=e=>({userId:e}),Vb=(e,t,r)=>{const s={userId:r};for(const n of Gb){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},Kb=async(e,t)=>{const r=qb(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,$b(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,t)}for(const o of r)s.has(o)||s.set(o,jb(o));return s},zb=e=>pu(e)?e:null,Hb=e=>"string"==typeof e?e:void 0,Wb=e=>{const t=Hb(e)?.trim();return t||void 0},Jb=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isFinite(t)?t:void 0}},Qb=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},Zb=e=>{const t=zb(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},Yb=e=>{const t=zb(e);return t?zb(t.data)?t.data:t:null},Xb=(e,t)=>{const r=zb(e),s=r&&zb(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return Jb(n[0])},e_=e=>Wb(e.chatRoomId)??Wb(e.chatroomid)??Wb(e.id)??"",t_=e=>Hb(e.name)??Hb(e.title)??Hb(e.groupname)??"",r_=e=>jb(e),s_=(e,t)=>{const r=(e=>{const t=Hb(e);return"owner"===t||"admin"===t||"member"===t||"none"===t?t:void 0})(e.permission);if(void 0!==r)return r;if(!t)return;if(Wb(e.owner)===t)return"owner";const s=Array.isArray(e.affiliations)?e.affiliations:[];for(const n of s){const e=zb(n);if(e){if(Wb(e.owner)===t)return"owner";if(Wb(e.admin)===t)return"admin";if(Wb(e.member)===t)return"member"}}},n_=(e,t)=>{const r=zb(e);if(!r)return null;const s=e_(r);if(!s)return null;const n=t?.stripOwnerAppKeyPrefix?(e=>{if(!e)return;const t=e.indexOf("_");return t<0?e:e.slice(t+1)})(Wb(r.owner)):Wb(r.owner);return{chatRoomId:s,name:t_(r),owner:n?r_(n):void 0,memberCount:Jb(r.memberCount)??Jb(r.affiliations_count),disabled:Qb(r.disabled)}},i_=(e,t)=>{const r=(e=>{const t=zb(e);return t?Jb(t.count):void 0})(e),s=Zb(e).map(e=>n_(e,t)).filter(e=>null!==e),n=Xb(e,"pagenum"),i=Xb(e,"pagesize");return{items:s,pageNum:n,pageSize:i,total:r,hasMore:void 0!==r&&void 0!==n&&void 0!==i?n*i<r:void 0}},o_=e=>Zb(e).map(e=>Wb(e)).filter(e=>Boolean(e)).map(e=>r_(e)),a_=(e,t)=>{const r=Yb(e)??{},s=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],n=zb(r.errorKeys)??{},i={};for(const[o,a]of Object.entries(n))"string"==typeof a&&(i[o]={code:d_(a),message:a});return{chatRoomId:t,appliedKeys:s,failedKeys:i}},c_=e=>{const t=zb(e),r=t?.data,s=Array.isArray(r)?r:void 0!==r?[r]:[],n=[],i=[];return s.forEach(e=>{const t=zb(e),r=(e=>{const t=zb(e);if(!t)return null;const r=Wb(t.user),s=Wb(t.chatRoomId)??Wb(t.chatroomid)??Wb(t.id),n=Hb(t.action),i=Qb(t.result);return r&&s&&void 0!==n&&void 0!==i?{chatRoomId:s,user:r_(r),action:n,reason:Hb(t.reason),...i?{}:{reason:Hb(t.reason)??"failed"}}:null})(e);if(!r||!t)return;Qb(t.result)?n.push(r):i.push(r)}),{succeeded:n,failed:i}},d_=e=>e.includes("is exceeding maximum limit")||e.includes("size of metadata")&&e.includes("exceeds")?ot.SERVICE_LIMIT_EXCEEDED:e.includes("is not part of you")?ot.CHATROOM_PERMISSION_DENIED:e.includes("is not Legal")||e.includes("is not exist")?ot.VALIDATION_REQUIRED:ot.REST_BUSINESS_UNKNOWN,u_=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},l_=e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),h_=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),p_=(e,t)=>`/${e.orgName}/${e.appName}${t}`,m_=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw h_(t,`${t} must be a string`);return e}},f_=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw h_(t,`${t} must be a number`);return e}},g_=(e,t)=>{const r=Qy();"number"==typeof e?.pageNum&&r.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&r.set("pagesize",String(e.pageSize));const s=r.toString();return s?`?${s}`:""},y_=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw l_(t);return e.trim()},v_=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw l_(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw h_(`${t}[${n}]`,`${t}[${n}] must be a string`);const i=e.trim();i&&!s.has(i)&&(s.add(i),r.push(i))}),0===r.length)throw l_(t);return r},I_=(e,t)=>v_(e,t),b_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}?joined_time=true&version=v3`);return((e,t)=>{const r=Zb(e),s=zb(r[0])??Yb(e)??{},n=n_(s)??{chatRoomId:e_(s),name:t_(s)},i=s_(s,t);return{...n,description:Hb(s.description),maxMembers:Jb(s.maxMembers)??Jb(s.maxusers)??Jb(s.max_users),createdAt:Jb(s.createdAt)??Jb(s.created),ext:Hb(s.ext)??Hb(s.custom),muteAllMembers:Qb(s.mute),permissionType:i}})(await e.get(i,{operation:"getChatRoomInfo"}),t.userId)},__=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i={},o=m_(r.name,"params.name"),a=m_(r.description,"params.description"),c=f_(r.maxMembers,"params.maxMembers");if(void 0!==o&&(i.groupname=o),void 0!==a&&(i.description=a),void 0!==c&&(i.maxusers=c),0===Object.keys(i).length)throw l_("params");const d=p_(s,`/chatrooms/${encodeURIComponent(n)}?resource=${s.encodedResource}`);return(e=>{const t=Yb(e)??{};return{nameUpdated:Qb(t.groupname),descriptionUpdated:Qb(t.description),maxMembersUpdated:Qb(t.maxusers)}})(await e.put(d,i,{operation:"updateChatRoomInfo"}))},T_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}/users${(e=>{const t=Qy();"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor);const r=t.toString();return r?`?${r}`:""})(r)}`);return(e=>{const t=[];for(const n of Zb(e)){const e=zb(n);if(!e)continue;const r=Wb(e.owner),s=Wb(e.admin),i=Wb(e.member),o=r??s??i;o&&t.push({user:r_(o),role:r?"owner":s?"admin":"member",joinedAt:Jb(e.joinedAt)??Jb(e.joined_time)})}const r=zb(e),s=r?Wb(r.cursor):void 0;return{items:t,cursor:s,hasMore:"string"==typeof s&&s.length>0}})(await e.get(i,{operation:"getChatRoomMemberList"}))},C_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}/admin`),o=await e.get(i,{operation:"getChatRoomAdminList"});return o_(o)},S_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=Qy();i.set("version","v3"),"number"==typeof r.pageNum&&i.set("pagenum",String(r.pageNum)),"number"==typeof r.pageSize&&i.set("pagesize",String(r.pageSize));const o=p_(s,`/chatrooms/${encodeURIComponent(n)}/mute?${i.toString()}`);return(e=>{const t=Zb(e);if(t.every(e=>"string"==typeof e))return o_(e).map(e=>({user:e}));const r=[];for(const s of t){const e=zb(s);if(!e)continue;const t=Wb(e.user)??Wb(e.member)??Wb(e.owner)??Wb(e.admin);t&&r.push({user:r_(t),muteExpire:Jb(e.muteExpire)??Jb(e.expire)??Jb(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(o,{operation:"getChatRoomMuteList"}))},E_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/sdk/chatrooms/${encodeURIComponent(n)}/mute/${s.encodedUserId}?version=v3`);return(e=>{const t=Yb(e)??{};return{muted:Qb(t.muted)??Qb(t.value)??Boolean(t.data),muteExpireAt:Jb(t.muteExpireAt)??Jb(t.expire)??Jb(t.mute_expire)}})(await e.get(i,{operation:"isCurrentUserMutedInChatRoom"}))},w_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=g_(r),o=i?"&":"",a=p_(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users?version=v3${o}${i.replace("?","")}`),c=await e.get(a,{operation:"getChatRoomBlocklist"});return o_(c).map(e=>({user:e}))},R_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}/white/users`),o=await e.get(i,{operation:"getChatRoomAllowlist"});return o_(o).map(e=>({user:e}))},A_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${s.encodedUserId}?version=v3`);return(e=>{const t=Yb(e)??{};return Qb(t.value)??Qb(t.white)??!1})(await e.get(i,{operation:"checkIfInChatRoomAllowList"}))},N_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}/announcement`);return(e=>{const t=Yb(e)??{};return{announcement:Hb(t.announcement)??""}})(await e.get(i,{operation:"getChatRoomAnnouncement"}))},O_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/metadata/chatroom/${encodeURIComponent(n)}`);return((e,t)=>{const r=Yb(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(i,{keys:r.keys?I_(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),n)},M_=async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw h_(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw l_(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw h_(t,`${t} contains invalid key`);if("string"!=typeof r)throw h_(`${t}.${e}`,`${t}.${e} must be a string`);return[e,r]}))})(r.attributes,"params.attributes"),{autoDelete:o=!0,isForced:a=!1}=r,c=a?"/forced":"",d=p_(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${c}`),u=await e.put(d,{metaData:i,autoDelete:o?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return a_(u,n)},U_={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},L_=(e,t,r)=>new mt(e,{code:"required"===r?ot.VALIDATION_REQUIRED:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:e,rule:r}]}}),k_=(e,t)=>{if("string"!=typeof e)throw L_(`${t} must be a string`,t,"invalid_format");return e},D_=(e,t)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw L_(`${t} must be a string, number, or boolean`,t,"invalid_format")},P_=(e,t="attribute")=>{const r=U_[e];if(!r)throw L_(`${t} is invalid`,t,"invalid_format");return r},x_=(e,t="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw L_(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,i]of e.entries()){const e=k_(i,`${t}[${n}]`).trim();e&&(s.has(e)||(s.add(e),r.push(e)))}if(0===r.length)throw L_(`${t} is required`,t,"required");return r},F_=(e,t="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw L_(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,i]of e.entries()){const e=k_(i,`${t}[${n}]`);if(!(e in U_))throw L_(`${t}[${n}] is invalid`,`${t}[${n}]`,"invalid_format");s.has(e)||(s.add(e),r.push(e))}if(0===r.length)throw L_(`${t} is required`,t,"required");return r},B_=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}/metadata/user/get`},G_=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}/metadata/user/${encodeURIComponent(e.userId)}`},q_=e=>({targets:x_(e)}),$_=e=>!!pu(e)&&("nickname"in e||"avatarurl"in e||"avatarUrl"in e||"mail"in e||"phone"in e||"gender"in e||"sign"in e||"birth"in e||"ext"in e),j_=(e,t)=>{if(Array.isArray(e))for(const r of e){if(!pu(r))continue;const e="string"==typeof r.username?r.username:"";e&&t.set(e,r)}},V_=(e,t)=>{const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r},K_=(e,t)=>{const r=(e=>{const t=new Map,r=pu(e)?e:null;if(r?.data&&pu(r.data))for(const[s,n]of Object.entries(r.data))$_(n)&&t.set(s,n);return j_(r?.entities,t),j_(r?.data&&pu(r.data)?r.data.entities:void 0,t),t})(e),s=(e=>{const t=new Map,r=pu(e)?e:null;if(!r?.lastModified||!pu(r.lastModified))return t;for(const[s,n]of Object.entries(r.lastModified))"number"==typeof n&&t.set(s,n);return t})(e),n=[];for(const i of t){const e=r.get(i);e&&n.push({profile:V_(i,e),lastModified:s.get(i)})}return n},z_=(e,t)=>K_(e,t).map(e=>e.profile),H_=(e,t,r,s)=>{void 0!==r&&("gender"!==t?e.push([t,k_(r,s)]):e.push([t,String(D_(r,s))]))},W_=e=>e.map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"),J_={onChatRoomDestroyed:Se,onMembersJoined:Ee,onMembersExited:we,onRemovedFromChatRoom:Re,onMuteListAdded:Ae,onMuteListRemoved:Ne,onAllowListAdded:Oe,onAllowListRemoved:Me,onAllMemberMuteStateChanged:Ue,onAdminAdded:Le,onAdminRemoved:ke,onOwnerChanged:De,onAnnouncementChanged:Pe,onChatRoomInfoChanged:xe,onAttributesUpdate:Fe,onAttributesRemoved:Be},Q_=bv(_v,{common:{},apis:{getChatRoomList:{range:"",errors:{}},getChatRoomInfo:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},updateChatRoomInfo:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},destroyChatRoom:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},joinChatRoom:{range:"4,705,704,707",errors:{exceed_limit:{code:4,httpStatus:403,retryable:!1},members_full:{code:704,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"member list is full"},user_in_blocklist:{code:707,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"is in the blacklist"},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},leaveChatRoom:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMemberList:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},addChatRoomMembers:{range:"110,204,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAdminList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAdmin:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomAdmin:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMuteList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteChatRoomMembers:{range:"110,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},isCurrentUserMutedInChatRoom:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["30005"]}}},getChatRoomBlocklist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},blockChatRoomMembers:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},unblockChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAllowlist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},addUsersToChatRoomAllowlist:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeUsersFromChatRoomAllowlist:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},checkIfInChatRoomAllowList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAnnouncement:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},updateChatRoomAnnouncement:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomSharedFileList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},deleteChatRoomSharedFile:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAttributes:{range:"110,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},setChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}}}}),Z_=class{constructor(){this.capabilities=["rawNotify:chatroom"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.chatRoomRegistry=new Map}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){const r=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{const r=J_[e];return r&&t?[[r,t]]:[]}));this.eventContext?.addEventHandler(e,r)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("chatroom"!==e.type)return;const t=e.payload,r=await this.buildIncomingEventPayload(t.eventName,t);if(!r)return;const s=J_[t.eventName];s&&this.eventContext?.dispatch?.(s,r)}async buildIncomingEventPayload(e,t){const r=t.payload,s=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(e){case"onChatRoomDestroyed":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName};case"onMembersJoined":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),s),ext:r.ext};case"onMembersExited":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),s)};case"onRemovedFromChatRoom":return{reason:r.reasonCode??0,chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,participant:this.pickEventUser(r.participantId,s)};case"onMuteListAdded":return{chatRoomId:r.chatRoomId,mutes:this.pickEventMuteEntries(r.userIds,r.muteExpire,s),muteExpire:r.muteExpire};case"onMuteListRemoved":return{chatRoomId:r.chatRoomId,mutes:this.pickEventUsers(r.userIds,s)};case"onAllowListAdded":case"onAllowListRemoved":return{chatRoomId:r.chatRoomId,allowlist:this.pickEventUsers(r.userIds,s)};case"onAllMemberMuteStateChanged":return{chatRoomId:r.chatRoomId,isMuted:Boolean(r.isMuted)};case"onAdminAdded":case"onAdminRemoved":return{chatRoomId:r.chatRoomId,admin:this.pickEventUser(r.adminId,s)};case"onOwnerChanged":return{chatRoomId:r.chatRoomId,newOwner:this.pickEventUser(r.newOwnerId,s),oldOwner:this.pickEventUser(r.oldOwnerId,s)};case"onAnnouncementChanged":return{chatRoomId:r.chatRoomId,announcement:r.announcement??""};case"onChatRoomInfoChanged":return{chatRoomId:r.chatRoomId,chatRoomInfo:await this.resolveChatRoomDetailForEvent(r)};case"onAttributesUpdate":return{chatRoomId:r.chatRoomId,attributes:r.attributes??{},from:this.pickEventUser(r.from,s)};case"onAttributesRemoved":return{chatRoomId:r.chatRoomId,keyList:r.keyList??[],from:this.pickEventUser(r.from,s)};default:return null}}async getChatRoomList(e={}){return this.runOperation("getChatRoomList",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r={})=>{const s=u_(t),n=p_(s,`/chatrooms${g_(r)}`),i=await e.get(n,{operation:"getChatRoomList"});return i_(i)})(this.getRestClient(t),t,e);return{...r,items:await this.hydrateSummaryOwners(r.items)}})}getChatRoom(e){this.requireClient();const t=e.trim();if(0===t.length)throw new mt("chatRoomId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"chatRoomId",message:"chatRoomId is required",rule:"required"}]}});const r=this.chatRoomRegistry.get(t);if(r)return r;const s=new Bb(t,this);return this.chatRoomRegistry.set(t,s),s}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await b_(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return __(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=y_(e.chatRoomId,"params.chatRoomId"),s=this.normalizeOptionalString(e.ext,"params.ext"),n=this.normalizeOptionalBoolean(e.leaveOtherRooms,"params.leaveOtherRooms");try{return(await t.sendChatRoomOperation({operation:"join",chatRoomId:r,ext:s,leaveOtherRooms:n})).chatRoomInfo??{}}catch(i){throw this.remapChatRoomOperationError("joinChatRoom",i)}})}async leaveChatRoom(e){return this.runOperation("leaveChatRoom",async()=>{const t=this.requireClient(),r=y_(e.chatRoomId,"params.chatRoomId");try{await t.sendChatRoomOperation({operation:"leave",chatRoomId:r})}catch(s){throw this.remapChatRoomOperationError("leaveChatRoom",s)}})}async getMemberList(e){return this.runOperation("getMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await T_(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(r.items)}})}async removeMembers(e){return this.runOperation("removeMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=v_(r.userIds,"params.userIds"),o=p_(s,`/chatrooms/${encodeURIComponent(n)}/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"removeChatRoomMembers"});return c_(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await C_(this.getRestClient(t),t,e);return this.hydrateUserInfos(r)})}async addAdmin(e){return this.runOperation("addAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=y_(r.userId,"params.userId"),o=p_(s,`/chatrooms/${encodeURIComponent(n)}/admin?resource=${s.encodedResource}`);await e.post(o,{newadmin:i},{operation:"setChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async removeAdmin(e){return this.runOperation("removeAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=y_(r.userId,"params.userId"),o=p_(s,`/chatrooms/${encodeURIComponent(n)}/admin/${encodeURIComponent(i)}?resource=${s.encodedResource}`);await e.delete(o,{operation:"removeChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async getMuteList(e){return this.runOperation("getMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await S_(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async muteMembers(e){return this.runOperation("muteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=v_(r.userIds,"params.userIds"),o=f_(r.duration,"params.duration"),a=p_(s,`/chatrooms/${encodeURIComponent(n)}/mute?resource=${s.encodedResource}`);await e.post(a,{usernames:i,mute_duration:o},{operation:"muteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteMembers(e){return this.runOperation("unmuteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=v_(r.userIds,"params.userIds"),o=p_(s,`/chatrooms/${encodeURIComponent(n)}/mute/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(o,{operation:"unmuteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async muteAllMembers(e){return this.runOperation("muteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}/ban?resource=${s.encodedResource}`);await e.post(i,void 0,{operation:"muteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllMembers(e){return this.runOperation("unmuteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=p_(s,`/chatrooms/${encodeURIComponent(n)}/ban?resource=${s.encodedResource}`);await e.delete(i,{operation:"unmuteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async checkIfInMuteList(e){return this.runOperation("checkIfInMuteList",async()=>{const t=this.getRestContextOrThrow();return E_(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await w_(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async blockMembers(e){return this.runOperation("blockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=v_(r.userIds,"params.userIds"),o=1===i.length,a=p_(s,o?`/chatrooms/${encodeURIComponent(n)}/blocks/users/${encodeURIComponent(i[0]??"")}?resource=${s.encodedResource}`:`/chatrooms/${encodeURIComponent(n)}/blocks/users?resource=${s.encodedResource}`),c=await e.post(a,o?void 0:{usernames:i},{operation:"blockChatRoomMembers"});return c_(c)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async unblockMembers(e){return this.runOperation("unblockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=v_(r.userIds,"params.userIds"),o=p_(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"unblockChatRoomMembers"});return c_(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await R_(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async addUsersToAllowlist(e){return this.runOperation("addUsersToAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=v_(r.userIds,"params.userIds"),o=p_(s,`/chatrooms/${encodeURIComponent(n)}/white/users?resource=${s.encodedResource}`),a=await e.post(o,{usernames:i},{operation:"addUsersToChatRoomAllowlist"});return c_(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async removeUsersFromAllowlist(e){return this.runOperation("removeUsersFromAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=v_(r.userIds,"params.userIds"),o=p_(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"removeUsersFromChatRoomAllowlist"});return c_(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return A_(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return N_(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=m_(r.announcement,"params.announcement");if(void 0===i)throw l_("params.announcement");const o=p_(s,`/chatrooms/${encodeURIComponent(n)}/announcement?resource=${s.encodedResource}`);await e.post(o,{announcement:i},{operation:"updateChatRoomAnnouncement"})})(this.getRestClient(t),t,e)})}async getAttributes(e){return this.runOperation("getAttributes",async()=>{const t=this.getRestContextOrThrow();return O_(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await M_(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async removeAttributes(e){return this.runOperation("removeAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=u_(t),n=y_(r.chatRoomId,"params.chatRoomId"),i=I_(r.keys,"params.keys"),{isForced:o=!1}=r,a=o?"/forced":"",c=p_(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${a}`),d=await e.request(c,{method:"DELETE",body:{keys:i},operation:"removeChatRoomAttributes"});return a_(d,n)})(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Vs(`ChatRoomManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof ut?t:t instanceof Error?new ut(`ChatRoomManager ${e} failed: ${t.message}`,ot.UNKNOWN):new ut(`ChatRoomManager ${e} failed`,ot.UNKNOWN)}remapChatRoomOperationError(e,t){return t instanceof ut&&t.code===ot.GROUP_NOT_EXIST?new ft("Chat room does not exist",{code:ot.CHATROOM_NOT_EXIST,details:{...t.details,api:e,originalCode:t.code,canonicalCode:ot.CHATROOM_NOT_EXIST,retryable:!1}}):t}checkAttributeMutationResult(e){const t=Object.values(e.failedKeys);if(t.length>0&&0===e.appliedKeys.length){const[e]=t;if(e)throw new ut(e.message,e.code)}return e}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Vf(e.restBaseUrl,{errorMap:Q_,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new ut("ChatRoomManager is not bound to client",ot.VALIDATION_REQUIRED);return this.client}normalizeOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw new mt(`${t} must be a string`,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:`${t} must be a string`,rule:"invalid_format"}]}});return e}}normalizeOptionalBoolean(e,t){if(void 0!==e){if("boolean"!=typeof e)throw new mt(`${t} must be a boolean`,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:`${t} must be a boolean`,rule:"invalid_format"}]}});return e}}getCacheManager(){return this.client?.getCacheManager()??null}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}async resolveUserInfoMap(e){return Kb(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Vs("ChatRoomManager user info fetch failed",{userIds:e,error:r}),[]}}})}async hydrateUserInfos(e){return(async(e,t)=>{const r=qb(e),s=await Kb(r,t);return r.map(e=>Vb(void 0,s.get(e),e))})(e.map(e=>e.userId),{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Vs("ChatRoomManager hydrate users failed",{userIds:e,error:r}),[]}}})}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=q_(e),s=await this.getRestClient(t).request(B_(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return z_(s,r.targets)}collectEventUserIds(e){const t=e.payload,r=[t.participantId,t.memberId,...t.memberIds??[],t.adminId,t.oldOwnerId,t.newOwnerId,t.from,...t.userIds??[]],s=[],n=new Set;for(const i of r){if("string"!=typeof i)continue;const e=i.trim();e&&!n.has(e)&&(n.add(e),s.push(e))}return s}pickEventUser(e,t){if(e)return Vb(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>Vb(void 0,t.get(e),e))}pickEventMuteEntries(e,t,r){return this.pickEventUsers(e,r).map(e=>({user:e,muteExpire:t}))}async resolveChatRoomDetailForEvent(e){if(e.shouldFetchChatRoomDetail)try{return await this.getChatRoomInfo({chatRoomId:e.chatRoomId})}catch(t){Vs("ChatRoomManager event detail fetch failed",{chatRoomId:e.chatRoomId,error:t})}return{chatRoomId:e.chatRoomId,name:e.chatRoomPatch?.name??e.chatRoomName??"",...e.chatRoomPatch??{}}}async hydrateEntriesWithUsers(e){const t=e.map(e=>e.user.userId),r=await this.resolveUserInfoMap(t);return e.map(e=>({...e,user:Vb(e.user,r.get(e.user.userId),e.user.userId)}))}async hydrateActionListResult(e){return{succeeded:await this.hydrateEntriesWithUsers(e.succeeded),failed:await this.hydrateEntriesWithUsers(e.failed)}}async hydrateSummaryOwners(e){const t=e.map(e=>e.owner?.userId).filter(e=>"string"==typeof e),r=await this.resolveUserInfoMap(t);return e.map(e=>e.owner?.userId?{...e,owner:Vb(e.owner,r.get(e.owner.userId),e.owner.userId)}:e)}async hydrateChatRoomDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveUserInfoMap([e.owner.userId]);return{...e,owner:Vb(e.owner,t.get(e.owner.userId),e.owner.userId)}}};Z_.key="chatRoomManager";let Y_=Z_;const X_={common:{},apis:{getContactList:{range:"",errors:{}},addContact:{range:"110,204,210,1000,1001,1002",localErrors:{addContact:{validation_invalid:{code:110,retryable:!1},cannot_add_self:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},ALREADY_FRIEND:{code:1e3,retryable:!1},BLOCKED_BY_USER:{code:210,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},deleteContact:{range:"110,204",localErrors:{deleteContact:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},acceptContactInvite:{range:"110,204,1001,1002",localErrors:{acceptContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},declineContactInvite:{range:"110,204",localErrors:{declineContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1}}},setContactRemark:{range:"4,110,221",localErrors:{setContactRemark:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_ON_ROSTER:{code:221,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"please add as a friend first"},remark_length_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"remark length must less than"}}},getBlocklist:{range:"",errors:{}},addUsersToBlocklist:{range:"4,110,204",localErrors:{addUsersToBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{service_resource_not_found:{code:204,httpStatus:404,retryable:!1},blocklist_limit_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"almost reached or been greater than the upper range"}}},removeUserFromBlocklist:{range:"110",localErrors:{removeUserFromBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{}}}},eT="User ID is invalid: cannot add yourself as a contact",tT=(e,t,r)=>{if(!pu(e)||!pu(e.data))return;const s=e.data[t];if(Array.isArray(s))for(const n of s)if(pu(n)&&"string"==typeof n.failReason&&n.failReason.toLowerCase().includes(r))return n.failReason},rT=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},sT=e=>pu(e)&&Array.isArray(e.data)?e.data.filter(e=>"string"==typeof e&&e.length>0):Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[],nT=(e,t)=>{if(!Array.isArray(e.userIds)||0===e.userIds.length)throw new mt(`${t} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}});const r=e.userIds.map((e,r)=>{if("string"!=typeof e)throw new mt(`${t}[${r}] must be a string`,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:`${t}[${r}]`,message:"userId must be a string",rule:"invalid_format"}]}});return e.trim()}),s=(e=>{const t=[],r=new Set;for(const s of e)s&&!r.has(s)&&(r.add(s),t.push(s));return t})(r);if(0===s.length)throw new mt(`${t} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}});return s.length!==r.length&&pu(e),s},iT=async(e,t,r)=>{const s=rT(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/apply?resource=${s.encodedResource}`;(e=>{const t=tT(e,"applyYourselfUsers","user cannot apply to become a new friend");if(t)throw new mt(eT,{code:ot.VALIDATION_INVALID_FORMAT,details:{api:"addContact",mapped:!0,reasonKey:"cannot_add_self",serverMessage:t,retryable:!1,canonicalCode:ot.VALIDATION_INVALID_FORMAT,fields:[{path:"params.userId",message:eT,rule:"invalid_format"}]}});const r=tT(e,"notExistUsers","the users not exist");if(!r)return;const s=Gf(X_,"addContact",{error:"USER_NOT_FOUND"});if(!s)throw qf({apiName:"addContact",serverMessage:r,mapped:!1,reasonKey:"USER_NOT_FOUND"});throw qf({apiName:"addContact",entry:s.entry,serverMessage:r,mapped:!0,reasonKey:s.reasonKey,matchedBy:s.matchedBy})})(await e.post(n,{usernames:[r.userId],reason:r.message??""},{operation:"addContact"}))},oT=async(e,t)=>{const r=rT(t),s=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/blocks/users`,n=await e.get(s,{operation:"getBlocklist"});return sT(n).map(e=>({userId:e}))},aT=async(e,t,r)=>{const s=rT(t),n=`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/blocks?resource=${s.encodedResource}`,i=await e.post(n,{usernames:r},{operation:"addUsersToBlocklist"});return{succeeded:sT(i).map(e=>({userId:e})),failed:[]}},cT={nested:{easemob:{nested:{imfusion:{nested:{gateway:{nested:{v1:{nested:{MessageType:{values:{MESSAGE_TYPE_UNSPECIFIED:0,MESSAGE_TYPE_PING:1,MESSAGE_TYPE_PONG:2,MESSAGE_TYPE_ROSTER_REQUEST:3,MESSAGE_TYPE_ROSTER_RESPONSE:4,MESSAGE_TYPE_ERROR:5}},ServerStatus:{values:{SERVER_STATUS_OK:0,SERVER_STATUS_BUSY:1}},RosterResponseType:{values:{ROSTER_RESPONSE_TYPE_UNSPECIFIED:0,ROSTER_RESPONSE_TYPE_INCREMENTAL:1,ROSTER_RESPONSE_TYPE_FULL:2}},BaseMessage:{fields:{type:{type:"MessageType",id:1}}},GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},requestId:{type:"string",id:3},protocolVersion:{type:"int32",id:4}}},PingRequest:{fields:{type:{type:"MessageType",id:1}}},PongResponse:{fields:{type:{type:"MessageType",id:1},status:{type:"ServerStatus",id:2}}},ErrorDetail:{fields:{type:{type:"MessageType",id:1},code:{type:"string",id:2},message:{type:"string",id:3},header:{type:"GatewayHeader",id:4}}},GetRosterRequest:{fields:{type:{type:"MessageType",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},version:{type:"string",id:6},cursor:{type:"uint64",id:7}}},RosterItem:{fields:{contact:{type:"string",id:1},remark:{type:"string",id:2},metadata:{type:"string",id:3},createdAt:{type:"int64",id:4},updatedAt:{type:"int64",id:5},metadataUpdatedAt:{type:"int64",id:6}}},GetRosterResponse:{fields:{type:{type:"MessageType",id:1},header:{type:"GatewayHeader",id:2},data:{rule:"repeated",type:"RosterItem",id:3},cursor:{type:"uint64",id:4},version:{type:"string",id:5},responseType:{type:"RosterResponseType",id:6}}}}}}}}}}}}};let dT=!1,uT=null;const lT=()=>uT||(dT||(fa.util.Long=Dn,fa.configure(),dT=!0),Va(),uT=fa.Root.fromJSON(cT),ja(uT),uT),hT=e=>"number"==typeof e?e:Dn.isLong(e)?e.toNumber():0,pT=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:hT(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:hT(t.protocolVersion)}};class mT{encodeRequest(e){const t=lT().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=Dv){const t=lT().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:Mv,status:e})).finish()}decode(e){const t=lT(),r=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(r.type){case Ov:return{type:Ov};case Mv:{const r=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:Mv,status:hT(r.status)}}case Lv:{const r=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:Lv,header:pT(r.header),data:Array.isArray(r.data)?r.data.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{contact:"string"==typeof t.contact?t.contact:"",remark:"string"==typeof t.remark?t.remark:"",metadata:"string"==typeof t.metadata?t.metadata:"",createdAt:hT(t.createdAt),updatedAt:hT(t.updatedAt),metadataUpdatedAt:hT(t.metadataUpdatedAt)}})(e)):[],cursor:hT(r.cursor),version:"string"==typeof r.version?r.version:"",responseType:hT(r.responseType)||Pv}}case kv:{const r=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:kv,header:pT(r.header),code:"string"==typeof r.code?r.code:"",message:"string"==typeof r.message?r.message:"Unknown roster error"}}default:return{type:"number"==typeof r.type?r.type:Nv}}}}class fT{constructor(e){this.pages=[],this.responseType=null,this.version="",this.nextCursor=0,this.pageCount=0,this.completed=!1,this.requestId=e}push(e){const t=e.header?.requestId;if(t&&t!==this.requestId)throw new ut("Roster response requestId mismatched",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",expectedRequestId:this.requestId,receivedRequestId:t}});if(this.completed)throw new ut("Roster response received after completion",ot.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:e.cursor}});if(null!==this.responseType&&this.responseType!==e.responseType)throw new ut("Roster response type changed in same session",ot.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.responseType,received:e.responseType}});if(this.pages.length>0&&0!==e.cursor&&e.cursor===this.pages[this.pages.length-1]?.cursor)throw new ut("Roster cursor duplicated",ot.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:e.cursor}});return this.responseType=e.responseType,this.version=e.version||this.version,this.pages.push(e),this.nextCursor=e.cursor,this.pageCount+=1,this.completed=0===e.cursor,{done:this.completed,nextCursor:this.nextCursor,pageCount:this.pageCount}}getNextCursor(){return this.nextCursor}getPageCount(){return this.pageCount}hasPages(){return this.pages.length>0}isCompleted(){return this.completed}buildResult(){return{mode:this.responseType===xv?"incremental":"full",version:this.version,pages:this.pages}}}const gT=e=>e.type===Lv,yT=e=>"message"in e&&"code"in e;class vT{constructor(e){this.codec=new mT,this.sharedSession=e}async sync(e){const t=new fT(e.request.header.requestId);return await this.syncWithSharedSession(e.request,t)}cancel(){this.sharedSession.cancel("contact-sync-cancelled")}async syncWithSharedSession(e,t){return await this.sharedSession.request({dataType:"contact",label:"Roster sync",requestId:e.header.requestId,encode:()=>{const r=this.buildAttemptRequest(e,t.getNextCursor());return this.codec.encodeRequest(r)},decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:gT(t)||yT(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(e,r)=>{try{if(e.type===Ov)return void(await r.send(this.codec.encodePong()));if(gT(e)){if(!t.push(e).done)return;return{done:!0,result:t.buildResult()}}if(yT(e))throw(e=>{const t=e.header?.requestId,r=r=>({stage:"sync_page",serverCode:e.code,requestId:t,retryable:r});switch(Number.parseInt(e.code,10)){case Bv:return new pt(e.message,{code:ot.AUTH_UNAUTHORIZED,details:r(!1)});case Gv:return new ut(e.message,ot.SERVICE_LIMIT_EXCEEDED,{details:r(!0)});case Fv:return new ut(e.message,ot.VALIDATION_REQUIRED,{details:r(!1)});case qv:return new ut(e.message,ot.VALIDATION_INVALID_FORMAT,{details:r(!1)});case $v:return new ut(e.message,ot.REST_BUSINESS_UNKNOWN,{details:r(!0)});case jv:return new ut(e.message,ot.CONTACT_SYNC_SOCKET_FAILED,{details:r(!1)});default:return new ut(e.message,ot.CONTACT_SYNC_SOCKET_FAILED,{details:r(!0)})}})(e);return}catch(s){throw s instanceof ut?s:new ut("Roster frame decode failed",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:s instanceof Error?s.message:String(s)}})}}})}buildAttemptRequest(e,t){return{...e,cursor:t,header:{...e.header,timestamp:Date.now(),requestId:e.header.requestId}}}}const IT=e=>e.versionState.version?"incremental":"full",bT=e=>{const{metadata:t,metadataFailed:r,state:s}=e,n=s.versionState.version;return r||!t?{decision:"complete"===s.cacheMeta.cacheIntegrity?IT(s):"full",version:n}:t.requiresSync||"complete"!==s.cacheMeta.cacheIntegrity?t.requiresSync&&"complete"===s.cacheMeta.cacheIntegrity&&n?{decision:"incremental",version:t.version||n}:{decision:"full",version:t.version||n}:{decision:"skip",version:t.version||n}},_T=e=>{if(!e)return{};try{const t=JSON.parse(e);return{nickname:"string"==typeof t.nickname?t.nickname:void 0,avatarUrl:"string"==typeof t.avatarUrl?t.avatarUrl:"string"==typeof t.avatarurl?t.avatarurl:void 0,sign:"string"==typeof t.sign?t.sign:void 0,ext:"string"==typeof t.ext?t.ext:void 0}}catch{return{}}},TT=e=>{const t=(e=>{if(!(e instanceof ut&&e.details))return null;const t=e.details.httpStatus;return"number"==typeof t?t:null})(e);return 401===t||403===t||404===t},CT=(e,t,r,s)=>({code:t,stage:e,message:`${e}: ${r}`,retryable:s}),ST=e=>{Vs("Contact sync duration",e)};class ET{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("contact-sync-cancelled")}async runSync(){const e=this.dependencies.getContextState(),t=Date.now();let r;this.dependencies.onStart();try{const s=await this.dependencies.queryMetadata(e.versionState.version);if(r=bT({metadata:s,state:e}),"skip"===r.decision)return this.dependencies.onFinish(),void ST({outcome:"skip",decision:r.decision,durationMs:Date.now()-t,version:r.version,hasUsableSnapshot:e.cachedSnapshot.complete})}catch(s){if(TT(s)){const r=bT({metadataFailed:!0,state:e}),n=s instanceof ut?s:new ut("Contact metadata request failed",ot.CONTACT_SYNC_METADATA_FAILED,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:CT("metadata",n.code,n.message,!1)}),void ST({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:e.versionState.version,stage:"metadata",hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}if(r=bT({metadataFailed:!0,state:e}),e.cachedSnapshot.complete)return this.dependencies.onFinish({error:CT("metadata",ot.CONTACT_SYNC_METADATA_FAILED,s instanceof Error?s.message:String(s),!0)}),void ST({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:r.version,stage:"metadata",hasUsableSnapshot:!0,source:e.cachedSnapshot.source})}try{const s=await this.dependencies.getSyncUrls(),n=this.dependencies.buildRosterRequest({decision:r.decision,version:e.versionState.version}),i=await new vT(this.dependencies.getSharedSyncSession()).sync({urls:s,request:n}),o=(e=>{const t=[];for(const r of e)for(const e of r.data){const r=_T(e.metadata);t.push({relation:{userId:e.contact,remark:e.remark,sign:r.sign??"",addTs:e.createdAt,updatedAt:e.updatedAt,metadataUpdatedAt:e.metadataUpdatedAt},userInfo:{userId:e.contact,nickname:r.nickname,avatarUrl:r.avatarUrl,sign:r.sign,ext:r.ext}})}return t})(i.pages),a=this.dependencies.applySyncResult({mode:i.mode,relations:o.map(e=>e.relation),userInfos:o.map(e=>e.userInfo),version:i.version,lastSyncTs:Date.now()});this.dependencies.onFinish(),ST({outcome:"finish",decision:r.decision,durationMs:Date.now()-t,version:i.version,source:"sync",changed:a.changed,hasUsableSnapshot:a.snapshot.complete})}catch(s){const n=s instanceof ut?s:new ut("Contact sync failed",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"sync_page",cause:s instanceof Error?s.message:String(s)}}),i=n.details??{},o="string"==typeof i.stage?i.stage:"sync_page";this.dependencies.onFinish({error:CT(o,n.code,n.message,!0)}),ST({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:r.version,stage:o,hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}}}const wT={items:[],loaded:!1,source:"server"},RT=bv(_v,X_),AT=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=wT,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=wT,this.blocklistSessionKey=null}getContacts(){return this.client?.getContactSnapshot()?.items??[]}async addContact(e){return this.runOperation("addContact",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.validateOptionalString(e.message,"params.message"),s=this.getRestContextOrThrow();if(t===s.userId)throw this.buildValidationError(eT,[{path:"params.userId",message:eT,rule:"invalid_format"}]);const n=this.getRestClient(s);js("ContactManager addContact",{userId:t,hasMessage:"string"==typeof r&&r.length>0}),await iT(n,s,{userId:t,message:r})})}async deleteContact(e){return this.runOperation("deleteContact",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);js("ContactManager deleteContact",{userId:t}),await(async(e,t,r)=>{const s=rT(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.delete(n,{operation:"deleteContact"})})(s,r,{userId:t});const n=this.client?.getCacheManager()?.removeContact(t);js("ContactManager deleteContact patched cache",{userId:t,changed:n?.changed??!1})})}async acceptContactInvite(e){return this.runOperation("acceptContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);js("ContactManager acceptContactInvite",{userId:t}),await(async(e,t,r)=>{const s=rT(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/accept/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.post(n,void 0,{operation:"acceptContactInvite"})})(s,r,{userId:t}),await this.requireClient().refreshContactSnapshot()})}async declineContactInvite(e){return this.runOperation("declineContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);js("ContactManager declineContactInvite",{userId:t}),await(async(e,t,r)=>{const s=rT(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/decline/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.post(n,void 0,{operation:"declineContactInvite"})})(s,r,{userId:t})})}async setContactRemark(e){return this.runOperation("setContactRemark",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.validateRemark(e.remark,"params.remark"),s=this.getRestContextOrThrow(),n=this.getRestClient(s);js("ContactManager setContactRemark",{userId:t,remarkLength:r.length}),await(async(e,t,r)=>{const s=rT(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.put(n,{remark:r.remark},{operation:"setContactRemark"})})(n,s,{userId:t,remark:r});const i=this.client?.getCacheManager()?.updateContactRemark(t,r);this.client?.refreshConversationDisplayFromUserInfos([{userId:t}],"profile"),js("ContactManager setContactRemark patched cache",{userId:t,changed:i?.changed??!1})})}async getBlocklist(){return this.runOperation("getBlocklist",async()=>{const e=this.getRestContextOrThrow();this.ensureBlocklistSession(e);const t=this.getRestClient(e);if(this.blocklistSnapshot.loaded)return this.blocklistSnapshot.items;const r=await this.enrichBlocklistUsers(await oT(t,e));return this.blocklistSnapshot={items:r,loaded:!0,source:"server"},js("ContactManager getBlocklist",{count:r.length}),r})}async addUsersToBlocklist(e){return this.runOperation("addUsersToBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const r=nT(e,"params.userIds"),s=this.getRestClient(t);js("ContactManager addUsersToBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length});const n=await aT(s,t,r),i=await this.enrichBlocklistUsers(n.succeeded);return this.blocklistSnapshot=this.patchBlocklistSnapshotWithAdditions(i),{succeeded:i,failed:await this.enrichBlocklistUsers(n.failed)}})}async removeUserFromBlocklist(e){return this.runOperation("removeUserFromBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const r=nT(e,"params.userIds"),s=this.getRestClient(t);js("ContactManager removeUserFromBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length}),await(async(e,t,r)=>{const s=rT(t),n=`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/blocks?resource=${s.encodedResource}`;await e.request(n,{method:"DELETE",body:{usernames:r},operation:"removeUserFromBlocklist"})})(s,t,r),this.blocklistSnapshot=this.patchBlocklistSnapshotWithRemovals(r)})}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Vs(`ContactManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof ut?t:t instanceof Error?new ut(`ContactManager ${e} failed: ${t.message}`,ot.UNKNOWN):new ut(`ContactManager ${e} failed`,ot.UNKNOWN)}requireClient(){if(!this.client)throw this.buildValidationError("ContactManager is not bound to client",[{path:"contactManager.client",message:"ContactManager is not bound to client",rule:"required"}]);return this.client}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Vf(e.restBaseUrl,{errorMap:RT,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}ensureBlocklistSession(e){const t=`${e.restBaseUrl}:${e.userId}:${e.token}`;this.blocklistSessionKey!==t&&(this.blocklistSessionKey=t,this.blocklistSnapshot=wT)}patchBlocklistSnapshotWithAdditions(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const r of e)t.set(r.userId,r);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}patchBlocklistSnapshotWithRemovals(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const r of e)t.delete(r);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}validateUserId(e,t){if("string"!=typeof e)throw this.buildValidationError("userId must be a string",[{path:t,message:"userId must be a string",rule:"invalid_format"}]);const r=e.trim();if(!r)throw this.buildValidationError("userId is required",[{path:t,message:"userId is required",rule:"required"}]);return r}validateOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw this.buildValidationError(`${t} must be a string`,[{path:t,message:`${t} must be a string`,rule:"invalid_format"}]);return e}}validateRemark(e,t){if("string"!=typeof e)throw this.buildValidationError("remark must be a string",[{path:t,message:"remark must be a string",rule:"invalid_format"}]);return e}buildValidationError(e,t){const r=t.some(e=>"invalid_format"===e.rule)?ot.VALIDATION_INVALID_FORMAT:ot.VALIDATION_REQUIRED;return new mt(e,{code:r,details:{fields:t}})}async enrichBlocklistUsers(e){if(0===e.length||!this.requireClient().isUserInfoSyncEnabled())return e;const t=await Ev(e.map(e=>e.userId),{cacheManager:this.requireClient().getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchUserInfos(e)});return e.map(e=>t.get(e.userId)??e)}async fetchUserInfos(e){if(0===e.length)return[];try{const t=this.getUserInfoManager();return t?await t.getUserInfoByUserId({userIds:e}):await this.fetchUserInfosFromRest(e)}catch(t){return Vs("ContactManager user info fetch failed",{userIds:e,error:t}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=q_(e),s=await this.getRestClient(t).request(B_(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return z_(s,r.targets)}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}createSyncController(e){return new ET(e)}};AT.key="contactManager";let NT=AT;class OT{constructor(e,t){this.groupId=e,this.manager=t}getSummary(){return this.manager.getGroupSummaryForHandle(this.groupId)}getDetail(){return this.manager.getGroupDetailForHandle(this.groupId)}refresh(){return this.manager.refreshGroupDetailForHandle(this.groupId)}updateInfo(e){return this.manager.updateGroupInfo({groupId:this.groupId,...e})}updateConfigs(e){return this.manager.updateGroupInfo({groupId:this.groupId,...e})}changeOwner(e){return this.manager.changeGroupOwner({groupId:this.groupId,newOwner:e.newOwner})}destroy(){return this.manager.destroyGroup(this.toTarget())}leave(){return this.manager.leaveGroup(this.toTarget())}getMembers(e={}){return this.manager.getGroupMemberList({groupId:this.groupId,...e})}removeMembers(e){return this.manager.removeGroupMembers(this.toUserBatchParams(e))}getAdmins(){return this.manager.getGroupAdminList(this.toTarget())}addAdmin(e){return this.manager.addGroupAdmin({groupId:this.groupId,userId:e.userId})}removeAdmin(e){return this.manager.removeGroupAdmin({groupId:this.groupId,userId:e.userId})}getMuteList(e){return this.manager.getGroupMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteGroupMembers({groupId:this.groupId,userIds:e.userIds,muteDuration:e.muteDuration})}unmuteMembers(e){return this.manager.unmuteGroupMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllGroupMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllGroupMembers(this.toTarget())}getBlocklist(e){return this.manager.getGroupBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockGroupMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockGroupMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getGroupAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToGroupAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromGroupAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInGroupAllowList({groupId:this.groupId})}checkIfInMuteList(){return this.manager.checkIfInGroupMuteList(this.toTarget())}getAnnouncement(){return this.manager.getGroupAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateGroupAnnouncement({groupId:this.groupId,announcement:e.announcement})}getSharedFileList(e={}){return this.manager.getGroupSharedFileList({groupId:this.groupId,...e})}uploadSharedFile(e){return this.manager.uploadGroupSharedFile({groupId:this.groupId,...e})}deleteSharedFile(e){return this.manager.deleteGroupSharedFile({groupId:this.groupId,fileId:e.fileId})}downloadSharedFile(e){return this.manager.downloadGroupSharedFile({groupId:this.groupId,...e})}setMemberAttributes(e){return this.manager.setGroupMemberAttributes({groupId:this.groupId,userId:e.userId,memberAttributes:e.memberAttributes})}getMembersAttributes(e){return this.manager.getGroupMembersAttributes({groupId:this.groupId,userIds:e.userIds,keys:e.keys})}toTarget(){return{groupId:this.groupId}}toUserBatchParams(e){return{groupId:this.groupId,userIds:e.userIds}}}const MT=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},UT=e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),LT=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),kT=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw UT(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw LT(`${t}[${n}]`,`${t}[${n}] must be a string`);const i=e.trim();i&&!s.has(i)&&(s.add(i),r.push(i))}),0===r.length)throw UT(t);return r},DT=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw UT(t);return e.trim()},PT=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw LT(t,`${t} must be a string`);return e}},xT=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw LT(t,`${t} must be a boolean`);return e}},FT=(e,t)=>`/${e.orgName}/${e.appName}${t}`,BT=new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),GT=e=>{const t=Qy();"number"==typeof e?.pageNum&&t.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize));const r=t.toString();return r?`?${r}`:""},qT=async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups?resource=${s.encodedResource}`);return(e=>{const t=Eu(e),r=bu(t[0]),s=wu(e)??r;return{groupId:s&&Nu(s)||r&&Nu(r)||""}})(await e.post(n,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?kT(r.memberIds,"params.memberIds"):[],public:r.public,approval:r.joinApprovalRequired,allowinvites:r.allowInvites,invite_need_confirm:r.inviteNeedConfirm,maxusers:r.maxMembers,custom:r.ext,avatar:r.avatar},{operation:"createGroup"}))},$T=async(e,t,r)=>{const s=MT(t),n=DT(r.groupId,"params.groupId"),i=FT(s,`/chatgroups/${encodeURIComponent(n)}?joined_time=true&version=v3`),o=await e.get(i,{operation:"getGroupInfo"});return Mu(o)},jT=async(e,t,r)=>{const s=MT(t),n=DT(r.groupId,"params.groupId"),i={},o=PT(r.name,"params.name"),a=PT(r.description,"params.description"),c=PT(r.avatar,"params.avatar"),d=PT(r.ext,"params.ext"),u=xT(r.public,"params.public"),l=xT(r.joinApprovalRequired,"params.joinApprovalRequired"),h=xT(r.allowInvites,"params.allowInvites"),p=xT(r.inviteNeedConfirm,"params.inviteNeedConfirm"),m=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw LT(t,`${t} must be a number`);return e}})(r.maxMembers,"params.maxMembers");if(void 0!==o&&(i.groupname=o),void 0!==a&&(i.description=a),void 0!==c&&(i.avatar=c),void 0!==d&&(i.custom=d),void 0!==u&&(i.public=u),void 0!==l&&(i.membersonly=l),void 0!==h&&(i.allowinvites=h),void 0!==p&&(i.invite_need_confirm=p),void 0!==m&&(i.maxusers=m),0===Object.keys(i).length)throw UT("params");const f=FT(s,`/chatgroups/${encodeURIComponent(n)}?resource=${s.encodedResource}&version=v3`);await e.put(f,i,{operation:"updateGroupInfo"})},VT=async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/users${(e=>{const t=Qy();return"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor),t.set("version","v3"),`?${t.toString()}`})(r)}`);return(e=>{const t=[];for(const i of Eu(e)){const e=bu(i);if(!e)continue;const r=Tu(e.owner),s=Tu(e.admin),n=Tu(e.member),o=r??s??n;if(!o)continue;const a=Cu(e.joinedAt)??Cu(e.joined_time);t.push({user:Uu(o),role:r?"owner":s?"admin":"member",...void 0===a?{}:{joinedAt:a}})}const r=Ru(e,"pagenum"),s=Ru(e,"pagesize"),n=Au(e,s);return{items:t,pageNum:r,pageSize:s,...void 0===n?{}:{hasMore:n}}})(await e.get(n,{operation:"getGroupMemberList"}))},KT=async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/admin`),i=await e.get(n,{operation:"getGroupAdminList"});return Lu(i)},zT=async(e,t,r)=>{const s=MT(t),n=DT(r.groupId,"params.groupId"),i=GT(r),o=i?"&":"",a=FT(s,`/chatgroups/${encodeURIComponent(n)}/mute?version=v3${o}${i.replace("?","")}`);return(e=>{const t=[];for(const r of Eu(e)){const e=Tu(r);if(e){t.push({user:Uu(e)});continue}const s=bu(r);if(!s)continue;const n=Tu(s.user);if(!n)continue;const i=Cu(s.expire);t.push({user:Uu(n),...void 0===i?{}:{muteExpire:i}})}return t})(await e.get(a,{operation:"getGroupMuteList"}))},HT=async(e,t,r)=>{const s=MT(t),n=DT(r.groupId,"params.groupId"),i=GT(r),o=i?"&":"",a=FT(s,`/chatgroups/${encodeURIComponent(n)}/blocks/users?version=v3${o}${i.replace("?","")}`),c=await e.get(a,{operation:"getGroupBlocklist"});return Lu(c).map(e=>({user:e}))},WT=async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/white/users`),i=await e.get(n,{operation:"getGroupAllowlist"});return Lu(i).map(e=>({user:e}))},JT=async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=wu(e)??{};return{announcement:_u(t.announcement)??""}})(await e.get(n,{operation:"getGroupAnnouncement"}))},QT=async(e,t,r)=>{const s=MT(t),n=Qy();n.set("pagenum",String(r.pageNum??1)),n.set("pagesize",String(r.pageSize??20));const i=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/share_files?${n.toString()}`);return(e=>{const t=Ru(e,"pagenum"),r=Ru(e,"pagesize"),s=Au(e,r);return{items:Eu(e).map(e=>ku(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===s?{}:{hasMore:s}}})(await e.get(i,{operation:"getGroupSharedFileList"}))},ZT=(e,t)=>{const r=MT(e);return FT(r,`/chatgroups/${encodeURIComponent(DT(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(DT(t.fileId,"params.fileId"))}`)},YT=async(e,t,r)=>{const s=MT(t),n=DT(r.groupId,"params.groupId"),i=DT(r.userId,"params.userId"),o=((e,t,r)=>{if(t!==e.userId)return null;const s=Object.entries(r);if(0===s.length)return null;let n;for(const[i,o]of s){if(!BT.has(i)||"string"!=typeof o)return null;if(void 0!==n){if(n!==o)return null}else n=o}return void 0===n?null:{nameCard:n}})(t,i,r.memberAttributes);if(o){const t=FT(s,`/sdk/chatgroups/${encodeURIComponent(n)}/nameCard`);return await e.put(t,o,{operation:"setGroupMemberAttributes"})}const a=FT(s,`/sdk/metadata/chatgroup/${encodeURIComponent(n)}/user/${encodeURIComponent(i)}?resource=${s.encodedResource}`);return await e.put(a,{metaData:r.memberAttributes},{operation:"setGroupMemberAttributes"})},XT=async(e,t,r)=>{const s=MT(t),n=FT(s,`/sdk/metadata/chatgroup/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/get`);return(e=>{const t=wu(e)??{},r=bu(t.data)??t,s={};for(const[n,i]of Object.entries(r)){const e=bu(i);e&&(s[n]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:s}})(await e.post(n,{targets:kT(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},eC=e=>{const t=pu(e)?e:{},r=t.data,s=pu(r)?r.data:void 0,n=Array.isArray(r)?r:Array.isArray(s)?s:null;if(Array.isArray(n))return tC(n);const i=pu(r)?r:t,o=pu(i.namecards)?i.namecards:i,a={};for(const[c,d]of Object.entries(o)){if("string"==typeof d){a[c]={namecard:d};continue}if(!pu(d))continue;const e=d.namecard??d.nameCard??d.groupNamecard??d.group_namecard??d.group_name_card;"string"==typeof e&&(a[c]={namecard:e,namecardUpdateTime:rC(d)})}return a},tC=e=>{const t={};return e.forEach(e=>{if(!pu(e))return;const r=e.username??e.userId??e.userid??e.user_id,s=e.name_card??e.namecard??e.nameCard??e.groupNamecard??e.group_namecard??e.group_name_card;"string"==typeof r&&r.trim()&&"string"==typeof s&&(t[r.trim()]={namecard:s,namecardUpdateTime:rC(e)})}),t},rC=e=>bl("number"==typeof e.update_timestamp?e.update_timestamp:"number"==typeof e.updateTimestamp?e.updateTimestamp:"number"==typeof e.timestamp?e.timestamp:"number"==typeof e.lastModified?e.lastModified:"number"==typeof e.last_modified?e.last_modified:void 0),sC=e=>{if(pu(e))return bl("number"==typeof e.timestamp?e.timestamp:"number"==typeof e.update_timestamp?e.update_timestamp:"number"==typeof e.updateTimestamp?e.updateTimestamp:"number"==typeof e.lastModified?e.lastModified:"number"==typeof e.last_modified?e.last_modified:void 0)};class nC{constructor(e){this.repository=e}applyPatch(e){e.shouldMarkStale&&this.repository.markStale(e.groupId);const t=this.repository.getDetailSnapshot(e.groupId);if(!e.groupPatch)return t;const r=t??{groupId:e.groupId,name:e.groupPatch.name??e.groupName??""};return this.repository.mergeDetail({...r,...e.groupPatch,groupId:e.groupId})}}const iC=e=>({...e}),oC=e=>({...e,owner:e.owner?{...e.owner}:void 0});class aC{constructor(e){this.summarySnapshot=null,this.detailSnapshot=null,this.loadedSummary=!1,this.stale=!1,this.loadedDetail=!1,this.lastPatchedAt=null,this.lastHydratedAt=null,this.groupId=e}mergeSummary(e){e.groupId===this.groupId&&(this.summarySnapshot=iC({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=oC({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=iC(this.toSummaryFromDetail(this.detailSnapshot)),this.loadedSummary=!0,this.loadedDetail=!0,this.stale=!1,this.lastPatchedAt=Date.now(),this.lastHydratedAt=Date.now())}markStale(){this.stale=!0,this.lastPatchedAt=Date.now()}clear(){this.summarySnapshot=null,this.detailSnapshot=null,this.loadedSummary=!1,this.stale=!1,this.loadedDetail=!1,this.lastPatchedAt=null,this.lastHydratedAt=null}getSummarySnapshot(){return this.summarySnapshot?iC(this.summarySnapshot):this.detailSnapshot?iC(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?oC(this.detailSnapshot):null}isStale(){return this.stale}hasLoadedSummary(){return this.loadedSummary}hasLoadedDetail(){return this.loadedDetail}getLastPatchedAt(){return this.lastPatchedAt}getLastHydratedAt(){return this.lastHydratedAt}toSummaryFromDetail(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,public:e.public,joinApprovalRequired:e.joinApprovalRequired,allowInvites:e.allowInvites,maxMembers:e.maxMembers,role:e.role,disabled:e.disabled}}}class cC{toSummary(e){const t=e.getSummarySnapshot();return t?(e=>({...e}))(t):null}toDetail(e){const t=e.getDetailSnapshot();return t?(e=>({...e,owner:e.owner?{...e.owner}:void 0}))(t):null}}class dC{constructor(){this.groups=new Map,this.joinedGroupById=new Map,this.removedJoinedGroupIds=new Set,this.snapshotMapper=new cC,this.joinedGroupSnapshot=null,this.sessionKey=null}ensureSession(e){return this.sessionKey!==e&&(this.sessionKey=e,this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null,!0)}getSessionKey(){return this.sessionKey}getOrCreate(e){const t=this.groups.get(e);if(t)return t;const r=new aC(e);return this.groups.set(e,r),r}mergeSummary(e){return this.getOrCreate(e.groupId).mergeSummary(e),this.getSummarySnapshot(e.groupId)??{...e}}mergeSummaries(e){return e.map(e=>this.mergeSummary(e))}applyJoinedGroupSnapshot(e){const t=e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId));this.joinedGroupSnapshot={items:t.map(e=>({...e})),meta:{...e.meta}},this.joinedGroupById.clear();for(const r of t){const e={...r};this.joinedGroupById.set(e.groupId,e),this.mergeSummary(this.toGroupSummary(e))}}getJoinedGroupSnapshot(e){return this.joinedGroupSnapshot?{items:this.joinedGroupSnapshot.items.map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}}:e?{items:e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId)).map(e=>({...e})),meta:{...e.meta}}:{items:[],meta:{integrity:"unknown",limited:!1,storageLimit:100,serverLimit:3e3,source:"sync"}}}getJoinedGroupSummarySnapshot(e,t){const r=this.joinedGroupById.get(e);if(r)return{...r};if(this.removedJoinedGroupIds.has(e))return null;const s=t?.items.find(t=>t.groupId===e);return s?{...s}:null}addJoinedGroupIfAbsent(e,t){const r=this.getJoinedGroupSnapshot(t);return r.items.some(t=>t.groupId===e.groupId)?null:(this.removedJoinedGroupIds.delete(e.groupId),this.applyJoinedGroupSnapshot({items:[{...e},...r.items],meta:{...r.meta}}),this.getJoinedGroupSnapshot())}mergeJoinedGroupSummary(e,t){const r=this.joinedGroupById.get(e);if(!r||!this.joinedGroupSnapshot)return null;const s={...r,...t,groupId:e};return this.joinedGroupById.set(e,s),this.mergeSummary(this.toGroupSummary(s)),this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.map(t=>t.groupId===e?{...s}:{...t}),meta:{...this.joinedGroupSnapshot.meta}},this.getJoinedGroupSnapshot()}mergeDetail(e){const t=this.mergeJoinedGroupFieldsIntoDetail(e);return this.getOrCreate(t.groupId).mergeDetail(t),this.getDetailSnapshot(t.groupId)??{...t}}mergeDetails(e){return e.map(e=>this.mergeDetail(e))}getSummarySnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toSummary(t):null}getDetailSnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toDetail(t):null}hasFreshDetail(e){const t=this.groups.get(e);return Boolean(t&&t.hasLoadedDetail()&&!t.isStale())}markStale(e){this.getOrCreate(e).markStale()}delete(e){this.groups.delete(e),this.joinedGroupById.delete(e),this.joinedGroupSnapshot&&(this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.filter(t=>t.groupId!==e).map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}})}markJoinedGroupRemoved(e){this.removedJoinedGroupIds.add(e),this.delete(e)}clear(){this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null}mergeJoinedGroupFieldsIntoDetail(e){const t=this.joinedGroupById.get(e.groupId);return t&&void 0===e.joinedAt&&void 0!==t.joinedAt?{...e,joinedAt:t.joinedAt}:e}toGroupSummary(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,role:e.role,disabled:e.disabled}}}const uC=0,lC=5,hC=12,pC=13,mC=0,fC=1,gC=2,yC=0,vC=1,IC=2,bC=3,_C=e=>{const t=e.group_id?.trim();return t?{groupId:t,name:e.group_name??"",description:e.description,memberCount:e.members_count,role:(s=e.role,s===mC?"owner":s===fC?"admin":s===gC?"member":void 0),disabled:e.disabled,ownerId:e.group_owner,avatarUrl:e.group_avatar,muteAllMembers:e.mute_all,muteExpiration:e.mute_expiration,remindType:(r=e.remind_type,r===yC?"DEFAULT":r===vC?"ALL":r===IC?"AT":r===bC?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,s},TC=e=>e.updatedAt??0,CC=(e,t)=>{if(!e)return!0;return TC(t)>=TC(e)},SC={nested:{easemob:{nested:{joinedgroups:{nested:{GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},request_id:{type:"string",id:3},protocol_version:{type:"int32",id:4}}},GetJoinedGroupsRequest:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},last_sync_time:{type:"int64",id:6},cursor:{type:"string",id:7}}},GroupItem:{fields:{group_id:{type:"string",id:1},group_name:{type:"string",id:2},group_owner:{type:"string",id:3},members_count:{type:"int64",id:4},mute_all:{type:"bool",id:5},disabled:{type:"bool",id:6},description:{type:"string",id:7},group_avatar:{type:"string",id:8},role:{type:"uint32",id:9},mute_expiration:{type:"int64",id:10},remind_type:{type:"int32",id:11},create_at:{type:"uint64",id:12},update_at:{type:"uint64",id:13},joined_timestamp:{type:"int64",id:14}}},GetJoinedGroupsResponse:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},groups:{rule:"repeated",type:"GroupItem",id:3},is_last_batch:{type:"bool",id:4},last_sync_finished_ts:{type:"int64",id:5},cursor:{type:"string",id:6}}},ErrorDetail:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},code:{type:"uint32",id:3},message:{type:"string",id:4}}}}}}}}};let EC=null,wC=!1;const RC=()=>EC||(wC||(fa.util.Long=Dn,fa.configure(),wC=!0),Va(),EC=fa.Root.fromJSON(SC),ja(EC),EC),AC=e=>RC().lookupType(e),NC=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}if(Dn.isLong(e))return e.toNumber();if(e&&"object"==typeof e&&"toString"in e&&"function"==typeof e.toString){const t=Number(e.toString());return Number.isFinite(t)?t:void 0}},OC=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:NC(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:NC(t.protocol_version)??NC(t.protocolVersion)??0}};class MC{constructor(){this.requestType=AC("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=AC("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=AC("easemob.joinedgroups.ErrorDetail")}encodeRequest(e){const t=this.requestType.create({type:e.type,header:e.header?{resource:e.header.resource,timestamp:e.header.timestamp,request_id:e.header.requestId,protocol_version:e.header.protocolVersion}:void 0,org:e.org,app:e.app,username:e.username,last_sync_time:e.lastSyncTime??0,cursor:e.cursor});return this.requestType.encode(t).finish()}decode(e){const t=this.tryDecodeError(e);if(t)return t;const r=this.tryDecodeResponse(e);if(r)return r;const s=this.tryDecodeRequest(e);return s||{type:uC}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=NC(t.type);return r!==hC?null:{type:r,header:OC(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:NC(t.last_sync_time)??NC(t.lastSyncTime)??0,cursor:"string"==typeof t.cursor?t.cursor:void 0}}catch{return null}}tryDecodeResponse(e){try{const t=this.responseType.toObject(this.responseType.decode(e),{longs:String,bytes:Uint8Array}),r=NC(t.type);return r!==pC?null:{type:r,header:OC(t.header),groups:Array.isArray(t.groups)?t.groups.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{group_id:"string"==typeof t.group_id?t.group_id:"string"==typeof t.groupId?t.groupId:void 0,group_name:"string"==typeof t.group_name?t.group_name:"string"==typeof t.groupName?t.groupName:void 0,group_owner:"string"==typeof t.group_owner?t.group_owner:"string"==typeof t.groupOwner?t.groupOwner:void 0,members_count:NC(t.members_count)??NC(t.membersCount),mute_all:"boolean"==typeof t.mute_all?t.mute_all:"boolean"==typeof t.muteAll?t.muteAll:void 0,disabled:"boolean"==typeof t.disabled?t.disabled:void 0,description:"string"==typeof t.description?t.description:void 0,group_avatar:"string"==typeof t.group_avatar?t.group_avatar:"string"==typeof t.groupAvatar?t.groupAvatar:void 0,role:NC(t.role),mute_expiration:NC(t.mute_expiration)??NC(t.muteExpiration),remind_type:NC(t.remind_type)??NC(t.remindType),create_at:NC(t.create_at)??NC(t.createAt),update_at:NC(t.update_at)??NC(t.updateAt),joined_timestamp:NC(t.joined_timestamp)??NC(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:NC(t.last_sync_finished_ts)??NC(t.lastSyncFinishedTs),cursor:"string"==typeof t.cursor?t.cursor:void 0}}catch{return null}}tryDecodeError(e){try{const t=this.errorType.toObject(this.errorType.decode(e),{longs:String,bytes:Uint8Array}),r=NC(t.type);return r!==lC?null:{type:r,header:OC(t.header),code:NC(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class UC{constructor(e){this.batches=[],this.done=!1,this.requestId=e}getResumeCursor(){return this.latestCursor}push(e){if(e.type!==pC)return{done:!1};const t=e.header?.requestId;if(t!==this.requestId)return{done:!1};if(this.done)throw new ut("Joined groups response received after completion",ot.REST_BUSINESS_UNKNOWN,{details:{stage:"response_decode",requestId:this.requestId}});if(this.batches.push(e),e.cursor&&(this.latestCursor=e.cursor),e.isLastBatch){if("number"!=typeof e.lastSyncFinishedTs)throw new ut("Joined groups final batch missing lastSyncFinishedTs",ot.REST_BUSINESS_UNKNOWN,{details:{stage:"completion_meta",requestId:this.requestId}});this.done=!0,this.lastSyncFinishedTs=e.lastSyncFinishedTs}return{done:this.done}}buildResult(){return{batches:this.batches.map(e=>({...e,groups:e.groups.map(e=>({...e}))})),lastSyncFinishedTs:this.lastSyncFinishedTs}}}const LC=e=>e.type===pC,kC=e=>e.type===lC;class DC{constructor(e){this.codec=new MC,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new UC(t);return await this.syncWithSharedSession(e.request,t,r)}cancel(){this.sharedSession.cancel("group-sync-cancelled")}async syncWithSharedSession(e,t,r){return await this.sharedSession.request({dataType:"group",label:"Group sync",requestId:t,encode:()=>this.codec.encodeRequest(this.buildAttemptRequest(e,t,r.getResumeCursor())),decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:LC(t)||kC(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(LC(e)){if(!r.push(e).done)return;return{done:!0,result:r.buildResult()}}if(kC(e))throw(e=>{const t=(t,r)=>({stage:t,serverCode:e.code,requestId:e.header?.requestId,retryable:r});switch(e.code){case 1601:return new ut(e.message,ot.VALIDATION_REQUIRED,{details:t("request_send",!1)});case 1602:return new ut(e.message,ot.REST_BUSINESS_UNKNOWN,{details:t("batch_merge",!0)});case 1002:return new pt(e.message,{code:ot.AUTH_UNAUTHORIZED,details:t("auth",!1)});case 1003:return new ut(e.message,ot.SERVICE_LIMIT_EXCEEDED,{details:t("server_limit",!0)});default:return new ut(e.message,ot.REST_BUSINESS_UNKNOWN,{details:t("response_decode",!0)})}})(e);return}catch(t){throw t instanceof ut?t:new ut("Joined groups frame decode failed",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:t instanceof Error?t.message:String(t)}})}}})}buildAttemptRequest(e,t,r){return{...e,cursor:r,lastSyncTime:0,header:{resource:e.header?.resource??"",timestamp:Date.now(),requestId:t,protocolVersion:e.header?.protocolVersion??1}}}}class PC{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("group-sync-cancelled")}async runSync(){this.dependencies.onStart();const e=Date.now();try{const r=await this.dependencies.getSyncUrls();if(0===r.length)throw new ut("Group sync websocket urls are unavailable",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",retryable:!0}});const s=this.buildRequest(),n=await new DC(this.dependencies.getSharedSyncSession()).sync({urls:r,request:s}),i=n.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=_C(r);e&&t.push(e)}return t})(e.groups)),o=this.dependencies.getRuntimeSnapshot(),a=(e=>{const t=new Map(e.existingItems.map(e=>[e.groupId,e])),r=new Map;for(const n of e.incomingItems){const e=r.get(n.groupId)??t.get(n.groupId);CC(e,n)?r.set(n.groupId,{...e??{},...n,groupId:n.groupId}):e&&r.set(n.groupId,{...e})}const s=r.size>=lm;return{items:Array.from(s?e.existingItems.map(e=>({...e})):r.values()).sort((e,t)=>{const r=(t.joinedAt??0)-(e.joinedAt??0);return 0!==r?r:e.groupId.localeCompare(t.groupId)}),meta:{integrity:s?"limited":"synced",limited:s,storageLimit:um,serverLimit:lm,source:"sync",lastSyncFinishedTs:e.lastSyncFinishedTs,lastSuccessfulAt:Date.now()}}})({existingItems:o?.items??[],incomingItems:i,lastSyncFinishedTs:n.lastSyncFinishedTs}),c=this.dependencies.getCacheManager();this.dependencies.applyRuntimeSnapshot(a);const d=this.dependencies.getRuntimeSnapshot()??a;try{await c.commitJoinedGroupPreviewSnapshot(d);const e=this.dependencies.getRuntimeSnapshot();e&&!this.hasSameMembership(d,e)&&await c.commitJoinedGroupPreviewSnapshot(e)}catch(t){throw o&&this.dependencies.applyRuntimeSnapshot(o),new yt("Joined-group preview persistence failed",{details:{stage:"preview_persist",cause:t instanceof Error?t.message:String(t)}})}Vs("Group sync finished",{durationMs:Date.now()-e,itemCount:a.items.length,limited:a.meta.limited}),this.dependencies.onFinish({status:"success"})}catch(t){const r=(e=>{const t=e instanceof ut?e:new ut("Group sync failed",ot.REST_BUSINESS_UNKNOWN,{details:{stage:"socket_connect",cause:e instanceof Error?e.message:String(e)}}),r=t.details??{},s=r.serverCode;return{dataType:"group",code:t.code,stage:(n=r.stage,"config"===n||"socket_connect"===n||"request_send"===n||"response_decode"===n||"batch_merge"===n||"preview_persist"===n||"completion_meta"===n||"auth"===n||"server_limit"===n||"cancelled"===n?n:"socket_connect"),message:t.message,retryable:!0===r.retryable,serverCode:"number"==typeof s||"string"==typeof s?s:void 0};var n})(t);Vs("Group sync failed",{durationMs:Date.now()-e,stage:r.stage,code:r.code,serverCode:r.serverCode}),this.dependencies.onFinish({status:"failed",error:r})}}hasSameMembership(e,t){if(e.items.length!==t.items.length)return!1;const r=new Set(t.items.map(e=>e.groupId));return e.items.every(e=>r.has(e.groupId))}buildRequest(){const e=this.dependencies.getRestContext(),{orgName:t,appName:r}=fs(e.appKey);return{type:hC,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:t,app:r,username:e.userId,lastSyncTime:0}}}const xC=bv(_v,{common:{},apis:{createGroup:{range:"4,110,204,608",errors:{invalid_parameter:{code:110,httpStatus:400,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},exceed_limit:{code:4,httpStatus:403,retryable:!1},group_name_violation:{code:608,httpStatus:403,retryable:!1,aliases:["INVALID_GROUP_NAME"]},resource_not_found:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","username_not_found"]}}},getJoinedGroupList:{range:"",errors:{}},getGroupInfo:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupInfoList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},updateGroupInfo:{range:"110,603,606,607,608",errors:{group_authorization:{code:603,httpStatus:403,retryable:!1},forbidden_op:{code:603,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},exceed_limit:{code:110,httpStatus:403,retryable:!1},group_name_violation:{code:608,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1},group_disabled:{code:607,httpStatus:403,retryable:!1}}},changeGroupOwner:{range:"603,606",errors:{forbidden_op:{code:603,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1}}},destroyGroup:{range:"603,606,607",errors:{group_authorization:{code:603,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1},group_disabled:{code:607,httpStatus:403,retryable:!1}}},leaveGroup:{range:"602,603,606",errors:{not_joined:{code:602,retryable:!1,aliases:["GROUP_NOT_JOINED","group_not_joined"]},owner_cannot_leave:{code:603,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"owner can not quit group"},resource_not_found:{code:606,httpStatus:404,retryable:!1}}},joinGroup:{range:"600-607,613",errors:{group_invalid_id:{code:600,retryable:!1,aliases:["GROUP_INVALID_ID"]},already_joined:{code:601,retryable:!1,aliases:["ALREADY_JOINED","GROUP_ALREADY_JOINED","group_already_joined"]},not_joined:{code:602,retryable:!1,aliases:["GROUP_NOT_JOINED","group_not_joined"]},group_authorization:{code:603,httpStatus:403,retryable:!1,aliases:["NEED_APPROVAL","GROUP_PERMISSION_DENIED"]},group_full:{code:604,httpStatus:403,retryable:!1,aliases:["GROUP_FULL","GROUP_MEMBERS_FULL"],matchField:"error_description",matchPattern:"member list is full"},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["GROUP_NOT_FOUND","service_resource_not_found"]},group_disabled:{code:607,retryable:!1,aliases:["GROUP_DISABLED"]},group_user_in_blocklist:{code:613,httpStatus:403,retryable:!1,aliases:["GROUP_USER_IN_BLOCKLIST"],matchField:"error_description",matchPattern:"is in the blacklist"}}},inviteUsersToGroup:{range:"204,603,606,607",errors:{group_authorization:{code:603,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","username_not_found"]},group_not_found:{code:606,retryable:!1,aliases:["GROUP_NOT_FOUND"]},group_disabled:{code:607,retryable:!1}}},acceptGroupJoinRequest:{range:"",errors:{}},rejectGroupJoinRequest:{range:"",errors:{}},acceptInvitation:{range:"",errors:{}},rejectInvitation:{range:"",errors:{}},removeGroupMembers:{range:"",errors:{}},addGroupAdmin:{range:"",errors:{}},removeGroupAdmin:{range:"",errors:{}},muteGroupMembers:{range:"",errors:{}},unmuteGroupMembers:{range:"",errors:{}},muteAllGroupMembers:{range:"",errors:{}},unmuteAllGroupMembers:{range:"",errors:{}},blockGroupMembers:{range:"",errors:{}},unblockGroupMembers:{range:"",errors:{}},addUsersToGroupAllowlist:{range:"",errors:{}},removeUsersFromGroupAllowlist:{range:"",errors:{}},checkIfInGroupAllowList:{range:"",errors:{}},getGroupMemberList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},getGroupAdminList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupMuteList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},checkIfInGroupMuteList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupBlocklist:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupAllowlist:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupAnnouncement:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},updateGroupAnnouncement:{range:"110",errors:{announcement_length_exceeded:{code:110,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"announce into length exceeds limit"},announcement_info_length_exceeded:{code:110,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"announce info length exceeds limit"}}},getGroupSharedFileList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["RestGroupFeignException"]}}},deleteGroupSharedFile:{range:"603,605,606",errors:{group_authorization:{code:603,retryable:!1},file_not_found:{code:605,retryable:!1,aliases:["GROUP_SHARED_FILE_INVALID_ID"]},resource_not_found:{code:606,retryable:!1}}},setGroupMemberAttributes:{range:"4,210,302,305,602,609-612",errors:{attributes_reach_limit:{code:609,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_REACH_LIMIT"],matchField:"error_code",matchValue:60006},attributes_update_failed:{code:610,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_UPDATE_FAILED"],matchField:"error_code",matchValue:60005},attributes_key_reach_limit:{code:611,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_KEY_REACH_LIMIT"],matchField:"error_code",matchValue:60009},attributes_value_reach_limit:{code:612,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_VALUE_REACH_LIMIT"],matchField:"error_code",matchValue:600010},not_joined:{code:602,httpStatus:404,retryable:!1,matchField:"error_code",matchValue:60003},permission_denied:{code:210,httpStatus:401,retryable:!1,matchField:"error_code",matchValue:60001},permission_denied_403:{code:210,httpStatus:403,retryable:!1,matchField:"error_code",matchValue:60002},exceed_service_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60007},service_disabled:{code:305,httpStatus:403,retryable:!1,matchField:"error_code",matchValue:60004}}},getGroupMembersAttributes:{range:"606",errors:{resource_not_found:{code:606,retryable:!1}}},getGroupNamecards:{range:"",errors:{}}}}),FC=class{constructor(){this.capabilities=["rawNotify:group","group:namecard"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.groupRegistry=new Map,this.groupRepository=null,this.groupEventSync=null}bind(e,t){this.client=e,this.eventContext=t??null,this.groupRegistry.clear(),this.groupRepository=new dC,this.groupEventSync=new nC(this.groupRepository),this.ensureRepositorySession()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("group"!==e.type)return;const t=e.payload,r=t.eventName,s=await this.buildIncomingEventPayload(r,t);if(!s)return;if(this.eventContext?.dispatch?.(r,s),r!==Te)return;if(!("attribute"in s)||!("user"in s))return;const n=this.extractGroupNamecard(s.attribute);if(void 0===n||!s.user?.userId)return;const i=this.client?.getCurrentUserId();s.user.userId!==i&&(this.getCacheManager()?.setGroupNamecards([{groupId:s.groupId,userId:s.user.userId,namecard:n,lastAccess:Date.now(),lastUpdate:Date.now()}]),this.eventContext?.dispatch?.(Ce,{groupId:s.groupId,userId:s.user.userId,namecard:n}))}async createGroup(e){return this.runOperation("createGroup",async()=>{const t=this.getRestContextOrThrow(),r=await qT(this.getRestClient(t),t,e);return this.ensureRepositorySession(),this.addJoinedGroupIfAbsent({groupId:r.groupId,name:e.name,role:"owner",ownerId:t.userId,...void 0===e.description?{}:{description:e.description},...void 0===e.avatar?{}:{avatarUrl:e.avatar}}),r})}getJoinedGroupList(){return this.getJoinedGroupSnapshotForSync().items}getJoinedGroupSnapshotForSync(){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSnapshot(this.loadJoinedGroupPreviewSnapshot())}applyJoinedGroupSnapshot(e){this.ensureRepositorySession(),this.getGroupRepository().applyJoinedGroupSnapshot(e)}getGroupSummaryForHandle(e){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())}getGroup(e){this.requireClient(),this.ensureRepositorySession();const t=e.trim();if(0===t.length)throw new mt("groupId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"groupId",message:"groupId is required",rule:"required"}]}});const r=this.groupRegistry.get(t);if(r)return r;this.getGroupSummaryForHandle(t),this.getGroupRepository().getOrCreate(t);const s=new OT(t,this);return this.groupRegistry.set(t,s),s}async getGroupInfo(e){return this.runOperation("getGroupInfo",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow(),r=await $T(this.getRestClient(t),t,e),s=await this.hydrateGroupDetailUsers(r);return this.getGroupRepository().mergeDetail(s)})}async getGroupInfoList(e){return this.runOperation("getGroupInfoList",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=MT(t),n=kT(r.groupIds,"params.groupIds"),i=FT(s,`/chatgroups/${n.map(e=>encodeURIComponent(e)).join(",")}?joined_time=true&version=v3`),o=await e.get(i,{operation:"getGroupInfoList"});return(pu(o)&&Array.isArray(o.data)?o.data:[]).map(e=>Mu({data:[e]}))})(this.getRestClient(t),t,e),s=await this.hydrateGroupDetailsUsers(r);return this.getGroupRepository().mergeDetails(s)})}async getGroupDetailForHandle(e){this.ensureRepositorySession();const t=this.getGroupRepository();if(t.getOrCreate(e),t.hasFreshDetail(e)){const r=t.getDetailSnapshot(e);if(r)return r}return this.getGroupInfo({groupId:e})}async refreshGroupDetailForHandle(e){return this.ensureRepositorySession(),this.getGroupRepository().getOrCreate(e),this.getGroupInfo({groupId:e})}resetSessionRuntime(){this.groupRegistry.clear(),this.getGroupRepository().ensureSession(null)}async buildIncomingEventPayload(e,t){this.ensureRepositorySession();const r=t.payload,s=e===ie?this.resolveLocalGroupName(r.groupId):void 0,n=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(await this.syncRuntimeForEvent(e,r,n),e){case Y:return{groupId:r.groupId,groupName:r.groupName,inviter:this.pickEventUser(r.inviterId,n),reason:r.reason};case X:return{groupId:r.groupId,groupName:r.groupName,applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case ee:return{groupId:r.groupId,groupName:r.groupName,accepter:this.pickEventUser(r.accepterId,n)};case te:return{groupId:r.groupId,groupName:r.groupName,decliner:this.pickEventUser(r.declinerId,n),applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case re:case se:return{groupId:r.groupId,invitee:this.pickEventUser(r.inviteeId,n),reason:r.reason};case ne:return{groupId:r.groupId,groupName:r.groupName};case ie:return{groupId:r.groupId,groupName:r.groupName??s};case oe:return{groupId:r.groupId,inviter:this.pickEventUser(r.inviterId,n),inviteMessage:r.reason};case ae:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n),muteExpire:r.muteExpire};case ce:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n)};case de:case ue:return{groupId:r.groupId,allowlist:this.pickEventUsers(r.userIds,n)};case le:return{groupId:r.groupId,isMuted:Boolean(r.isMuted)};case he:case pe:return{groupId:r.groupId,administrator:this.pickEventUser(r.administratorId,n)};case me:return{groupId:r.groupId,newOwner:this.pickEventUser(r.newOwnerId,n),oldOwner:this.pickEventUser(r.oldOwnerId,n)};case fe:return{groupId:r.groupId,groupName:await this.resolveMembersJoinedGroupName(r),members:this.pickEventUsers(r.memberIds,n)};case ge:return{groupId:r.groupId,members:this.pickEventUsers(r.memberIds,n)};case ye:return{groupId:r.groupId,announcement:r.announcement??""};case ve:return{groupId:r.groupId,sharedFile:this.hydrateEventSharedFile(r.sharedFile,n)};case Ie:return{groupId:r.groupId,fileId:r.fileId??""};case be:return{groupId:r.groupId,groupInfo:await this.resolveGroupDetailForEvent(r)};case _e:{const e=await this.resolveGroupDetailForEvent(r),t=void 0===r.isDisabled?Boolean(e.disabled):Boolean(r.isDisabled);return{groupId:r.groupId,groupInfo:e,disabled:t}}case Te:return{groupId:r.groupId,user:this.pickEventUser(r.userId,n),attribute:r.attribute??{},from:r.from,source:r.source};default:return null}}async resolveGroupDetailForEvent(e){this.ensureRepositorySession();const t=void 0===e.isDisabled?e.groupPatch:{...e.groupPatch??{},disabled:e.isDisabled},r=this.getGroupEventSync().applyPatch({groupId:e.groupId,groupName:e.groupName,groupPatch:t,shouldMarkStale:e.shouldFetchGroupDetail});if(e.shouldFetchGroupDetail)try{return await this.getGroupInfo({groupId:e.groupId})}catch(n){Vs("GroupManager resolveGroupDetailForEvent fallback to snapshot",{groupId:e.groupId,error:n})}if(r)return r;const s=this.getGroupRepository().getDetailSnapshot(e.groupId);return s||{groupId:e.groupId,name:t?.name??e.groupName??"",...t??{}}}async updateGroupInfo(e){return this.runOperation("updateGroupInfo",async()=>{const t=this.getRestContextOrThrow();await jT(this.getRestClient(t),t,e)})}async changeGroupOwner(e){return this.runOperation("changeGroupOwner",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}?resource=${s.encodedResource}`);await e.put(n,{newowner:DT(r.newOwner,"params.newOwner")},{operation:"changeGroupOwner"})})(this.getRestClient(t),t,e)})}async destroyGroup(e){return this.runOperation("destroyGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}?version=v3&resource=${s.encodedResource}`);await e.delete(n,{operation:"destroyGroup"})})(this.getRestClient(t),t,e),await this.requireClient().handleGroupDestroyedConversation(e.groupId),await this.removeJoinedGroupLocal(e.groupId)})}async leaveGroup(e){return this.runOperation("leaveGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/quit?resource=${s.encodedResource}`);await e.delete(n,{operation:"leaveGroup"})})(this.getRestClient(t),t,e),await this.removeJoinedGroupLocal(e.groupId)})}async joinGroup(e){return this.runOperation("joinGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/apply?resource=${s.encodedResource}`);await e.post(n,{message:r.message??""},{operation:"joinGroup"})})(this.getRestClient(t),t,e)})}async inviteUsersToGroup(e){return this.runOperation("inviteUsersToGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/invite?resource=${s.encodedResource}`);await e.post(n,{usernames:kT(r.userIds,"params.userIds")},{operation:"inviteUsersToGroup"})})(this.getRestClient(t),t,e)})}async acceptGroupJoinRequest(e){return this.runOperation("acceptGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:DT(r.userId,"params.userId"),verifyResult:!0},{operation:"acceptGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async rejectGroupJoinRequest(e){return this.runOperation("rejectGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:DT(r.userId,"params.userId"),verifyResult:!1,reason:r.reason},{operation:"rejectGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async acceptInvitation(e){return this.runOperation("acceptInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/invite_verify?resource=${s.encodedResource}`);await e.post(n,{invitee:t.userId,verifyResult:!0},{operation:"acceptInvitation"})})(this.getRestClient(t),t,e)})}async rejectInvitation(e){return this.runOperation("rejectInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/invite_verify?resource=${s.encodedResource}`);await e.post(n,{invitee:t.userId,verifyResult:!1},{operation:"rejectInvitation"})})(this.getRestClient(t),t,e)})}async getGroupMemberList(e){return this.runOperation("getGroupMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await VT(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(e.groupId,r.items)}})}async removeGroupMembers(e){return this.runOperation("removeGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=kT(r.userIds,"params.userIds"),i=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"removeGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAdminList(e){return this.runOperation("getGroupAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await KT(this.getRestClient(t),t,e);return this.hydrateUserInfos(e.groupId,r)})}async addGroupAdmin(e){return this.runOperation("addGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/admin?resource=${s.encodedResource}`);await e.post(n,{newadmin:r.userId},{operation:"addGroupAdmin"})})(this.getRestClient(t),t,e)})}async removeGroupAdmin(e){return this.runOperation("removeGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/admin/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`);await e.delete(n,{operation:"removeGroupAdmin"})})(this.getRestClient(t),t,e)})}async getGroupMuteList(e){return this.runOperation("getGroupMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await zT(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async muteGroupMembers(e){return this.runOperation("muteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/mute?resource=${s.encodedResource}`);await e.post(n,{usernames:kT(r.userIds,"params.userIds"),mute_duration:r.muteDuration},{operation:"muteGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteGroupMembers(e){return this.runOperation("unmuteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=kT(r.userIds,"params.userIds"),i=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/mute/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"unmuteGroupMembers"})})(this.getRestClient(t),t,e)})}async muteAllGroupMembers(e){return this.runOperation("muteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/ban?resource=${s.encodedResource}`);await e.post(n,void 0,{operation:"muteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllGroupMembers(e){return this.runOperation("unmuteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/ban?resource=${s.encodedResource}`);await e.delete(n,{operation:"unmuteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupBlocklist(e){return this.runOperation("getGroupBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await HT(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async blockGroupMembers(e){return this.runOperation("blockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/blocks/users?resource=${s.encodedResource}`);await e.post(n,{usernames:kT(r.userIds,"params.userIds")},{operation:"blockGroupMembers"})})(this.getRestClient(t),t,e)})}async unblockGroupMembers(e){return this.runOperation("unblockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=kT(r.userIds,"params.userIds"),i=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/blocks/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"unblockGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAllowlist(e){return this.runOperation("getGroupAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await WT(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async addUsersToGroupAllowlist(e){return this.runOperation("addUsersToGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/white/users?resource=${s.encodedResource}`);await e.post(n,{usernames:kT(r.userIds,"params.userIds")},{operation:"addUsersToGroupAllowlist"})})(this.getRestClient(t),t,e)})}async removeUsersFromGroupAllowlist(e){return this.runOperation("removeUsersFromGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=kT(r.userIds,"params.userIds"),i=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/white/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"removeUsersFromGroupAllowlist"})})(this.getRestClient(t),t,e)})}async checkIfInGroupAllowList(e){return this.runOperation("checkIfInGroupAllowList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),i=await e.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof i?i:pu(i)&&"boolean"==typeof i.data?i.data:Boolean(i)})(this.getRestClient(t),t,e)})}async checkIfInGroupMuteList(e){return this.runOperation("checkIfInGroupMuteList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=MT(t),n=FT(s,`/sdk/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),i=await e.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof i?i:pu(i)&&"boolean"==typeof i.data?i.data:Boolean(i)})(this.getRestClient(t),t,e)})}async getGroupAnnouncement(e){return this.runOperation("getGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();return JT(this.getRestClient(t),t,e)})}async updateGroupAnnouncement(e){return this.runOperation("updateGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/announcement?resource=${s.encodedResource}`);await e.post(n,{announcement:r.announcement},{operation:"updateGroupAnnouncement"})})(this.getRestClient(t),t,e)})}async getGroupSharedFileList(e){return this.runOperation("getGroupSharedFileList",async()=>{const t=this.getRestContextOrThrow(),r=await QT(this.getRestClient(t),t,e),s=await this.resolveGroupContextUserInfoMap(e.groupId,r.items.map(e=>e.fileOwner).filter(e=>void 0!==e));return{...r,items:r.items.map(e=>({...e,fileOwner:e.fileOwner?.userId?s.get(e.fileOwner.userId)??e.fileOwner:e.fileOwner}))}})}async uploadGroupSharedFile(e){return this.runOperation("uploadGroupSharedFile",async()=>{const t=this.getRestContextOrThrow(),r=ZT(t,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),s=os({file:e.file}),n=Uh({operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"}),i=n?.startRequest({requestName:"GROUP_UPLOAD_SHAREDFILE",method:"POST",url:`${t.restBaseUrl}${r}`});try{const o=await(this.requireClient().getUploadAdapter()?.upload({url:`${t.restBaseUrl}${r}?resource=${encodeURIComponent(t.clientResource)}`,headers:{Authorization:`Bearer ${t.token}`,[ru]:tu()},source:s.source,timeoutMs:3e5,onProgress:e.onFileUploadProgress}));if(!o)throw new Error("platform upload adapter is unavailable");if(o.status<200||o.status>=300)throw new ut("uploadGroupSharedFile failed",ot.REST_HTTP_ERROR,{details:{status:o.status}});i?.finish({code:o.status,success:!0}),n?.finish({code:0,success:!0}),e.onFileUploadComplete?.(o.body)}catch(o){const t=Pd(o);throw i?.finish({code:t.code,success:!1,description:t.message}),n?.finish({code:t.code,success:!1,description:t.message}),t.code===ot.UPLOAD_ABORTED&&e.onFileUploadCanceled?.(),e.onFileUploadError?.(t),t}})}async deleteGroupSharedFile(e){return this.runOperation("deleteGroupSharedFile",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(DT(r.fileId,"params.fileId"))}?resource=${s.encodedResource}`);await e.delete(n,{operation:"deleteGroupSharedFile"})})(this.getRestClient(t),t,e)})}async downloadGroupSharedFile(e){return this.runOperation("downloadGroupSharedFile",async()=>{let t,r;try{const s=this.getRestContextOrThrow(),n=`${s.restBaseUrl}${ZT(s,e)}`;t=Uh({operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"}),r=t?.startRequest({requestName:"GROUP_DOWNLOAD_SHAREDFILE",method:"GET",url:n});const i=this.requireClient().getRequestAdapter();if(!i)throw new ut("downloadGroupSharedFile request adapter is unavailable",ot.REST_NETWORK_ERROR);const o=await i.request({url:n,method:"GET",headers:{Authorization:`Bearer ${s.token}`,...e.secret?{"Share-Secret":e.secret}:{},[ru]:tu()},responseType:"arraybuffer",timeoutMs:6e4});if(o.status<200||o.status>=300)throw r?.finish({code:o.status,success:!1,description:"downloadGroupSharedFile failed"}),t?.finish({code:o.status,success:!1,description:"downloadGroupSharedFile failed"}),new ut("downloadGroupSharedFile failed",ot.REST_HTTP_ERROR);r?.finish({code:o.status,success:!0}),t?.finish({code:0,success:!0});const a="undefined"!=typeof Blob?new Blob([o.data]):o.data;e.onFileDownloadComplete?.(a)}catch(s){const n=s instanceof ut?s.code:ot.REST_NETWORK_ERROR,i=s instanceof Error?s.message:String(s);throw r?.finish({code:n,success:!1,description:i}),t?.finish({code:n,success:!1,description:i}),e.onFileDownloadError?.(s),s}})}async setGroupMemberAttributes(e){return this.runOperation("setGroupMemberAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await YT(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return XT(this.getRestClient(t),t,e)})}async hydrateMessageProfileGroupNamecards(e,t){0!==t.length&&await this.runOperation("hydrateMessageProfileGroupNamecards",async()=>{const r=this.getRestContextOrThrow(),s=t.map(e=>e.userId),n=await(async(e,t,r)=>{const s=MT(t),n=FT(s,`/sdk/chatgroups/${encodeURIComponent(DT(r.groupId,"params.groupId"))}/nameCard/batch/get`),i=await e.post(n,{members:kT(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:eC(i),responseTimestamp:sC(i)}})(this.getRestClient(r),r,{groupId:e,userIds:s}),i=new Map(t.map(e=>[e.userId,e.namecardUpdateTime])),o=[],a=new Set;for(const[t,d]of Object.entries(n.items))a.add(t),o.push({groupId:e,userId:t,namecard:d.namecard,namecardUpdateTime:i.get(t)??d.namecardUpdateTime,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()});const c=s.filter(e=>!a.has(e));c.length>0&&"number"==typeof n.responseTimestamp&&o.push(...c.map(t=>({groupId:e,userId:t,namecard:"",namecardUpdateTime:n.responseTimestamp,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}))),this.getCacheManager()?.setGroupNamecards(o);for(const e of o)e.userId!==r.userId&&""!==e.namecard&&this.eventContext?.dispatch?.(Ce,{groupId:e.groupId,userId:e.userId,namecard:e.namecard});c.length>0&&"number"!=typeof n.responseTimestamp&&Vs("Group namecard hydration returned partial result",{groupId:e,requestedUserIds:s,missingUserIds:c})})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Vs(`GroupManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof ut?t:t instanceof Error?new ut(`GroupManager ${e} failed: ${t.message}`,ot.UNKNOWN):new ut(`GroupManager ${e} failed`,ot.UNKNOWN)}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Vf(e.restBaseUrl,{errorMap:xC,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new ut("GroupManager is not bound to client",ot.VALIDATION_REQUIRED);return this.client}getGroupRepository(){return this.groupRepository||(this.groupRepository=new dC),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new nC(this.getGroupRepository())),this.groupEventSync}ensureRepositorySession(){this.getGroupRepository().ensureSession(this.resolveRepositorySessionKey())&&this.groupRegistry.clear()}resolveRepositorySessionKey(){if(!this.client)return null;const e=this.client.getCurrentUserId();if(!e)return null;try{const e=this.client.getRestContext();return`${e.restBaseUrl}:${e.userId}:${e.token}:${e.clientResource}`}catch{return`pending:${e}`}}getCacheManager(){return this.client?.getCacheManager()??null}loadJoinedGroupPreviewSnapshot(){const e=this.getCacheManager();if(e&&"function"==typeof e.loadJoinedGroupPreviewSnapshot)return e.loadJoinedGroupPreviewSnapshot()}resolveLocalGroupName(e){const t=this.getGroupRepository(),r=t.getSummarySnapshot(e)?.name;if(r)return r;const s=t.getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())?.name;return s||void 0}async resolveMembersJoinedGroupName(e){const t=this.resolveUsableGroupName(this.resolveLocalGroupName(e.groupId),e.groupId);if(t)return t;const r=this.resolveUsableGroupName(e.groupName,e.groupId);if(r)return r;const s=this.getGroupRepository().getSessionKey();try{const t=this.getRestContextOrThrow(),r=await $T(this.getRestClient(t),t,{groupId:e.groupId}),n=this.getGroupRepository();if(n.getSessionKey()!==s)return;return n.mergeDetail(r),this.resolveUsableGroupName(r.name,e.groupId)}catch(n){return void Vs("Members joined group detail enrichment failed",{groupId:e.groupId,error:n})}}resolveUsableGroupName(e,t){const r=e?.trim();return r&&r!==t?r:void 0}writeSelfGroupNamecardCache(e,t,r){if(t.userId!==e)return;const s=this.extractGroupNamecard(t.memberAttributes);if("string"!=typeof s)return;const n=this.resolveGroupMemberAttributesUpdateTime(r,t.userId);"number"!=typeof n&&Vs("Group member attributes update response missing server update time",{groupId:t.groupId,userId:t.userId}),this.getCacheManager()?.setGroupNamecards([{groupId:t.groupId,userId:t.userId,namecard:s,namecardUpdateTime:n,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}])}resolveGroupMemberAttributesUpdateTime(e,t){const r=[];this.collectUpdateTimeCandidates(e,t,r);for(const s of r){const e=bl("number"==typeof s?s:Number(s));if("number"==typeof e)return e}}collectUpdateTimeCandidates(e,t,r){if(!pu(e))return;r.push(e.lastModified,e.last_modified,e.timestamp,e.updateTime,e.update_time,e.updatedAt,e.updated_at);const s=e.data;if(pu(s)){this.collectUpdateTimeCandidates(s,t,r);const e=s[t];pu(e)&&this.collectUpdateTimeCandidates(e,t,r)}const n=e.lastModified??e.last_modified;pu(n)&&r.push(n[t])}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}async resolveUserInfoMap(e){return Iu(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Vs("GroupManager user info fetch failed",{userIds:e,error:r}),[]}}})}collectEventUserIds(e){const t=e.payload,r=[t.inviterId,t.applicantId,t.accepterId,t.declinerId,t.inviteeId,t.administratorId,t.oldOwnerId,t.newOwnerId,t.userId,t.sharedFile?.fileOwner?.userId,...t.memberIds??[],...t.userIds??[]],s=[],n=new Set;for(const i of r){if("string"!=typeof i)continue;const e=i.trim();e&&!n.has(e)&&(n.add(e),s.push(e))}return s}pickEventUser(e,t){if(e)return vu(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>vu(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:vu(e.fileOwner,t.get(e.fileOwner.userId),e.fileOwner.userId)}:e}async syncRuntimeForEvent(e,t,r){switch(e){case le:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{muteAllMembers:Boolean(t.isMuted)}});case me:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{owner:this.pickEventUser(t.newOwnerId,r)}});case ee:case oe:return void this.addCurrentUserJoinedGroupFromEvent(t);case fe:{let r=!1;if(t.memberIds?.includes(this.requireClient().getCurrentUserId()??"")&&(r=await this.addCurrentUserJoinedGroupFromEvent(t)),r)return;if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0})}case ge:if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,-this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});case ne:case ie:return void(await this.removeJoinedGroupLocal(t.groupId));case ae:case ce:case de:case ue:case he:case pe:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});default:return}}getMemberEventDeltaCount(e,t){switch(e){case fe:case ge:return t.memberIds?.length??0;default:return 0}}applyMemberCountDeltaPatch(e,t,r){if(0===r)return!1;const s=this.getGroupRepository().getDetailSnapshot(e);return!(!s||"number"!=typeof s.memberCount)&&(this.getGroupEventSync().applyPatch({groupId:e,groupName:t,groupPatch:{memberCount:Math.max(0,s.memberCount+r)}}),!0)}async removeJoinedGroupLocal(e){this.getGroupRepository().markJoinedGroupRemoved(e);const t=this.getCacheManager();t&&"function"==typeof t.removeJoinedGroupPreview&&await t.removeJoinedGroupPreview(e)}async addCurrentUserJoinedGroupFromEvent(e){if(!this.addJoinedGroupIfAbsent({groupId:e.groupId,name:e.groupName??"",role:"member"}))return!1;const t=this.getGroupRepository().getSessionKey();let r;try{r=this.getRestContextOrThrow()}catch(s){return Vs("Joined group detail enrichment skipped",{groupId:e.groupId,error:s}),!1}try{return await this.enrichJoinedGroupFromDetail(e.groupId,t,r)}catch(s){return Vs("Joined group detail enrichment failed",{groupId:e.groupId,error:s}),!1}}addJoinedGroupIfAbsent(e){const t=this.getGroupRepository().addJoinedGroupIfAbsent(e,this.loadJoinedGroupPreviewSnapshot());return!!t&&(this.persistJoinedGroupSnapshot(t),!0)}async enrichJoinedGroupFromDetail(e,t,r){const s=await $T(this.getRestClient(r),r,{groupId:e}),n=this.getGroupRepository();if(n.getSessionKey()!==t)return!1;n.mergeDetail(s);const i=n.getJoinedGroupSummarySnapshot(e);if(!i)return!1;const o=n.mergeJoinedGroupSummary(e,{...i.name||!s.name?{}:{name:s.name},...void 0!==i.description||void 0===s.description?{}:{description:s.description},...void 0!==i.memberCount||void 0===s.memberCount?{}:{memberCount:s.memberCount},...void 0!==i.role||void 0===s.role?{}:{role:s.role},...void 0!==i.disabled||void 0===s.disabled?{}:{disabled:s.disabled},...i.ownerId||!s.owner?.userId?{}:{ownerId:s.owner.userId},...void 0!==i.avatarUrl||void 0===s.avatarUrl?{}:{avatarUrl:s.avatarUrl},...void 0!==i.muteAllMembers||void 0===s.muteAllMembers?{}:{muteAllMembers:s.muteAllMembers},...void 0!==i.createdAt||void 0===s.createdAt?{}:{createdAt:s.createdAt},...void 0!==i.joinedAt||void 0===s.joinedAt?{}:{joinedAt:s.joinedAt}});if(o){this.persistJoinedGroupSnapshot(o);const t=n.getJoinedGroupSummarySnapshot(e);t&&this.requireClient().refreshConversationDisplayFromJoinedGroups([{...t,name:s.name||t.name,avatarUrl:s.avatarUrl??t.avatarUrl}],"profile",{onlyWhenNameMissing:!0})}return!0}persistJoinedGroupSnapshot(e){const t=this.getCacheManager();if(t&&"function"==typeof t.applyJoinedGroupPreviewSnapshot){try{t.applyJoinedGroupPreviewSnapshot(e)}catch(r){return void Vs("Joined group preview persistence failed",{error:r})}"function"==typeof t.flushPending&&t.flushPending().catch(e=>{Vs("Joined group preview flush failed",{error:e})})}}async hydrateUserInfos(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t);return t.map(e=>r.get(e.userId)??e)}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=q_(e),s=await this.getRestClient(t).request(B_(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return z_(s,r.targets)}async hydrateEntriesWithUsers(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t.map(e=>e.user));return t.map(e=>({...e,user:r.get(e.user.userId)??e.user}))}extractGroupNamecard(e){return e.groupNamecard??e.group_namecard??e.group_name_card??e.namecard}async hydrateGroupDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveGroupContextUserInfoMap(e.groupId,[e.owner]);return{...e,owner:t.get(e.owner.userId)??e.owner}}async hydrateGroupDetailsUsers(e){const t=e.filter(e=>Boolean(e.owner?.userId)).map(e=>({groupId:e.groupId,user:e.owner}));if(0===t.length)return e;const r=await this.resolveGroupUserInfoContexts(t);return e.map(e=>e.owner?.userId?{...e,owner:r.get(aI(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),s=await mI({groupId:e,users:t,includeNameCard:r,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return r&&this.dispatchFetchedUserInfoUpdates(s.fetchedUserInfos),s.usersById}async resolveGroupUserInfoContexts(e){const t=this.isGroupNamecardEnhancementEnabled(),r=await pI({contexts:e,includeNameCard:t,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return t&&this.dispatchFetchedUserInfoUpdates(r.fetchedUserInfos),r.usersByContextKey}async fetchGroupUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoManager();return t?await t.getUserInfoByUserId({userIds:e}):await this.fetchUserInfosFromRest(e)}isGroupNamecardEnhancementEnabled(){const e=this.requireClient(),t=e.isUserInfoSyncEnabled;return"function"==typeof t&&t.call(e)}dispatchFetchedUserInfoUpdates(e){if(0===e.length)return;const t=this.requireClient(),r=t.getCurrentUserId(),s=e.find(e=>e.userId===r),n=e.filter(e=>e.userId!==r);s&&t.dispatchOwnInfoUpdated?.(s),t.dispatchUserInfoUpdated?.(n),t.refreshConversationDisplayFromUserInfos?.(e.map(e=>({userId:e.userId})),"profile")}createSyncController(e){return new PC(e)}};FC.key="groupManager";let BC=FC;const GC=bv(_v,{common:{},apis:{publishPresence:{range:"1100",errors:{PRESENCE_PARAM_EXCEED:{code:1100,httpStatus:400,retryable:!1}}},subscribePresences:{range:"1100,1101",errors:{cannot_subscribe_yourself:{code:1101,httpStatus:400,retryable:!1,matchField:"result",matchPattern:"you can't sub yourself"},param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},unsubscribePresence:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getSubscribedPresenceList:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getPresenceStatus:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}}}}),qC=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async publishPresence(e){return this.runOperation("publishPresence",async()=>{this.validateDescription(e.customStatus);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/${t.clientResource}/1`,o={ext:e.customStatus};js("Call publishPresence",{customStatus:e.customStatus}),await r.request(i,{method:"POST",body:o,operation:"publishPresence"})})}async subscribePresence(e){return this.runOperation("subscribePresence",async()=>{this.validateUserIds(e.userIds),this.validateExpiry(e.expiry);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/${e.expiry}`,o={usernames:e.userIds};js("Call subscribePresence",{userIds:e.userIds,expiry:e.expiry});const a=await r.request(i,{method:"POST",body:o,operation:"subscribePresences"});return this.normalizeSubscribeResponse(a)})}async unsubscribePresence(e){return this.runOperation("unsubscribePresence",async()=>{this.validateUserIds(e.userIds);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence`;js("Call unsubscribePresence",{userIds:e.userIds}),await r.request(i,{method:"DELETE",body:e.userIds,operation:"unsubscribePresence"})})}async getSubscribedPresenceList(e){return this.runOperation("getSubscribedPresenceList",async()=>{this.validatePage(e.pageNum,e.pageSize);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/sublist?pageNum=${e.pageNum}&pageSize=${e.pageSize}`;js("Call getSubscribedPresenceList",{pageNum:e.pageNum,pageSize:e.pageSize});const o=await r.request(i,{method:"GET",operation:"getSubscribedPresenceList"});return this.normalizeSubscribedListResponse(o)})}async getPresenceStatus(e){return this.runOperation("getPresenceStatus",async()=>{this.validateUserIds(e.userIds);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence`,o={usernames:e.userIds};js("Call getPresenceStatus",{userIds:e.userIds});const a=await r.request(i,{method:"POST",body:o,operation:"getPresenceStatus"});return this.normalizeSubscribeResponse(a)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Vs(`PresenceManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof ut?t:t instanceof Error?new ut(`PresenceManager ${e} failed: ${t.message}`,ot.UNKNOWN):new ut(`PresenceManager ${e} failed`,ot.UNKNOWN)}getEventContextOrThrow(){if(!this.eventContext)throw new mt("PresenceManager is not bound to event context",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.eventContext",message:"PresenceManager is not bound to event context",rule:"required"}]}});return this.eventContext}getClientOrThrow(){if(!this.client)throw new mt("PresenceManager is not bound to client",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.client",message:"PresenceManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Vf(e.restBaseUrl,{errorMap:GC,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError([{path:"appKey",message:"appKey is invalid",rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateDescription(e){if("string"!=typeof e)throw this.buildValidationError([{path:"description",message:"description must be a string",rule:"invalid_format"}])}validateUserIds(e){if(!Array.isArray(e))throw this.buildValidationError([{path:"userIds",message:"userIds must be an array",rule:"invalid_format"}]);if(0===e.length)throw this.buildValidationError([{path:"userIds",message:"userIds is required",rule:"required"}]);for(const t of e)if("string"!=typeof t||0===t.trim().length)throw this.buildValidationError([{path:"userIds",message:"userIds contains invalid userId",rule:"invalid_format"}])}validateExpiry(e){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"expiry",message:"expiry must be a number",rule:"invalid_format"}]);if(e<0)throw this.buildValidationError([{path:"expiry",message:"expiry must be greater than or equal to 0",rule:"range"}])}validatePage(e,t){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"pageNum",message:"pageNum must be a number",rule:"invalid_format"}]);if("number"!=typeof t||Number.isNaN(t))throw this.buildValidationError([{path:"pageSize",message:"pageSize must be a number",rule:"invalid_format"}]);if(e<0||t<0)throw this.buildValidationError([{path:"pageNum",message:"pageNum must be greater than or equal to 0",rule:"range"},{path:"pageSize",message:"pageSize must be greater than or equal to 0",rule:"range"}])}normalizeSubscribeResponse(e){return(e.result??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.length?{publisher:e.uid,statusList:this.normalizeStatusList(e.status),ext:"string"==typeof e.ext?e.ext:"",latestTime:"number"==typeof e.last_time?e.last_time:0,expiryTime:"number"==typeof e.expiry?e.expiry:0}:null).filter(e=>null!==e)}normalizeSubscribedListResponse(e){const t=e.result;return(t?.sublist??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.trim().length?e.uid:null).filter(e=>null!==e)}normalizeStatusList(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return{};var t;const r={};for(const[s,n]of Object.entries(e))if("number"==typeof n&&Number.isFinite(n))r[s]=Math.trunc(n);else if("string"==typeof n&&n.trim().length>0){const e=Number(n);Number.isFinite(e)&&(r[s]=Math.trunc(e))}return r}buildValidationError(e){return new mt("Invalid parameters",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:e}})}};qC.key="presenceManager";let $C=qC;const jC=["apns","fcm","huawei","xiaomi","meizu","vivo","oppo","honor"],VC=(e,t,r="invalid_format")=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:r}]}}),KC=(e,t)=>{if(void 0!==e){if("string"!=typeof e||0===e.trim().length)throw VC(t,`${t} must be a non-empty string`);return e.trim()}},zC=e=>8===e?"normal":jC[e]??"normal",HC=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.push_token&&"number"==typeof t.push_type&&Number.isInteger(t.push_type)&&t.push_type>=0&&t.push_type<=8&&"number"==typeof t.code&&"string"==typeof t.error};class WC{constructor(e){this.dependencies=e,this.config=null,this.session=null,this.state="unconfigured",this.disabledByUser=!1,this.registrationVersion=0,this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.bindingPromise=null,this.lastBindingError=null,this.lastRemovalError=null,this.removalPromise=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.pluginRegistered=!1,this.delays=new Set}configure(e){const t=(e=>{if(!e||"object"!=typeof e)throw VC("options","options is required","required");const t=e.plugin;if(!t||"object"!=typeof t)throw VC("plugin","plugin is required","required");const r=t;if("function"!=typeof r.onRegister)throw VC("plugin.onRegister","plugin.onRegister must be a function");if("function"!=typeof r.unRegister)throw VC("plugin.unRegister","plugin.unRegister must be a function");const s=e.certificates;if(!s||"object"!=typeof s)throw VC("certificates","certificates is required","required");const n=s,i={apns:KC(n.apns,"certificates.apns"),fcm:KC(n.fcm,"certificates.fcm"),huawei:KC(n.huawei,"certificates.huawei"),xiaomi:KC(n.xiaomi,"certificates.xiaomi"),meizu:KC(n.meizu,"certificates.meizu"),vivo:KC(n.vivo,"certificates.vivo"),oppo:KC(n.oppo,"certificates.oppo"),honor:KC(n.honor,"certificates.honor")};if(!jC.some(e=>void 0!==i[e]))throw VC("certificates","at least one native push certificate is required");return{plugin:t,certificates:i,signature:jC.map(e=>`${e}:${i[e]??""}`).join("|")}})(e),r=null!==this.config&&"disabled"!==this.state,s=this.config?.plugin===t.plugin&&this.config.signature===t.signature;if(r&&!s)throw new mt("Native push is enabled; call removePushToken() before replacing its configuration",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"options",message:"removePushToken() must succeed before replacing native push config",rule:"conflict"}]}});r&&s&&"failed"!==this.state||(this.invalidateRegistration(),this.safeUnregister(),this.config=t,this.disabledByUser=!1,this.exhaustedKey=null,this.state="configured",this.session&&this.startRegistration())}onSessionReady(e){this.invalidateRegistration(),this.safeUnregister(),this.session=e,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.config&&!this.disabledByUser&&(this.state="configured",this.startRegistration())}async onSessionEnding(e){if(this.session&&this.session.generation===e.generation){if(this.sessionEndingGeneration=e.generation,this.invalidateRegistration(),this.removalPromise)try{await this.removalPromise}catch{}if(this.isSessionGenerationActive(e.generation)&&(this.bindingPromise&&await this.bindingPromise,this.isSessionGenerationActive(e.generation))){for(const t of this.collectRemovalTargets(e.generation)){const r=await this.removeWithRetry(t,e.generation);if(!this.isSessionGenerationActive(e.generation))return;if(!r){this.emitFailure(Ge.TOKEN_REMOVE_FAILED,"remove",t.channel,t.notifierName,this.lastRemovalError??void 0);break}}this.isSessionGenerationActive(e.generation)&&(this.safeUnregister(),this.clearSessionRuntime())}}}resetSessionRuntime(){this.invalidateRegistration(),this.safeUnregister(),this.clearSessionRuntime()}removePushToken(){return this.session?(this.removalPromise||(this.removalPromise=this.performManualRemoval().finally(()=>{this.removalPromise=null})),this.removalPromise):Promise.reject(new ut("User is not logged in",ot.AUTH_NOT_LOGIN))}startRegistration(){if(!this.config||!this.session||this.disabledByUser)return;const e=this.config,t=this.session.generation,r=++this.registrationVersion;this.state="registering",this.pluginRegistered=!0;try{e.plugin.onRegister(s=>{if(!this.isRegistrationActive(t,r))return;const n=((e,t)=>{if(!HC(e)||200!==e.code||0===e.push_token.trim().length)return null;const r=zC(e.push_type);if("normal"===r)return null;const s=t.certificates[r];return s?{token:e.push_token,channel:r,notifierName:s}:null})(s,e);if(!n){this.state="failed";const t=HC(s)?zC(s.push_type):void 0,r=HC(s)&&200===s.code&&s.push_token.trim().length>0&&void 0!==t&&"normal"!==t&&void 0===e.certificates[t];return void this.emitFailure(Ge.TOKEN_BIND_FAILED,r?"bind":"register",t)}this.enqueueBinding(n)})}catch{this.safeUnregister(),this.state="failed",this.emitFailure(Ge.TOKEN_BIND_FAILED,"register")}}enqueueBinding(e){const t=this.createBindingKey(e);t!==this.successfulKey&&t!==this.exhaustedKey&&t!==this.activeBindingKey&&(this.pendingCandidate=e,this.manualRemovalInProgress||this.bindingPromise||(this.bindingPromise=this.drainBindingQueue().finally(()=>{this.bindingPromise=null,this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress&&this.enqueueBinding(this.pendingCandidate)})))}async drainBindingQueue(){for(;this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress;){const e=this.pendingCandidate;this.pendingCandidate=null;const t=this.session.generation,r=this.createBindingKey(e);this.activeBindingKey=r,this.state="binding";const s=await this.bindWithRetry(e,t);if(this.activeBindingKey=null,!this.session||this.session.generation!==t||this.disabledByUser)return;s?(this.binding={...e,generation:t,userId:this.session.userId,deviceId:this.session.clientResource},this.successfulKey=r,this.exhaustedKey=null,this.state="bound",this.sessionEndingGeneration===t||this.manualRemovalInProgress||this.dependencies.dispatch(Ge.TOKEN_BOUND,{channel:e.channel,notifierName:e.notifierName})):(this.exhaustedKey=r,this.state="failed",this.sessionEndingGeneration===t||this.manualRemovalInProgress||this.emitFailure(Ge.TOKEN_BIND_FAILED,"bind",e.channel,e.notifierName,this.lastBindingError??void 0))}}async bindWithRetry(e,t){this.lastBindingError=null;for(let s=0;s<=2;s+=1)try{const r=this.session;return!(!r||r.generation!==t)&&(this.lastAttemptedBinding={...e,generation:t,userId:r.userId,deviceId:r.clientResource},await this.dependencies.requestToken({deviceId:r.clientResource,deviceToken:e.token,notifierName:e.notifierName,timeout:5e3}),!0)}catch(r){if(this.lastBindingError=this.toSdkError(r),!this.session||this.session.generation!==t)return!1;if(!this.isRetryable(r)||2===s)return!1;const e=Yr[s]??0;if(!(await this.wait(e)))return!1}return!1}async performManualRemoval(){if(!this.session)throw new ut("User is not logged in",ot.AUTH_NOT_LOGIN);const e=this.session.generation;if(this.manualRemovalInProgress=!0,this.cancelDelays(),this.bindingPromise&&await this.bindingPromise,!this.isSessionGenerationActive(e))throw this.manualRemovalInProgress=!1,new ut("User is not logged in",ot.AUTH_NOT_LOGIN);const t=this.collectRemovalTargets(e);if(0!==t.length)try{for(const r of t)if(await this.dependencies.requestToken({deviceId:r.deviceId,deviceToken:"",notifierName:r.notifierName}),!this.isSessionGenerationActive(e))return;this.disableByUser()}catch(r){const s=this.toSdkError(r),n=t[0];throw n&&this.isSessionGenerationActive(e)&&this.emitFailure(Ge.TOKEN_REMOVE_FAILED,"remove",n.channel,n.notifierName,s),this.manualRemovalInProgress=!1,this.resumePendingBinding(e),s}else this.disableByUser()}async removeWithRetry(e,t){this.lastRemovalError=null;for(let s=0;s<=1;s+=1)try{return await this.dependencies.requestToken({deviceId:e.deviceId,deviceToken:"",notifierName:e.notifierName,timeout:2500}),!0}catch(r){if(this.lastRemovalError=this.toSdkError(r),!this.isSessionGenerationActive(t))return!1;if(!this.isRetryable(r)||1===s)return!1;if(!(await this.wait(500)))return!1}return!1}disableByUser(){this.disabledByUser=!0,this.manualRemovalInProgress=!1,this.invalidateRegistration(),this.safeUnregister(),this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.state="disabled"}clearSessionRuntime(){this.session=null,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.state=this.disabledByUser?"disabled":this.config?"configured":"unconfigured"}invalidateRegistration(){this.registrationVersion+=1,this.pendingCandidate=null,this.cancelDelays()}cancelDelays(){for(const e of this.delays)clearTimeout(e.timer),e.resolve(!1);this.delays.clear()}collectRemovalTargets(e){const t=[this.binding,this.lastAttemptedBinding].filter(t=>t?.generation===e);return t.filter((e,r)=>t.findIndex(t=>t.deviceId===e.deviceId&&t.notifierName===e.notifierName)===r)}resumePendingBinding(e){if(!this.pendingCandidate||!this.isSessionGenerationActive(e)||this.disabledByUser||this.sessionEndingGeneration===e)return;const t=this.pendingCandidate;this.pendingCandidate=null,this.enqueueBinding(t)}isSessionGenerationActive(e){return this.session?.generation===e}safeUnregister(){if(this.pluginRegistered){this.pluginRegistered=!1;try{this.config?.plugin.unRegister()}catch{Vs("Native push plugin unregister failed")}}}isRegistrationActive(e,t){return this.session?.generation===e&&this.registrationVersion===t&&!this.disabledByUser}createBindingKey(e){const t=this.session;return t?`${t.generation}\0${t.userId}\0${t.clientResource}\0${e.token}\0${e.notifierName}`:""}wait(e){return new Promise(t=>{const r={timer:setTimeout(()=>{this.delays.delete(r),t(!0)},e),resolve:t};this.delays.add(r)})}isRetryable(e){return!(e instanceof ut)||(!0===e.details?.retryable||[ot.REST_NETWORK_ERROR,ot.REST_TIMEOUT,ot.REST_HTTP_ERROR,ot.SERVER_BUSY].includes(e.code))}toSdkError(e){return e instanceof ut?e:new ut("Native push operation failed",ot.UNKNOWN)}emitFailure(e,t,r,s,n){const i=!!n&&this.isRetryable(n);this.dependencies.dispatchFailure(e,{stage:t,...r?{channel:r}:{},...s?{notifierName:s}:{},...n?{code:n.code}:{},retryable:i}),Vs("Native push operation failed",{stage:t,...r?{channel:r}:{},...s?{notifierName:s}:{},...n?{code:n.code}:{},retryable:i})}}const JC=bv(_v,{common:{},apis:{setGlobalSilentMode:{range:"110,1501",localErrors:{setGlobalSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setConversationSilentMode:{range:"110,1501",localErrors:{setConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setPushLanguage:{range:"110,1502",localErrors:{setPushLanguage:{validation_invalid:{code:110,retryable:!1}}},errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,httpStatus:400,retryable:!1}}},uploadPushToken:{range:"110,201,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}},setNativePush:{validation_invalid:{code:110,retryable:!1}},removePushToken:{auth_not_login:{code:201,retryable:!1}}},errors:{TOKEN_UPLOAD_FAILED:{code:1500,httpStatus:400,retryable:!0}}},getGlobalSilentMode:{range:"1501",errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentMode:{range:"110,1501",localErrors:{getConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},clearConversationRemindType:{range:"110,1501",localErrors:{clearConversationRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentModes:{range:"110,1501",localErrors:{getConversationSilentModes:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationListByRemindType:{range:"110",localErrors:{getConversationListByRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPushLanguage:{range:"1502",errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,retryable:!1}}}}}),QC=["singleChat","groupChat"],ZC=["ALL","AT","NONE","DEFAULT"],YC=["ALL","AT","NONE"],XC=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),eS=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.eventContext=null,this.nativePushController=new WC({requestToken:async e=>{await this.requestNativePushToken(e)},dispatch:(e,t)=>{this.eventContext?.dispatch?.(e,t)},dispatchFailure:(e,t)=>{this.eventContext?.dispatch?.(e,t)}})}bind(e,t){this.client=e,this.eventContext=t??null}onSessionReady(e){this.nativePushController.onSessionReady(e)}async onSessionEnding(e){await this.nativePushController.onSessionEnding(e)}resetSessionRuntime(){this.nativePushController.resetSessionRuntime()}setNativePush(e){this.nativePushController.configure(e)}removePushToken(){return this.nativePushController.removePushToken()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async uploadPushToken(e){return this.runOperation(async()=>{this.validateUploadPushTokenParams(e),await this.requestNativePushToken(e)})}async requestNativePushToken(e){const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey);js("Call native push token operation",{deviceId:e.deviceId,notifierName:e.notifierName,removing:0===e.deviceToken.length}),await r.request(`/${s}/${n}/users/${t.userId}`,{method:"PUT",body:{device_id:e.deviceId,device_token:e.deviceToken,notifier_name:e.notifierName},operation:"uploadPushToken",...void 0!==e.timeout?{timeout:e.timeout}:{}})}async setGlobalSilentMode(e){return this.runOperation(async()=>{this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/notification/user/${t.userId}?resource=${encodeURIComponent(t.clientResource)}`,o=this.buildSilentModePayload(e.rule);js("Call setGlobalSilentMode",{mode:e.rule.mode});const a=await r.request(i,{method:"PUT",body:o,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),e.rule)}})}async getGlobalSilentMode(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:r,appName:s}=this.parseAppKey(e.appKey),n=`/${r}/${s}/users/${e.userId}/notification/user/${e.userId}`;js("Call getGlobalSilentMode");const i=await t.request(n,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(i))}})}async setConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType"),this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`,a=this.buildSilentModePayload(e.rule);js("Call setConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType,mode:e.rule.mode});const c=await r.request(o,{method:"PUT",body:a,operation:"setConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(c),e.rule)}})}async getConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}`;js("Call getConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await r.request(o,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a))}})}async clearConversationRemindType(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`;js("Call clearConversationRemindType",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await r.request(o,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),{remindType:"DEFAULT"})}})}async getConversationSilentModes(e){return this.runOperation(async()=>{this.validateConversationList(e.conversationList,"conversationList");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=e.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),o=e.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),a=`/${s}/${n}/users/${t.userId}/notification?user=${i}&group=${o}`;js("Call getConversationSilentModes",{count:e.conversationList.length});const c=await r.request(a,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(c,"user"),u=this.resolveConversationRuleMap(c,"group");return{conversations:e.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:u[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(e){await this.runOperation(async()=>{this.validateLanguage(e.language,"language");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/notification/language`;js("Call setPushLanguage",{language:e.language}),await r.request(i,{method:"PUT",body:{translationLanguage:e.language},operation:"setPushLanguage"})})}async getPushLanguage(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:r,appName:s}=this.parseAppKey(e.appKey),n=`/${r}/${s}/users/${e.userId}/notification/language`;js("Call getPushLanguage");const i=await t.request(n,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(i,"")}})}getConversationListByRemindType(e){return this.runOperation(()=>{js("Call getConversationListByRemindType",{pageSize:e.pageSize,hasCursor:Boolean(e.cursor)});const t=this.getClientOrThrow(),r=wf({items:t.getCacheManager()?.loadSessionList()??[],pageSize:e.pageSize,cursor:e.cursor});return Promise.resolve(r)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(e){return e instanceof ut?e:e instanceof Error?new ut(`PushManager operation failed: ${e.message}`,ot.UNKNOWN):new ut("PushManager operation failed",ot.UNKNOWN)}getRestContextOrThrow(){if(!this.client)throw this.buildValidationError("PushManager is not bound to client",[{path:"pushManager.client",message:"PushManager is not bound to client",rule:"required"}]);return this.client.getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Vf(e.restBaseUrl,{errorMap:JC,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}getClientOrThrow(){if(!this.client)throw new ut("PushManager is not bound to client",ot.VALIDATION_REQUIRED);return this.client}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError("Invalid appKey format",[{path:"appKey",message:'appKey must be in format "org#app"',rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateUploadPushTokenParams(e){this.validateNonEmptyString(e.deviceId,"deviceId"),this.validateNonEmptyString(e.deviceToken,"deviceToken"),this.validateNonEmptyString(e.notifierName,"notifierName")}validateConversationId(e,t){this.validateNonEmptyString(e,t)}validateConversationType(e,t){if("string"!=typeof e||!QC.includes(e))throw this.buildValidationError("Conversation type is not supported",[{path:t,message:"Only singleChat and groupChat are supported",rule:"invalid_format"}])}validateConversationList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError("conversationList must be a non-empty array",[{path:t,message:"conversationList must be a non-empty array",rule:"required"}]);if(e.length>20)throw this.buildValidationError("conversationList length must be <= 20",[{path:t,message:"conversationList length exceeds 20",rule:"range"}]);e.forEach((e,r)=>{this.validateConversationId(e.conversationId,`${t}[${r}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${r}].conversationType`)})}validateLanguage(e,t){this.validateNonEmptyString(e,t)}validateNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} must be a non-empty string`,[{path:t,message:`${t} must be a non-empty string`,rule:"invalid_format"}])}validateRuleInput(e,t){if(!XC(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);switch(e.mode){case"REMIND_TYPE":if(!YC.includes(e.remindType))throw this.buildValidationError("rule.remindType is invalid",[{path:`${t}.remindType`,message:"remindType must be one of ALL/AT/NONE",rule:"invalid_format"}]);this.ensureNoConflictFields(e,t,["mode","remindType"]);break;case"DURATION":if(!Number.isInteger(e.duration)||e.duration<=0)throw this.buildValidationError("rule.duration must be a positive integer",[{path:`${t}.duration`,message:"duration must be a positive integer",rule:"range"}]);this.ensureNoConflictFields(e,t,["mode","duration"]);break;case"INTERVAL":this.validateTimePoint(e.startTime,`${t}.startTime`),this.validateTimePoint(e.endTime,`${t}.endTime`),this.ensureNoConflictFields(e,t,["mode","startTime","endTime"]);break;default:throw this.buildValidationError("rule.mode is invalid",[{path:`${t}.mode`,message:"mode must be one of REMIND_TYPE/DURATION/INTERVAL",rule:"invalid_format"}])}}ensureNoConflictFields(e,t,r){const s=Object.keys(e).find(e=>!r.includes(e));if(s)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${s}`,message:`${s} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!XC(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);if(!Number.isInteger(e.hours)||e.hours<0||e.hours>23)throw this.buildValidationError("hours must be between 0 and 23",[{path:`${t}.hours`,message:"hours must be between 0 and 23",rule:"range"}]);if(!Number.isInteger(e.minutes)||e.minutes<0||e.minutes>59)throw this.buildValidationError("minutes must be between 0 and 59",[{path:`${t}.minutes`,message:"minutes must be between 0 and 59",rule:"range"}])}buildSilentModePayload(e){switch(e.mode){case"REMIND_TYPE":return{type:e.remindType};case"DURATION":return{ignoreDuration:6e4*e.duration};case"INTERVAL":return{ignoreInterval:`${this.formatIntervalSegment(e.startTime)}-${this.formatIntervalSegment(e.endTime)}`}}}normalizeRuleView(e,t){const r=this.parseRuleView(e);return r?t?{...this.toRuleViewFromFallback(t),...r}:r:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!XC(e))return null;const t={},r=this.normalizeRemindType(e.type);null!==r&&(t.remindType=r);const s=e.ignoreDuration;"number"==typeof s&&Number.isInteger(s)&&s>0&&(t.expireTimestamp=s);const n=e.ignoreInterval;if("string"==typeof n){const e=this.parseInterval(n);e&&(t.silentModeStartTime=e.startTime,t.silentModeEndTime=e.endTime)}return void 0!==t.remindType||void 0!==t.expireTimestamp||void 0!==t.silentModeStartTime&&void 0!==t.silentModeEndTime?t:null}parseInterval(e){const t=e.match(/^(\d{1,2}):(\d{1,2})-(\d{1,2}):(\d{1,2})$/);if(!t)return null;const r=Number(t[1]),s=Number(t[2]),n=Number(t[3]),i=Number(t[4]);return Number.isInteger(r)&&Number.isInteger(s)&&Number.isInteger(n)&&Number.isInteger(i)?r<0||r>23||n<0||n>23||s<0||s>59||i<0||i>59?null:{startTime:{hours:r,minutes:s},endTime:{hours:n,minutes:i}}:null}toRuleViewFromFallback(e){if("mode"in e)switch(e.mode){case"REMIND_TYPE":return{remindType:e.remindType};case"DURATION":return{};case"INTERVAL":return{silentModeStartTime:e.startTime,silentModeEndTime:e.endTime}}return e}formatIntervalSegment(e){return`${String(e.hours).padStart(2,"0")}:${String(e.minutes).padStart(2,"0")}`}resolveConversationRuleMap(e,t){if(XC(e.data)){const r=e.data[t];if(XC(r))return r}const r=e[t];return XC(r)?r:{}}resolveSilentModeRuleSource(e){if(!XC(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return XC(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":ZC.includes(e)?e:null}resolvePushLanguage(e,t){if("string"==typeof e.translationLanguage&&e.translationLanguage.length>0)return e.translationLanguage;if("string"==typeof e.language&&e.language.length>0)return e.language;if(XC(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const r=e.data.language;if("string"==typeof r&&r.length>0)return r}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(e,t){return new mt(e,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:t}})}};eS.key="pushManager";let tS=eS;const rS=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},sS=(e,t="params.userIds")=>x_(e,t),nS=e=>{const t=sS(e);if(t.length>100)throw((e,t,r,s=ot.VALIDATION_INVALID_FORMAT)=>new mt(e,{code:s,details:{fields:[{path:t,message:e,rule:r}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",ot.SERVICE_LIMIT_EXCEEDED);return{usernames:t}},iS=(e,t)=>{const r=(e=>sS(e))(t);return`${rS(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},oS=(e,t)=>{switch(e){case"nickname":return"string"==typeof t?{nickname:t}:null;case"avatarurl":case"avatarUrl":return"string"==typeof t?{avatarUrl:t}:null;case"mail":return"string"==typeof t?{mail:t}:null;case"phone":return"string"==typeof t?{phone:t}:null;case"gender":return"string"==typeof t||"number"==typeof t||"boolean"==typeof t?{gender:t}:null;case"sign":return"string"==typeof t?{sign:t}:null;case"birth":return"string"==typeof t?{birth:t}:null;case"ext":return"string"==typeof t?{ext:t}:null;default:return null}},aS=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],cS=bv(_v,{common:{},apis:{updateOwnUserInfo:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfo:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfoByAttribute:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByUserId:{range:"4,110,204,900",localErrors:{getUserInfoByUserId:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByAttribute:{range:"4,110,204,900",localErrors:{getUserInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},subscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},unsubscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},getSubscribedUsers:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}}}}),dS=class{constructor(){this.capabilities=["userInfo:read","rawNotify:userInfo"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}handleRawNotify(e){if("userInfo"!==e.type)return;const t=this.client,r=t?.getCacheManager();if(!t||!r||!t.getCurrentUserId())return;const s=e.payload,n=(e=>{const t={};for(const[r,s]of Object.entries(e.metadata)){const e=oS(r,s);e&&Object.assign(t,e)}return{userId:e.userId,attributes:t,lastModified:e.lastModified,source:"subscribe_metadata_updated"===e.notifyType?"subscription":"contact_metadata_updated"===e.notifyType?"contact":"own"}})(s);if(!n)return;const i=r.applyUserInfoNotifyPatch(n);if(!i.applied)return void js("User-info notify ignored",{userId:n.userId,notifyType:s.notifyType,reason:i.reason,lastModified:n.lastModified});if(r.updateUserInfoSummaryFromRuntime(n.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:n.userId,lastModified:n.lastModified}]),"subscription"===n.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[i.record.profile]);if("own"===n.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",i.record.profile);const o=t.getContactSnapshot()?.items.find(e=>e.userId===n.userId);this.eventContext?.dispatch?.(Z,{userInfo:i.record.profile,contact:o})}async getUserInfoByUserId(e){return this.runOperation("getUserInfoByUserId",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=q_(x_(e.userIds,"params.userIds")),n=B_(t);js("UserInfoManager getUserInfoByUserId",{userIds:s.targets});const i=await r.request(n,{method:"POST",body:s,operation:"getUserInfoByUserId"}),o=this.normalizeFetchEnvelope(i,s.targets);return this.writeCache(o),this.completeFetchedProfiles(o,s.targets)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(n=x_(e.userIds,"params.userIds"),i=F_(e.attributes,"params.attributes"),{targets:x_(n),properties:F_(i).map(e=>P_(e,"params.attributes"))});var n,i;const o=B_(t);js("UserInfoManager getUserInfoByAttribute",{userIds:s.targets,attributes:s.properties});const a=await r.request(o,{method:"POST",body:s,operation:"getUserInfoByAttribute"}),c=this.normalizeFetchEnvelope(a,s.targets);return this.writeCache(c),this.completeFetchedProfiles(c,s.targets)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>rS(e))(t),n=nS(e.userIds);js("UserInfoManager subscribeUsersInfo",{userIds:n.usernames}),await r.request(s,{method:"POST",body:n,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=iS(t,e.userIds);js("UserInfoManager unsubscribeUsersInfo",{userIds:x_(e.userIds,"params.userIds")}),await r.request(s,{method:"DELETE",operation:"unsubscribeUsersInfo"})})}async getSubscribedUsers(){return this.runOperation("getSubscribedUsers",async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),r=(e=>rS(e))(e);js("UserInfoManager getSubscribedUsers",{userId:e.userId});const s=(e=>{const t=e&&"object"==typeof e?e:null;if(!t||!Array.isArray(t.data))return[];const r=[],s=new Set;for(const n of t.data){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),r.push(e))}return r})(await t.request(r,{method:"GET",operation:"getSubscribedUsers"}));return 0===s.length?[]:await this.getUserInfoByUserId({userIds:s})})}async updateOwnInfo(e){return this.runOperation("updateOwnInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>{const t=[];if(H_(t,"nickname",e.nickname,"params.nickname"),H_(t,"avatarurl",e.avatarUrl,"params.avatarUrl"),H_(t,"mail",e.mail,"params.mail"),H_(t,"phone",e.phone,"params.phone"),H_(t,"gender",e.gender,"params.gender"),H_(t,"sign",e.sign,"params.sign"),H_(t,"birth",e.birth,"params.birth"),H_(t,"ext",e.ext,"params.ext"),0===t.length)throw L_("params must include at least one updatable field","params","required");return W_(t)})(e),n=G_(t);js("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const i=await r.request(n,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s,operation:"updateOwnInfo"}),o=this.normalizeUpdateEnvelope(i,t.userId,this.buildFallbackProfile(t.userId,e));return this.writeCache([o]),this.dispatchSelfUpdate(o.profile),o.profile})}async updateOwnInfoByAttribute(e,t){return this.runOperation("updateOwnInfoByAttribute",async()=>{const r=this.getRestContextOrThrow(),s=this.getRestClient(r),n=((e,t)=>{const r=P_(e,"attribute"),s=D_(t,"value");if("gender"!==r&&"string"!=typeof s)throw L_("value must be a string","value","invalid_format");return W_([[r,String(s)]])})(e,t),i=G_(r);js("UserInfoManager updateOwnInfoByAttribute",{userId:r.userId,attribute:e});const o=await s.request(i,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,operation:"updateOwnInfoByAttribute"}),a=this.normalizeUpdateEnvelope(o,r.userId,{userId:r.userId,[e]:t});return this.writeCache([a]),this.dispatchSelfUpdate(a.profile),a.profile})}async runOperation(e,t){try{return await t()}catch(r){throw this.normalizeOperationError(e,r)}}normalizeOperationError(e,t){return t instanceof ut?t:(Vs("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new ut(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new mt("UserInfoManager is not bound to client",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"userInfoManager.client",message:"client is required",rule:"required"}]}})}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Vf(e.restBaseUrl,{errorMap:cS,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}normalizeFetchEnvelope(e,t){return K_(e,t)}completeFetchedProfiles(e,t){const r=new Map(e.map(e=>[e.profile.userId,e.profile]));return t.map(e=>r.get(e)??{userId:e})}normalizeUpdateEnvelope(e,t,r){const s=pu(e)?e:null,n=(s&&pu(s.data)?s.data:null)??(s&&this.looksLikeUserInfoAttributes(s)?s:null),i=s&&"number"==typeof s.lastModified?s.lastModified:void 0;return{profile:n?this.toUserInfo(t,n):{userId:t,...r??{}},lastModified:i}}toUserInfo(e,t){const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r}looksLikeUserInfoAttributes(e){return!!pu(e)&&("nickname"in e||"avatarurl"in e||"avatarUrl"in e||"mail"in e||"phone"in e||"gender"in e||"sign"in e||"birth"in e||"ext"in e)}buildFallbackProfile(e,t){const r={userId:e},s=r;for(const n of aS)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return aS.filter(t=>t in e)}projectToSummary(e){const t=Date.now(),r=bl(e.lastModified);return{userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,userInfoUpdateTime:r,lastSyncAt:t,lastAccess:t,lastUpdate:e.lastModified??t}}writeCache(e){if(!this.client||0===e.length)return;const t=this.client.getCacheManager();t&&("function"==typeof t.upsertRuntimeUserInfos&&t.upsertRuntimeUserInfos(e.map(e=>({profile:e.profile,lastModified:e.lastModified,source:e.profile.userId===this.client?.getRestContext().userId?"update":"fetch"}))),t.setUserInfoSummaries(e.map(e=>this.projectToSummary(e))))}dispatchSelfUpdate(e){this.client?.dispatchOwnInfoUpdated?.(e)}};dS.key="userInfoManager";let uS=dS;return e.AuthenticationError=pt,e.CONVERSATION_MARK={MARK_0:0,MARK_1:1,MARK_2:2,MARK_3:3,MARK_4:4,MARK_5:5,MARK_6:6,MARK_7:7,MARK_8:8,MARK_9:9,MARK_10:10,MARK_11:11,MARK_12:12,MARK_13:13,MARK_14:14,MARK_15:15,MARK_16:16,MARK_17:17,MARK_18:18,MARK_19:19},e.CacheManager=Dm,e.ChatClient=zv,e.ChatManager=vb,e.ChatRoom=Bb,e.ChatRoomManager=Y_,e.ChatThread=Ib,e.ChatThreadManager=Fb,e.ConnectionError=ht,e.ContactManager=NT,e.Group=OT,e.GroupManager=BC,e.ImageType={ORIGINAL:"original",LARGE:"large"},e.LogEventName=V,e.MessageReceiveError=gt,e.MessageSendError=ft,e.NetworkError=lt,e.PresenceManager=$C,e.PushEventName=Ge,e.PushManager=tS,e.RUNTIME_PLATFORMS=Js,e.RestBusinessError=It,e.RestTransportError=vt,e.SDKError=ut,e.StorageError=yt,e.StreamMessageStatus=nt,e.UploadError=bt,e.UserInfoManager=uS,e.ValidationError=mt,e.createPlatformAdapter=Dd,e.detectRuntimePlatform=(e,t)=>On(t,e).platform,e.isSDKError=function(e){if(e instanceof ut)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},e.setConsoleLogEnabled=function(e){!function(e){Fs instanceof xs&&Fs.setConsoleEnabled(e)}(e)},e.setLogLevel=function(e){!function(e){Fs instanceof xs&&Fs.setLevel(e)}(e)},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
|
|
1
|
+
var IMSDK=function(e){"use strict";const t="disconnected",r="connecting",s="connected",n="reconnecting",i="reconnectFailed",o="onConnecting",a="onConnected",c="onDisconnected",d="onReconnectFailed",u="onTokenWillExpire",l="onTokenExpired",h="onOfflineMessageSyncStart",p="onOfflineMessageSyncFinish",m="onSendTimeout",g="onGroupNotify",f="onChatRoomNotify",y="onChatThreadNotify",v="onUserInfoNotify",I="__internal:onMessageSent",b="login",_="reconnect",T="online",C="offline-recover",S="heartbeat-failed",E="send-timeout",w="close",A="error",R="limit",N="offline",O="token-expired",M="onMessage",U="onStreamMessage",L="onConversationListUpdate",k="onMessageReadReceipts",D="onMessageDelivered",P="onMessageRecalled",x="onMessageUpdated",F="onReactionChanged",B="onPinnedMessageChanged",G="onMultiDeviceContact",q="onMultiDeviceConversation",$="onSyncDataStart",j="onSyncDataFinished",V={LOG:"onLog"},K="onPresenceStatusChange",z="onContactInvited",H="onContactDeleted",W="onContactAdded",J="onContactRefuse",Q="onContactAgreed",Z="onContactInfoUpdated",Y="onInvitationReceived",X="onRequestToJoinReceived",ee="onRequestToJoinAccepted",te="onRequestToJoinDeclined",re="onInvitationAccepted",se="onInvitationDeclined",ne="onUserRemoved",ie="onGroupDestroyed",oe="onAutoAcceptInvitationFromGroup",ae="onMuteListAdded",ce="onMuteListRemoved",de="onAllowListAdded",ue="onAllowListRemoved",le="onAllMemberMuteStateChanged",he="onAdminAdded",pe="onAdminRemoved",me="onOwnerChanged",ge="onMembersJoined",fe="onMembersExited",ye="onAnnouncementChanged",ve="onSharedFileAdded",Ie="onSharedFileDeleted",be="onGroupInfoChanged",_e="onGroupDisabledChanged",Te="onGroupMemberAttributeChanged",Ce="onUserGroupNamecardUpdated",Se="__chatroom:onChatRoomDestroyed",Ee="__chatroom:onMembersJoined",we="__chatroom:onMembersExited",Ae="__chatroom:onRemovedFromChatRoom",Re="__chatroom:onMuteListAdded",Ne="__chatroom:onMuteListRemoved",Oe="__chatroom:onAllowListAdded",Me="__chatroom:onAllowListRemoved",Ue="__chatroom:onAllMemberMuteStateChanged",Le="__chatroom:onAdminAdded",ke="__chatroom:onAdminRemoved",De="__chatroom:onOwnerChanged",Pe="__chatroom:onAnnouncementChanged",xe="__chatroom:onChatRoomInfoChanged",Fe="__chatroom:onAttributesUpdate",Be="__chatroom:onAttributesRemoved",Ge={TOKEN_BOUND:"onPushTokenBound",TOKEN_BIND_FAILED:"onPushTokenBindFailed",TOKEN_REMOVE_FAILED:"onPushTokenRemoveFailed"},qe="onChatRoomDestroyed",$e="onMembersJoined",je="onMembersExited",Ve="onRemovedFromChatRoom",Ke="onMuteListAdded",ze="onMuteListRemoved",He="onAllowListAdded",We="onAllowListRemoved",Je="onAllMemberMuteStateChanged",Qe="onAdminAdded",Ze="onAdminRemoved",Ye="onOwnerChanged",Xe="onAnnouncementChanged",et="onChatRoomInfoChanged",rt="onAttributesUpdate",st="onAttributesRemoved",nt={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function it(e){return"object"==typeof e.stream&&null!==e.stream}const ot={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},at="[REDACTED]",ct=e=>{if(!e)return"";const t=e.includes("?"),r=e.includes("#");try{return((e,t,r)=>(e.username&&(e.username=at),e.password&&(e.password=at),e.search=t?`?${at}`:"",e.hash=r?`#${at}`:"",e.toString()))(new URL(e),t,r)}catch{const t=[e.indexOf("?"),e.indexOf("#")].filter(e=>e>=0).sort((e,t)=>e-t)[0];return void 0===t?"[invalid-url]":`${e.slice(0,t)}?${at}`}},dt=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>"url"===e.toLowerCase()&&"string"==typeof t?[e,ct(t)]:[e,t]));class ut extends Error{constructor(e,t=ot.UNKNOWN,r){super(e),this.name="SDKError",this.code=t,this.details=r?.details?dt(r.details):void 0,Error.captureStackTrace&&Error.captureStackTrace(this,ut)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class lt extends ut{constructor(e,t){super(e,t?.code??ot.REST_NETWORK_ERROR,t),this.name="NetworkError"}}class ht extends ut{constructor(e,t){super(e,t?.code??ot.CONNECTION_WEBSOCKET_ERROR,t),this.name="ConnectionError"}}class pt extends ut{constructor(e,t){super(e,t?.code??ot.AUTH_UNAUTHORIZED,t),this.name="AuthenticationError"}}class mt extends ut{constructor(e,t){super(e,t?.code??ot.VALIDATION_UNKNOWN,t),this.name="ValidationError"}}class gt extends ut{constructor(e,t){super(e,t?.code??ot.MESSAGE_SEND_FAILED,t),this.name="MessageSendError"}}class ft extends ut{constructor(e,t){super(e,t?.code??ot.MESSAGE_DECODE_FAILED,t),this.name="MessageReceiveError"}}class yt extends ut{constructor(e,t){super(e,t?.code??ot.STORAGE_OPERATION_FAILED,t),this.name="StorageError"}}class vt extends ut{constructor(e,t){super(e,t?.code??ot.REST_NETWORK_ERROR,t),this.name="RestTransportError"}}class It extends ut{constructor(e,t){super(e,t?.code??ot.REST_BUSINESS_UNKNOWN,t),this.name="RestBusinessError"}}class bt extends ut{constructor(e,t){super(e,t?.code??ot.UPLOAD_REQUEST_FAILED,t),this.name="UploadError"}}const _t=0,Tt=1,Ct=2,St=3,Et=4,wt=0,At=1,Rt=2,Nt=3,Ot=4,Mt=5,Ut=6,Lt=7,kt=8,Dt=0,Pt=1,xt=2,Ft=3,Bt=4,Gt=5,qt=6,$t=7,jt=8,Vt=0,Kt=1,zt=2,Ht=3,Wt=4,Jt=0,Qt=1,Zt=2,Yt=3,Xt=5,er=0,tr=1,rr=2,sr=0,nr=0,ir=2,or=0,ar=1,cr=2,dr=3,ur=4,lr=5,hr=6,pr=7,mr=8,gr=9,fr=10,yr=11,vr=12,Ir=13,br=14,_r=15,Tr=16,Cr=17,Sr=18,Er=19,wr=20,Ar=1,Rr=2,Nr=3,Or=4,Mr=5,Ur=6,Lr=7,kr=8,Dr="Sorry, user register limit",Pr="Sorry, user register rate limit",xr="Sorry, token expired",Fr="Sorry, token or password does not match login info",Br="Sorry, user not found",Gr="Sorry, the app month live count limit",qr="Sorry, the app day live count limit",$r="Sorry, the app online count limit",jr={[ar]:ot.AUTH_UNAUTHORIZED,[cr]:ot.AUTH_UNAUTHORIZED,[dr]:ot.VALIDATION_REQUIRED,[ur]:ot.VALIDATION_INVALID_FORMAT,[lr]:ot.CONNECTION_WEBSOCKET_ERROR,[hr]:ot.AUTH_TOKEN_EXPIRED,[pr]:ot.AUTH_FORBIDDEN,[Er]:ot.AUTH_FORBIDDEN,[mr]:ot.CONNECTION_WEBSOCKET_ERROR,[gr]:ot.UNKNOWN,[fr]:ot.UNKNOWN,[yr]:ot.AUTH_BIND_ANOTHER_DEVICE,[vr]:ot.AUTH_FORBIDDEN,[Ir]:ot.AUTH_LOGIN_TOO_MANY_DEVICES,[br]:ot.SERVICE_LIMIT_EXCEEDED,[_r]:ot.AUTH_USER_MUTED,[Tr]:ot.UNKNOWN,[Cr]:ot.UNKNOWN,[Sr]:ot.MESSAGE_DECODE_FAILED,[wr]:ot.USER_DEVICE_CHANGED},Vr=new Set([ar,cr,dr,ur,hr,pr,Er,gr,fr,yr,vr,Ir,br,_r,Tr,Cr,Sr,wr]),Kr={[Dr]:ot.SERVICE_LIMIT_EXCEEDED,[Pr]:ot.SERVICE_LIMIT_EXCEEDED,[xr]:ot.AUTH_TOKEN_EXPIRED,[Fr]:ot.AUTH_UNAUTHORIZED,[Br]:ot.AUTH_UNAUTHORIZED,blocked:ot.MESSAGE_BLOCKED_BY_RECIPIENT,"group not found":ot.GROUP_NOT_EXIST,"illegal chatroom tag":ot.VALIDATION_REQUIRED,"not in group or chatroom":ot.GROUP_NOT_JOINED,"exceed recall time limit":ot.MESSAGE_RECALL_TIME_LIMIT,"message recall disabled":ot.SERVICE_NOT_ENABLED,"group ack not open":ot.SERVICE_NOT_ENABLED,"group ack msg permission denied":ot.GROUP_PERMISSION_DENIED,"the message has expired":ot.MESSAGE_EXPIRED,"limit send group ack msg":ot.SERVICE_LIMIT_EXCEEDED,"not in group or chatroom white list":ot.MESSAGE_ILLEGAL_WHITELIST,nonroster:ot.USER_NOT_ON_ROSTER,"group is disabled":ot.GROUP_DISABLED,"roaming is not open":ot.SERVICE_NOT_ENABLED,"Sorry, message does not exist":ot.VALIDATION_REQUIRED,"Sorry, edit limit reached":ot.SERVICE_LIMIT_EXCEEDED,"Sorry, You do not have permission":ot.AUTH_FORBIDDEN,"Sorry, format is incorrect":ot.VALIDATION_REQUIRED,"Sorry, edit is not available":ot.SERVER_SERVING_DISABLED,"Sorry, edit fail":ot.MESSAGE_EDIT_FAILED},zr=[["limit directed users",ot.SERVICE_LIMIT_EXCEEDED],["no permission to recall message",ot.AUTH_FORBIDDEN]],Hr={[Gr]:ot.SERVICE_LIMIT_EXCEEDED,[qr]:ot.SERVICE_LIMIT_EXCEEDED,[$r]:ot.SERVICE_LIMIT_EXCEEDED,"sensitive words":ot.MESSAGE_INCLUDE_ILLEGAL_CONTENT,"blocked by mod_antispam":ot.MESSAGE_INCLUDE_ILLEGAL_CONTENT,"user is mute":ot.USER_MUTED_BY_ADMIN,"traffic limit":ot.MESSAGE_CURRENT_LIMITING,"Sorry, data is too large":ot.MESSAGE_SIZE_LIMIT},Wr=(e,t)=>{if("number"!=typeof e)return{code:ot.UNKNOWN,retryable:!0};const r=((e,t)=>{if(t){if(e===ar){const e=Kr[t];if(void 0!==e)return e;for(const[r,s]of zr)if(t.includes(r))return s;try{const e=JSON.parse(t);if("moderation"===e.error_type)return ot.THIRD_MODERATION_FAILED;if("string"==typeof e.error_type)return ot.THIRD_DEFAULT_FAILED}catch{}return}return e===pr?Hr[t]:e===Er?ot.MESSAGE_EXTERNAL_LOGIC_BLOCKED:e===_r?ot.AUTH_USER_MUTED:void 0}})(e,t),s=jr[e]??ot.UNKNOWN;return{code:r??s,retryable:!Vr.has(e)}},Jr={[ot.SERVICE_LIMIT_EXCEEDED]:"Message operation exceeded a service limit",[ot.AUTH_TOKEN_EXPIRED]:"Message cannot be sent because the authentication token expired",[ot.VALIDATION_REQUIRED]:"Message cannot be sent because the request is invalid",[ot.AUTH_UNAUTHORIZED]:"Message cannot be sent because authentication failed",[ot.AUTH_FORBIDDEN]:"Message operation is forbidden",[ot.AUTH_BIND_ANOTHER_DEVICE]:"Message cannot be sent because the account is bound to another device",[ot.AUTH_LOGIN_TOO_MANY_DEVICES]:"Message cannot be sent because the account is logged in on too many devices",[ot.AUTH_USER_MUTED]:"Message cannot be sent because the user is muted in the group or chat room",[ot.MESSAGE_BLOCKED_BY_RECIPIENT]:"Message cannot be sent because you are blocked by the recipient",[ot.USER_MUTED_BY_ADMIN]:"Message cannot be sent because the user is globally muted",[ot.USER_DEVICE_CHANGED]:"Message cannot be sent because the current device has changed",[ot.USER_NOT_ON_ROSTER]:"Message cannot be sent because the recipient is not in your contact list",[ot.CONNECTION_WEBSOCKET_ERROR]:"Message cannot be sent because the server is unreachable",[ot.SERVER_SERVING_DISABLED]:"Message editing is not available",[ot.MESSAGE_DECODE_FAILED]:"Message processing failed",[ot.MESSAGE_INCLUDE_ILLEGAL_CONTENT]:"Message contains prohibited content",[ot.MESSAGE_SEND_TRAFFIC_LIMIT]:"Message sending traffic limit exceeded",[ot.MESSAGE_RECALL_TIME_LIMIT]:"The message recall time limit has been exceeded",[ot.SERVICE_NOT_ENABLED]:"The required messaging service is not enabled",[ot.MESSAGE_EXPIRED]:"The message has expired",[ot.MESSAGE_ILLEGAL_WHITELIST]:"The user is not in the group or chat room allowlist",[ot.MESSAGE_EXTERNAL_LOGIC_BLOCKED]:"The message was blocked by external logic",[ot.MESSAGE_CURRENT_LIMITING]:"Message sending rate limit exceeded",[ot.MESSAGE_SIZE_LIMIT]:"Message size exceeds the limit",[ot.MESSAGE_EDIT_FAILED]:"Message editing failed",[ot.GROUP_NOT_JOINED]:"The user is not in the group or chat room",[ot.GROUP_PERMISSION_DENIED]:"The user does not have permission to perform this group message operation",[ot.GROUP_NOT_EXIST]:"The group does not exist",[ot.GROUP_DISABLED]:"The group is disabled",[ot.THIRD_MODERATION_FAILED]:"The message was rejected by content moderation",[ot.THIRD_DEFAULT_FAILED]:"The message was rejected by a third-party service"},Qr=3e5,Zr=12e4,Yr=[1e3,2e3],Xr={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"},es=e=>"undefined"!=typeof Blob&&e instanceof Blob,ts=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),r=t.length>0?t[t.length-1]:void 0;if(r)return r},rs=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const r=e.slice(t+1).toLowerCase();return Xr[r]},ss=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t&&t.length>0)return t}},ns=e=>{const t=e.file,r=e.sourceMeta,s=t.name||(r?ss(r,["name","fileName","filename"]):void 0),n=e.file.type||(r?ss(r,["type","mimeType","filetype"]):void 0),i=e.file.size||(r?((e,t)=>{for(const r of t){const t=e[r];if("number"==typeof t&&Number.isFinite(t))return t}})(r,["size","fileSize","fileLength"]):void 0),o=is({fileName:s,fileType:n,fileSize:i,fallbackName:e.fallbackName,fallbackMimeType:e.fallbackMimeType,fallbackSize:e.fallbackSize});return{source:{sourceType:"web-file",file:e.file,name:o.fileName,mimeType:o.fileType,size:o.fileSize},fileName:o.fileName,fileType:o.fileType,fileSize:o.fileSize,webFile:e.file}},is=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),os=e=>{const{file:t,fallbackName:r,fallbackMimeType:s,fallbackSize:n}=e,i=(e=>{if(es(e))return e;if("object"!=typeof e||null===e)return;const t=e;for(const r of["file","originFileObj","raw","blob"]){const e=t[r];if(es(e))return e}})(t);if(i)return ns({file:i,fallbackName:r,fallbackMimeType:s,fallbackSize:n,sourceMeta:"object"==typeof t&&null!==t?t:void 0});if((e=>"object"==typeof e&&null!==e&&"path"in e)(t)){const e=ts(t.path),i=is({fileName:t.name??e,fileType:t.type??rs(t.name??e),fileSize:t.size,fallbackName:r,fallbackMimeType:s,fallbackSize:n});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=ts(t.uri),i=is({fileName:t.name??e,fileType:t.type??rs(t.name??e),fileSize:t.size,fallbackName:r,fallbackMimeType:s,fallbackSize:n});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 o=is({fallbackName:r,fallbackMimeType:s,fallbackSize:n});return{source:{sourceType:"web-file",name:o.fileName,mimeType:o.fileType,size:o.fileSize},fileName:o.fileName,fileType:o.fileType,fileSize:o.fileSize}},as=5242880,cs=5242880,ds="CHAT",us="GROUP",ls="ROOM",hs=/^http:\/\/(?:usr|tmp|store)(?:\/|$)/i,ps="original",ms="large",gs=e=>/^https?:\/\//i.test(e)&&!hs.test(e),fs=e=>{const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw new bt("Invalid appKey for upload",{code:ot.UPLOAD_INVALID_APPKEY,details:{appKey:e}});return{orgName:t[0],appName:t[1]}},ys=e=>"singleChat"===e?ds:"groupChat"===e?us:ls,vs=(e,t)=>bs(e,{size:t}),Is=e=>{try{return decodeURIComponent(e)}catch{return e}},bs=(e,t)=>{const[r="",s]=e.split("#",2),[n,i=""]=r.split("?",2),o=i.split("&").filter(Boolean);return Object.entries(t).forEach(([e,t])=>{const r=encodeURIComponent(e),s=o.filter(t=>{const[s=""]=t.split("=",2);return s!==r&&Is(s)!==e});o.length=0,o.push(...s),void 0!==t&&o.push(`${r}=${encodeURIComponent(String(t))}`)}),`${n}${o.length>0?`?${o.join("&")}`:""}${s?`#${s}`:""}`},_s=(e,t)=>{if(!e)return"";const r={};return e.includes("em-redirect")||(r["em-redirect"]="true"),t&&!e.includes("share-secret=")&&(r["share-secret"]=t),0===Object.keys(r).length?e:bs(e,r)},Ts=e=>{const t=(r=e.messageType,s=e.imageType,"image"!==r?"attachment":s===ps?"image-origin":"image-big");var r,s;const n=(e=>"image-origin"===e?204800:1048576)(t),i=e.fileSize>n;return{shouldPrecheck:i,thresholdType:t,thresholdBytes:n,actualBytes:e.fileSize,reason:i?"threshold-exceeded":"below-threshold"}},Cs=(e,t)=>{if(!e)return{};if(!1===t?.deriveVariants)return{originalImageUrl:e};const r=(e=>{const[t="",r]=e.split("#",2),[s,n=""]=t.split("?",2),i=n.split("&").filter(Boolean).filter(e=>{const[t="",r=""]=e.split("=",2),s=Is(t),n=Is(r);return"size"!==s||!["big","large","thumbnail","small"].includes(n)}).join("&");return`${s}${i?`?${i}`:""}${r?`#${r}`:""}`})(e);return{originalImageUrl:r,bigImageUrl:vs(r,"large"),thumbnailUrl:vs(r,"small")}},Ss=e=>e===ps?"origin":"large",Es=e=>2===e?ms:ps,ws=e=>{const t=e.response.entities?.[0];if(!t?.uuid)throw new bt("Upload response missing uuid",{code:ot.UPLOAD_REQUEST_FAILED,details:{response:e.response}});const r=t["share-secret"],s=t["file-metadata"]??{},n="number"==typeof s["content-length"]?s["content-length"]:e.fallbackSize,i="string"==typeof s["content-type"]?s["content-type"]:e.fileType,o=`${e.restBaseUrl}/${e.orgName}/${e.appName}/chatfiles/${t.uuid}`;if("image"===e.messageType){const t=(e.imageType??ms)===ps;return{...Cs(o,{deriveVariants:!e.useCustomAttachmentUpload}),isOriginalImage:t,secret:r,fileLength:n,filetype:i,filename:e.fileName,width:e.width,height:e.height}}const a="video"===e.messageType?`${o}?vframe=true`:void 0;return{url:o,secret:r,fileLength:n,filetype:i,filename:e.fileName,thumbnailUrl:a}},As=e=>new Promise(t=>{setTimeout(t,e)});const Rs=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(" "):"",r=t?`${e.message} ${t}`:e.message;return`${e.timestamp} [${e.level}] ${r}`}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 r=e;for(;r.length>this.maxChunkBytes;)t.push(r.slice(0,this.maxChunkBytes)),r=r.slice(this.maxChunkBytes);return r.length>0&&t.push(r),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 As(this.chunkDelayMs)}}finally{this.reporting=!1}}}async reportChunk(e){if(!this.canReport())return!1;const{restBaseUrl:t,appKey:r,userId:s,token:n,resource:i,requestAdapter:o}=this.context;if(!(t&&r&&s&&n&&o))return!1;let a="",c="";try{const e=fs(r);a=e.orgName,c=e.appName}catch{return!1}const d=`${t}/${a}/${c}/sdk/users/${s}/client/logs`,u={resource:i??"webim",logContent:e};try{const e=await o.request({url:d,method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json"},body:u,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}}},Ns="[MASKED]",Os=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),Ms=e=>!!e&&Os.has((e=>e.toLowerCase())(e)),Us=(e,t,r)=>{const s=r??new WeakSet;if("string"==typeof e)return((e,t)=>Ms(t)?Ns: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:(n=e).name,message:n.message};var n;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>Us(e,void 0,s));if("object"==typeof e){if(s.has(e))return"[Circular]";if(s.add(e),(e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Date||e instanceof Error))(e)){const t={};for(const[r,n]of Object.entries(e))Ms(r)?t[r]=Ns:t[r]=Us(n,r,s);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},Ls="undefined"!=typeof document;let Ds=null,Ps=!1;const xs={DEBUG:0,WARN:1,ERROR:2};class Fs{constructor(e="WARN"){this.consoleEnabled=!0,this.level=e}setLevel(e){this.level=e}setConsoleEnabled(e){this.consoleEnabled=e}shouldLog(e){return xs[e]>=xs[this.level]}emit(e,t,r){const s=(e=>{const t=new WeakSet;return e.map(e=>Us(e,void 0,t))})(r),n=((e,t,r)=>({timestamp:(new Date).toISOString(),level:e,message:t,args:r}))(e,t,s);if(Rs.append(n),this.consoleEnabled){const r=new Date,n=`[Chat][${e}][${`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}:${String(r.getSeconds()).padStart(2,"0")}.${String(r.getMilliseconds()).padStart(3,"0")}`}]`;Ls?console.log(`%c${n}`,"color: rgb(0, 157, 255); font-weight: bold",t,...s):console.log(n,t,...s)}const i=Ds;i&&!Ps&&Promise.resolve().then(()=>{if(i===Ds){Ps=!0;try{i(n)}catch{}finally{Ps=!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 Bs=new Fs;function Gs(e){Rs.setState(e)}function qs(e){Rs.updateContext(e)}async function $s(){await Rs.reportNow()}function js(){Rs.stop()}const Vs=(e,...t)=>Bs.debug(e,...t),Ks=(e,...t)=>Bs.warn(e,...t),zs=(e,...t)=>Bs.error(e,...t),Hs=e=>{if("function"==typeof TextEncoder)return(new TextEncoder).encode(e);const t=[];for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>=55296&&s<=56319&&r+1<e.length){const t=e.charCodeAt(r+1);t>=56320&&t<=57343&&(s=65536+(s-55296<<10)+(t-56320),r+=1)}s<=127?t.push(s):s<=2047?t.push(192|s>>6,128|63&s):s<=65535?t.push(224|s>>12,128|s>>6&63,128|63&s):t.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s)}return new Uint8Array(t)},Ws=e=>{if("function"==typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let r=0;r<e.length;r+=1){const s=e[r]??0;if(s<128){t+=String.fromCharCode(s);continue}if(s>=192&&s<224){const n=e[r+1]??0;t+=String.fromCharCode((31&s)<<6|63&n),r+=1;continue}if(s>=224&&s<240){const n=e[r+1]??0,i=e[r+2]??0;t+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&i),r+=2;continue}const n=((7&s)<<18|(63&(e[r+1]??0))<<12|(63&(e[r+2]??0))<<6|63&(e[r+3]??0))-65536;t+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),r+=3}return t};class Js{constructor(){this.lastEventKey=null}normalize(e,u){const l=(e=>{switch(e){case r:case n:return o;case s:return a;case t:return c;case i:return d;default:return null}})(e);if(!l)return null;const h=((e,t)=>[e,t.state,t.reason,String(t.attempt),String(t.maxAttempts),String(t.isLoginPhase),String(t.isOnline),String(t.errorCode??""),t.errorMessage??""].join("|"))(l,u);return this.lastEventKey===h?null:(this.lastEventKey=h,{eventName:l,payload:u})}reset(){this.lastEventKey=null}}const Qs={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"},Zs="init",Ys="request",Xs="upload",en="socket",tn="proto",rn="runtime",sn="PLATFORM_INIT_FAILED",nn="PLATFORM_MISSING_CAPABILITY",on="PLATFORM_REQUEST_FAILED",an="PLATFORM_UPLOAD_FAILED",cn="PLATFORM_SOCKET_FAILED",dn="PLATFORM_PROTO_FAILED",un=(e,t)=>{const r=new Error(e);return r.name="PlatformAdapterError",r.code=t.code,r.stage=t.stage,r.retryable=t.retryable,t.details&&(r.details=dt(t.details)),r},ln=0,hn=1,pn=2,mn=3,gn=["__uniConfig","skipWaiting","registration","navigator","process","window","document","localStorage","fetch","WebSocket","XMLHttpRequest","FormData","TextEncoder","TextDecoder","crypto"],fn=e=>{if(e)return e;return((e,t)=>{if(!e)return t;if(0===Object.keys(t).length)return e;const r={},s=e;for(const n of gn)try{const e=s[n];void 0!==e&&(r[n]=e)}catch{}for(const n of Object.keys(t))r[n]=t[n];return r})("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}:{}})},yn={web:Qs.WEB,"mp-weixin":Qs.WECHAT_MINIAPP,"mp-alipay":Qs.ALIPAY_MINIAPP,"mp-baidu":Qs.BAIDU_MINIAPP,"mp-toutiao":Qs.TOUTIAO_MINIAPP,"mp-lark":Qs.LARK_MINIAPP,"mp-qq":Qs.QQ_MINIAPP,"mp-kuaishou":Qs.KUAISHOU_MINIAPP,"mp-jd":Qs.JD_MINIAPP,"mp-360":Qs.MINIAPP_360,"mp-harmony":Qs.HARMONY_MINIAPP,"quickapp-webview":Qs.QUICKAPP,"quickapp-webview-union":Qs.QUICKAPP,"quickapp-webview-huawei":Qs.QUICKAPP},vn=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},In=e=>(e=>vn(e,"canIUse")&&vn(e,"getSystemInfo"))(e)||(e=>vn(e,"request")&&vn(e,"connectSocket"))(e),bn=e=>vn(e,"request")&&vn(e,"connectSocket")&&vn(e,"uploadFile"),_n=(e,t)=>t===Qs.WECHAT_MINIAPP?e.wx:t===Qs.QQ_MINIAPP?e.qq:t===Qs.TOUTIAO_MINIAPP?e.tt:t===Qs.BAIDU_MINIAPP?e.swan:t===Qs.ALIPAY_MINIAPP?e.my:t===Qs.DINGTALK_MINIAPP?e.dd:t===Qs.JD_MINIAPP?e.jd:t===Qs.KUAISHOU_MINIAPP?e.ks:t===Qs.UNIAPP?e.uni:void 0,Tn=e=>{const t=e?.miniGlobal;return In(t)?t:e},Cn=e=>{const t=Tn(e);return bn(t)?t:void 0},Sn=e=>void 0!==e.window&&void 0!==e.document,En=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),wn=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;if(In(t))return!0;try{if(!vn(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},An=e=>bn(e.wx)?Qs.WECHAT_MINIAPP:bn(e.my)?Qs.ALIPAY_MINIAPP:bn(e.dd)?Qs.DINGTALK_MINIAPP:bn(e.swan)?Qs.BAIDU_MINIAPP:bn(e.tt)?Qs.TOUTIAO_MINIAPP:bn(e.qq)?Qs.QQ_MINIAPP:bn(e.jd)?Qs.JD_MINIAPP:bn(e.ks)?Qs.KUAISHOU_MINIAPP:void 0,Rn=e=>void 0!==An(e),Nn=e=>{const t=An(e);if(t)return t;try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;if("string"==typeof r)return yn[r]??Qs.UNIAPP}catch{return Qs.UNIAPP}return Sn(e)?Qs.WEB:Qs.UNIAPP},On=(e,t)=>{const r=Cn(_n(e,t));if(r)return r;const s=Cn(e.uni);return s||(e.uni??e)},Mn=(e,t)=>{const r=e??fn();if(t){const e=t===Qs.UNIAPP||wn(r),s=e?Nn(r):t;return{platform:t,hostPlatform:s,framework:e?"uniapp":Sn(r)?"web":"native",global:e?On(r,s):Tn(_n(r,t))??r}}if(wn(r)){const e=Nn(r);return{platform:Qs.UNIAPP,hostPlatform:e,framework:"uniapp",global:On(r,e)}}return In(r.swan)?{platform:Qs.BAIDU_MINIAPP,hostPlatform:Qs.BAIDU_MINIAPP,framework:"native",global:Tn(r.swan)??r.swan}:In(r.tt)?{platform:Qs.TOUTIAO_MINIAPP,hostPlatform:Qs.TOUTIAO_MINIAPP,framework:"native",global:Tn(r.tt)??r.tt}:In(r.dd)?{platform:Qs.DINGTALK_MINIAPP,hostPlatform:Qs.DINGTALK_MINIAPP,framework:"native",global:Tn(r.dd)??r.dd}:In(r.my)?{platform:Qs.ALIPAY_MINIAPP,hostPlatform:Qs.ALIPAY_MINIAPP,framework:"native",global:Tn(r.my)??r.my}:In(r.wx)?{platform:Qs.WECHAT_MINIAPP,hostPlatform:Qs.WECHAT_MINIAPP,framework:"native",global:Tn(r.wx)??r.wx}:In(r.qq)?{platform:Qs.QQ_MINIAPP,hostPlatform:Qs.QQ_MINIAPP,framework:"native",global:Tn(r.qq)??r.qq}:In(r.jd)?{platform:Qs.JD_MINIAPP,hostPlatform:Qs.JD_MINIAPP,framework:"native",global:Tn(r.jd)??r.jd}:In(r.ks)?{platform:Qs.KUAISHOU_MINIAPP,hostPlatform:Qs.KUAISHOU_MINIAPP,framework:"native",global:Tn(r.ks)??r.ks}:(e=>"ReactNative"===e.navigator?.product)(r)?{platform:Qs.REACT_NATIVE,hostPlatform:Qs.REACT_NATIVE,framework:"react-native",global:r}:(e=>"string"==typeof e.process?.versions?.electron)(r)?{platform:Sn(r)?Qs.ELECTRON_RENDERER:Qs.ELECTRON_MAIN,hostPlatform:Sn(r)?Qs.ELECTRON_RENDERER:Qs.ELECTRON_MAIN,framework:"electron",global:r}:En(r)||Sn(r)?{platform:Qs.WEB,hostPlatform:Qs.WEB,framework:En(r)?"worker":"web",global:r}:{platform:Qs.UNKNOWN,hostPlatform:Qs.UNKNOWN,framework:"native",global:r}},Un=e=>e===Qs.WECHAT_MINIAPP||e===Qs.QQ_MINIAPP||e===Qs.TOUTIAO_MINIAPP||e===Qs.BAIDU_MINIAPP||e===Qs.ALIPAY_MINIAPP||e===Qs.DINGTALK_MINIAPP||e===Qs.LARK_MINIAPP||e===Qs.KUAISHOU_MINIAPP||e===Qs.JD_MINIAPP||e===Qs.MINIAPP_360||e===Qs.HARMONY_MINIAPP||e===Qs.QUICKAPP||e===Qs.UNIAPP,Ln=["request","upload","socket","proto"],kn=(e,t=Ln)=>{const r=((e,t=Ln)=>t.filter(t=>!e[t]))(e,t);if(0!==r.length)throw un("Platform missing required capabilities.",{code:nn,stage:Zs,retryable:!1,details:{required:[...t],missing:r}})};var Dn=null;try{Dn=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Pn(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function xn(e){return!0===(e&&e.__isLong__)}function Fn(e){var t=Math.clz32(e&-e);return e?31-t:t}Pn.prototype.__isLong__,Object.defineProperty(Pn.prototype,"__isLong__",{value:!0}),Pn.isLong=xn;var Bn={},Gn={};function qn(e,t){var r,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=Gn[e])?s:(r=jn(e,0,!0),n&&(Gn[e]=r),r):(n=-128<=(e|=0)&&e<128)&&(s=Bn[e])?s:(r=jn(e,e<0?-1:0,!1),n&&(Bn[e]=r),r)}function $n(e,t){if(isNaN(e))return t?Yn:Zn;if(t){if(e<0)return Yn;if(e>=Wn)return si}else{if(e<=-Jn)return ni;if(e+1>=Jn)return ri}return e<0?$n(-e,t).neg():jn(e%Hn|0,e/Hn|0,t)}function jn(e,t,r){return new Pn(e,t,r)}Pn.fromInt=qn,Pn.fromNumber=$n,Pn.fromBits=jn;var Vn=Math.pow;function Kn(e,t,r){if(0===e.length)throw Error("empty string");if("number"==typeof t?(r=t,t=!1):t=!!t,"NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return t?Yn:Zn;if((r=r||10)<2||36<r)throw RangeError("radix");var s;if((s=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return Kn(e.substring(1),t,r).neg();for(var n=$n(Vn(r,8)),i=Zn,o=0;o<e.length;o+=8){var a=Math.min(8,e.length-o),c=parseInt(e.substring(o,o+a),r);if(a<8){var d=$n(Vn(r,a));i=i.mul(d).add($n(c))}else i=(i=i.mul(n)).add($n(c))}return i.unsigned=t,i}function zn(e,t){return"number"==typeof e?$n(e,t):"string"==typeof e?Kn(e,t):jn(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}Pn.fromString=Kn,Pn.fromValue=zn;var Hn=4294967296,Wn=Hn*Hn,Jn=Wn/2,Qn=qn(1<<24),Zn=qn(0);Pn.ZERO=Zn;var Yn=qn(0,!0);Pn.UZERO=Yn;var Xn=qn(1);Pn.ONE=Xn;var ei=qn(1,!0);Pn.UONE=ei;var ti=qn(-1);Pn.NEG_ONE=ti;var ri=jn(-1,2147483647,!1);Pn.MAX_VALUE=ri;var si=jn(-1,-1,!0);Pn.MAX_UNSIGNED_VALUE=si;var ni=jn(0,-2147483648,!1);Pn.MIN_VALUE=ni;var ii=Pn.prototype;ii.toInt=function(){return this.unsigned?this.low>>>0:this.low},ii.toNumber=function(){return this.unsigned?(this.high>>>0)*Hn+(this.low>>>0):this.high*Hn+(this.low>>>0)},ii.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(ni)){var t=$n(e),r=this.div(t),s=r.mul(t).sub(this);return r.toString(e)+s.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var n=$n(Vn(e,6),this.unsigned),i=this,o="";;){var a=i.div(n),c=(i.sub(a.mul(n)).toInt()>>>0).toString(e);if((i=a).isZero())return c+o;for(;c.length<6;)c="0"+c;o=""+c+o}},ii.getHighBits=function(){return this.high},ii.getHighBitsUnsigned=function(){return this.high>>>0},ii.getLowBits=function(){return this.low},ii.getLowBitsUnsigned=function(){return this.low>>>0},ii.getNumBitsAbs=function(){if(this.isNegative())return this.eq(ni)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},ii.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&(-1===e&&!(0===this.low&&-2097152===this.high))},ii.isZero=function(){return 0===this.high&&0===this.low},ii.eqz=ii.isZero,ii.isNegative=function(){return!this.unsigned&&this.high<0},ii.isPositive=function(){return this.unsigned||this.high>=0},ii.isOdd=function(){return!(1&~this.low)},ii.isEven=function(){return!(1&this.low)},ii.equals=function(e){return xn(e)||(e=zn(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},ii.eq=ii.equals,ii.notEquals=function(e){return!this.eq(e)},ii.neq=ii.notEquals,ii.ne=ii.notEquals,ii.lessThan=function(e){return this.comp(e)<0},ii.lt=ii.lessThan,ii.lessThanOrEqual=function(e){return this.comp(e)<=0},ii.lte=ii.lessThanOrEqual,ii.le=ii.lessThanOrEqual,ii.greaterThan=function(e){return this.comp(e)>0},ii.gt=ii.greaterThan,ii.greaterThanOrEqual=function(e){return this.comp(e)>=0},ii.gte=ii.greaterThanOrEqual,ii.ge=ii.greaterThanOrEqual,ii.compare=function(e){if(xn(e)||(e=zn(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},ii.comp=ii.compare,ii.negate=function(){return!this.unsigned&&this.eq(ni)?ni:this.not().add(Xn)},ii.neg=ii.negate,ii.add=function(e){xn(e)||(e=zn(e));var t=this.high>>>16,r=65535&this.high,s=this.low>>>16,n=65535&this.low,i=e.high>>>16,o=65535&e.high,a=e.low>>>16,c=0,d=0,u=0,l=0;return u+=(l+=n+(65535&e.low))>>>16,d+=(u+=s+a)>>>16,c+=(d+=r+o)>>>16,c+=t+i,jn((u&=65535)<<16|(l&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},ii.subtract=function(e){return xn(e)||(e=zn(e)),this.add(e.neg())},ii.sub=ii.subtract,ii.multiply=function(e){if(this.isZero())return this;if(xn(e)||(e=zn(e)),Dn)return jn(Dn.mul(this.low,this.high,e.low,e.high),Dn.get_high(),this.unsigned);if(e.isZero())return this.unsigned?Yn:Zn;if(this.eq(ni))return e.isOdd()?ni:Zn;if(e.eq(ni))return this.isOdd()?ni:Zn;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Qn)&&e.lt(Qn))return $n(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,r=65535&this.high,s=this.low>>>16,n=65535&this.low,i=e.high>>>16,o=65535&e.high,a=e.low>>>16,c=65535&e.low,d=0,u=0,l=0,h=0;return l+=(h+=n*c)>>>16,u+=(l+=s*c)>>>16,l&=65535,u+=(l+=n*a)>>>16,d+=(u+=r*c)>>>16,u&=65535,d+=(u+=s*a)>>>16,u&=65535,d+=(u+=n*o)>>>16,d+=t*c+r*a+s*o+n*i,jn((l&=65535)<<16|(h&=65535),(d&=65535)<<16|(u&=65535),this.unsigned)},ii.mul=ii.multiply,ii.divide=function(e){if(xn(e)||(e=zn(e)),e.isZero())throw Error("division by zero");var t,r,s;if(Dn)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?jn((this.unsigned?Dn.div_u:Dn.div_s)(this.low,this.high,e.low,e.high),Dn.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Yn:Zn;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Yn;if(e.gt(this.shru(1)))return ei;s=Yn}else{if(this.eq(ni))return e.eq(Xn)||e.eq(ti)?ni:e.eq(ni)?Xn:(t=this.shr(1).div(e).shl(1)).eq(Zn)?e.isNegative()?Xn:ti:(r=this.sub(e.mul(t)),s=t.add(r.div(e)));if(e.eq(ni))return this.unsigned?Yn:Zn;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Zn}for(r=this;r.gte(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var n=Math.ceil(Math.log(t)/Math.LN2),i=n<=48?1:Vn(2,n-48),o=$n(t),a=o.mul(e);a.isNegative()||a.gt(r);)a=(o=$n(t-=i,this.unsigned)).mul(e);o.isZero()&&(o=Xn),s=s.add(o),r=r.sub(a)}return s},ii.div=ii.divide,ii.modulo=function(e){return xn(e)||(e=zn(e)),Dn?jn((this.unsigned?Dn.rem_u:Dn.rem_s)(this.low,this.high,e.low,e.high),Dn.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},ii.mod=ii.modulo,ii.rem=ii.modulo,ii.not=function(){return jn(~this.low,~this.high,this.unsigned)},ii.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},ii.clz=ii.countLeadingZeros,ii.countTrailingZeros=function(){return this.low?Fn(this.low):Fn(this.high)+32},ii.ctz=ii.countTrailingZeros,ii.and=function(e){return xn(e)||(e=zn(e)),jn(this.low&e.low,this.high&e.high,this.unsigned)},ii.or=function(e){return xn(e)||(e=zn(e)),jn(this.low|e.low,this.high|e.high,this.unsigned)},ii.xor=function(e){return xn(e)||(e=zn(e)),jn(this.low^e.low,this.high^e.high,this.unsigned)},ii.shiftLeft=function(e){return xn(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?jn(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):jn(0,this.low<<e-32,this.unsigned)},ii.shl=ii.shiftLeft,ii.shiftRight=function(e){return xn(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?jn(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):jn(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},ii.shr=ii.shiftRight,ii.shiftRightUnsigned=function(e){return xn(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?jn(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):jn(32===e?this.high:this.high>>>e-32,0,this.unsigned)},ii.shru=ii.shiftRightUnsigned,ii.shr_u=ii.shiftRightUnsigned,ii.rotateLeft=function(e){var t;return xn(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?jn(this.high,this.low,this.unsigned):e<32?(t=32-e,jn(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),jn(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},ii.rotl=ii.rotateLeft,ii.rotateRight=function(e){var t;return xn(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?jn(this.high,this.low,this.unsigned):e<32?(t=32-e,jn(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),jn(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},ii.rotr=ii.rotateRight,ii.toSigned=function(){return this.unsigned?jn(this.low,this.high,!1):this},ii.toUnsigned=function(){return this.unsigned?this:jn(this.low,this.high,!0)},ii.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},ii.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},ii.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},Pn.fromBytes=function(e,t,r){return r?Pn.fromBytesLE(e,t):Pn.fromBytesBE(e,t)},Pn.fromBytesLE=function(e,t){return new Pn(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},Pn.fromBytesBE=function(e,t){return new Pn(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},"function"==typeof BigInt&&(Pn.fromBigInt=function(e,t){return jn(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},Pn.fromValue=function(e,t){return"bigint"==typeof e?Pn.fromBigInt(e,t):zn(e,t)},ii.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e});var oi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function ai(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var r=function e(){var r=!1;try{r=this instanceof e}catch{}return r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}),r}var ci,di,ui={exports:{}},li={},hi={};function pi(){if(di)return ci;return di=1,ci=function(e,t){var r=new Array(arguments.length-1),s=0,n=2,i=!0;for(;n<arguments.length;)r[s++]=arguments[n++];return new Promise(function(n,o){r[s]=function(e){if(i)if(i=!1,e)o(e);else{for(var t=new Array(arguments.length-1),r=0;r<t.length;)t[r++]=arguments[r];n.apply(null,t)}};try{e.apply(t||null,r)}catch(a){i&&(i=!1,o(a))}})},ci}var mi,gi,fi,yi,vi,Ii={};var bi,_i,Ti,Ci,Si,Ei={};var wi,Ai,Ri,Ni,Oi,Mi,Ui,Li,ki,Di,Pi={exports:{}};Pi.exports;function xi(){return wi||(wi=1,e=Pi,t=Pi.exports,"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=null;try{t=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function r(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function s(e){return!0===(e&&e.__isLong__)}function n(e){var t=Math.clz32(e&-e);return e?31-t:t}r.prototype.__isLong__,Object.defineProperty(r.prototype,"__isLong__",{value:!0}),r.isLong=s;var i={},o={};function a(e,t){var r,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=o[e])?s:(r=d(e,0,!0),n&&(o[e]=r),r):(n=-128<=(e|=0)&&e<128)&&(s=i[e])?s:(r=d(e,e<0?-1:0,!1),n&&(i[e]=r),r)}function c(e,t){if(isNaN(e))return t?I:v;if(t){if(e<0)return I;if(e>=g)return S}else{if(e<=-f)return E;if(e+1>=f)return C}return e<0?c(-e,t).neg():d(e%m|0,e/m|0,t)}function d(e,t,s){return new r(e,t,s)}r.fromInt=a,r.fromNumber=c,r.fromBits=d;var u=Math.pow;function l(e,t,r){if(0===e.length)throw Error("empty string");if("number"==typeof t?(r=t,t=!1):t=!!t,"NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return t?I:v;if((r=r||10)<2||36<r)throw RangeError("radix");var s;if((s=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return l(e.substring(1),t,r).neg();for(var n=c(u(r,8)),i=v,o=0;o<e.length;o+=8){var a=Math.min(8,e.length-o),d=parseInt(e.substring(o,o+a),r);if(a<8){var h=c(u(r,a));i=i.mul(h).add(c(d))}else i=(i=i.mul(n)).add(c(d))}return i.unsigned=t,i}function h(e,t){return"number"==typeof e?c(e,t):"string"==typeof e?l(e,t):d(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}r.fromString=l,r.fromValue=h;var p=65536,m=p*p,g=m*m,f=g/2,y=a(1<<24),v=a(0);r.ZERO=v;var I=a(0,!0);r.UZERO=I;var b=a(1);r.ONE=b;var _=a(1,!0);r.UONE=_;var T=a(-1);r.NEG_ONE=T;var C=d(-1,2147483647,!1);r.MAX_VALUE=C;var S=d(-1,-1,!0);r.MAX_UNSIGNED_VALUE=S;var E=d(0,-2147483648,!1);r.MIN_VALUE=E;var w=r.prototype;w.toInt=function(){return this.unsigned?this.low>>>0:this.low},w.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},w.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(E)){var t=c(e),r=this.div(t),s=r.mul(t).sub(this);return r.toString(e)+s.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var n=c(u(e,6),this.unsigned),i=this,o="";;){var a=i.div(n),d=(i.sub(a.mul(n)).toInt()>>>0).toString(e);if((i=a).isZero())return d+o;for(;d.length<6;)d="0"+d;o=""+d+o}},w.getHighBits=function(){return this.high},w.getHighBitsUnsigned=function(){return this.high>>>0},w.getLowBits=function(){return this.low},w.getLowBitsUnsigned=function(){return this.low>>>0},w.getNumBitsAbs=function(){if(this.isNegative())return this.eq(E)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},w.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&-1===e&&!(0===this.low&&-2097152===this.high)},w.isZero=function(){return 0===this.high&&0===this.low},w.eqz=w.isZero,w.isNegative=function(){return!this.unsigned&&this.high<0},w.isPositive=function(){return this.unsigned||this.high>=0},w.isOdd=function(){return!(1&~this.low)},w.isEven=function(){return!(1&this.low)},w.equals=function(e){return s(e)||(e=h(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},w.eq=w.equals,w.notEquals=function(e){return!this.eq(e)},w.neq=w.notEquals,w.ne=w.notEquals,w.lessThan=function(e){return this.comp(e)<0},w.lt=w.lessThan,w.lessThanOrEqual=function(e){return this.comp(e)<=0},w.lte=w.lessThanOrEqual,w.le=w.lessThanOrEqual,w.greaterThan=function(e){return this.comp(e)>0},w.gt=w.greaterThan,w.greaterThanOrEqual=function(e){return this.comp(e)>=0},w.gte=w.greaterThanOrEqual,w.ge=w.greaterThanOrEqual,w.compare=function(e){if(s(e)||(e=h(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},w.comp=w.compare,w.negate=function(){return!this.unsigned&&this.eq(E)?E:this.not().add(b)},w.neg=w.negate,w.add=function(e){s(e)||(e=h(e));var t=this.high>>>16,r=65535&this.high,n=this.low>>>16,i=65535&this.low,o=e.high>>>16,a=65535&e.high,c=e.low>>>16,u=0,l=0,p=0,m=0;return p+=(m+=i+(65535&e.low))>>>16,l+=(p+=n+c)>>>16,u+=(l+=r+a)>>>16,u+=t+o,d((p&=65535)<<16|(m&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},w.subtract=function(e){return s(e)||(e=h(e)),this.add(e.neg())},w.sub=w.subtract,w.multiply=function(e){if(this.isZero())return this;if(s(e)||(e=h(e)),t)return d(t.mul(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned);if(e.isZero())return this.unsigned?I:v;if(this.eq(E))return e.isOdd()?E:v;if(e.eq(E))return this.isOdd()?E:v;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(y)&&e.lt(y))return c(this.toNumber()*e.toNumber(),this.unsigned);var r=this.high>>>16,n=65535&this.high,i=this.low>>>16,o=65535&this.low,a=e.high>>>16,u=65535&e.high,l=e.low>>>16,p=65535&e.low,m=0,g=0,f=0,b=0;return f+=(b+=o*p)>>>16,g+=(f+=i*p)>>>16,f&=65535,g+=(f+=o*l)>>>16,m+=(g+=n*p)>>>16,g&=65535,m+=(g+=i*l)>>>16,g&=65535,m+=(g+=o*u)>>>16,m+=r*p+n*l+i*u+o*a,d((f&=65535)<<16|(b&=65535),(m&=65535)<<16|(g&=65535),this.unsigned)},w.mul=w.multiply,w.divide=function(e){if(s(e)||(e=h(e)),e.isZero())throw Error("division by zero");var r,n,i;if(t)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?d((this.unsigned?t.div_u:t.div_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?I:v;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return I;if(e.gt(this.shru(1)))return _;i=I}else{if(this.eq(E))return e.eq(b)||e.eq(T)?E:e.eq(E)?b:(r=this.shr(1).div(e).shl(1)).eq(v)?e.isNegative()?b:T:(n=this.sub(e.mul(r)),i=r.add(n.div(e)));if(e.eq(E))return this.unsigned?I:v;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();i=v}for(n=this;n.gte(e);){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var o=Math.ceil(Math.log(r)/Math.LN2),a=o<=48?1:u(2,o-48),l=c(r),p=l.mul(e);p.isNegative()||p.gt(n);)p=(l=c(r-=a,this.unsigned)).mul(e);l.isZero()&&(l=b),i=i.add(l),n=n.sub(p)}return i},w.div=w.divide,w.modulo=function(e){return s(e)||(e=h(e)),t?d((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},w.mod=w.modulo,w.rem=w.modulo,w.not=function(){return d(~this.low,~this.high,this.unsigned)},w.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},w.clz=w.countLeadingZeros,w.countTrailingZeros=function(){return this.low?n(this.low):n(this.high)+32},w.ctz=w.countTrailingZeros,w.and=function(e){return s(e)||(e=h(e)),d(this.low&e.low,this.high&e.high,this.unsigned)},w.or=function(e){return s(e)||(e=h(e)),d(this.low|e.low,this.high|e.high,this.unsigned)},w.xor=function(e){return s(e)||(e=h(e)),d(this.low^e.low,this.high^e.high,this.unsigned)},w.shiftLeft=function(e){return s(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):d(0,this.low<<e-32,this.unsigned)},w.shl=w.shiftLeft,w.shiftRight=function(e){return s(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):d(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},w.shr=w.shiftRight,w.shiftRightUnsigned=function(e){return s(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?d(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):d(32===e?this.high:this.high>>>e-32,0,this.unsigned)},w.shru=w.shiftRightUnsigned,w.shr_u=w.shiftRightUnsigned,w.rotateLeft=function(e){var t;return s(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?d(this.high,this.low,this.unsigned):e<32?(t=32-e,d(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),d(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},w.rotl=w.rotateLeft,w.rotateRight=function(e){var t;return s(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?d(this.high,this.low,this.unsigned):e<32?(t=32-e,d(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),d(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},w.rotr=w.rotateRight,w.toSigned=function(){return this.unsigned?d(this.low,this.high,!1):this},w.toUnsigned=function(){return this.unsigned?this:d(this.low,this.high,!0)},w.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},w.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},w.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},r.fromBytes=function(e,t,s){return s?r.fromBytesLE(e,t):r.fromBytesBE(e,t)},r.fromBytesLE=function(e,t){return new r(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},r.fromBytesBE=function(e,t){return new r(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},"function"==typeof BigInt&&(r.fromBigInt=function(e,t){return d(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},r.fromValue=function(e,t){return"bigint"==typeof e?r.fromBigInt(e,t):h(e,t)},w.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e}),e.default=r}(t),e.exports=(r=t).default||r),Pi.exports;var e,t,r}function Fi(){return Ai||(Ai=1,function(e){var t,r,s=e;function n(e){return"__proto__"===e||"prototype"===e||"constructor"===e}function i(e){var t="boolean"==typeof arguments[arguments.length-1],r=t?arguments.length-1:arguments.length;t=t&&arguments[arguments.length-1];for(var s=1;s<r;++s){var i=arguments[s];if(i)for(var o=Object.keys(i),a=0;a<o.length;++a)n(o[a])||void 0!==e[o[a]]&&t||(e[o[a]]=i[o[a]])}return e}function o(e){function t(e,r){if(!(this instanceof t))return new t(e,r);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),r&&i(this,r)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}s.asPromise=pi(),s.base64=(mi||(mi=1,function(e){var t=e;t.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var r=new Array(64),s=new Array(123),n=0;n<64;)s[r[n]=n<26?n+65:n<52?n+71:n<62?n-4:n-59|43]=n++;t.encode=function(e,t,s){for(var n,i=null,o=[],a=0,c=0;t<s;){var d=e[t++];switch(c){case 0:o[a++]=r[d>>2],n=(3&d)<<4,c=1;break;case 1:o[a++]=r[n|d>>4],n=(15&d)<<2,c=2;break;case 2:o[a++]=r[n|d>>6],o[a++]=r[63&d],c=0}a>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=r[n],o[a++]=61,1===c&&(o[a++]=61)),i?(a&&i.push(String.fromCharCode.apply(String,o.slice(0,a))),i.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var i="invalid encoding";t.decode=function(e,t,r){for(var n,o=r,a=0,c=0;c<e.length;){var d=e.charCodeAt(c++);if(61===d&&a>1)break;if(void 0===(d=s[d]))throw Error(i);switch(a){case 0:n=d,a=1;break;case 1:t[r++]=n<<2|(48&d)>>4,n=d,a=2;break;case 2:t[r++]=(15&n)<<4|(60&d)>>2,n=d,a=3;break;case 3:t[r++]=(3&n)<<6|d,a=0}}if(1===a)throw Error(i);return r-o},t.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}(Ii)),Ii),s.EventEmitter=function(){if(fi)return gi;function e(){this._listeners=Object.create(null)}return fi=1,gi=e,e.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},e.prototype.off=function(e,t){if(void 0===e)this._listeners=Object.create(null);else if(void 0===t)this._listeners[e]=[];else{var r=this._listeners[e];if(!r)return this;for(var s=0;s<r.length;)r[s].fn===t?r.splice(s,1):++s}return this},e.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var r=[],s=1;s<arguments.length;)r.push(arguments[s++]);for(s=0;s<t.length;)t[s].fn.apply(t[s++].ctx,r)}return this},gi}(),s.float=function(){if(vi)return yi;function e(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),s=128===r[3];function n(e,s,n){t[0]=e,s[n]=r[0],s[n+1]=r[1],s[n+2]=r[2],s[n+3]=r[3]}function i(e,s,n){t[0]=e,s[n]=r[3],s[n+1]=r[2],s[n+2]=r[1],s[n+3]=r[0]}function o(e,s){return r[0]=e[s],r[1]=e[s+1],r[2]=e[s+2],r[3]=e[s+3],t[0]}function a(e,s){return r[3]=e[s],r[2]=e[s+1],r[1]=e[s+2],r[0]=e[s+3],t[0]}e.writeFloatLE=s?n:i,e.writeFloatBE=s?i:n,e.readFloatLE=s?o:a,e.readFloatBE=s?a:o}():function(){function i(e,t,r,s){var n=t<0?1:0;if(n&&(t=-t),0===t)e(1/t>0?0:2147483648,r,s);else if(isNaN(t))e(2143289344,r,s);else if(t>34028234663852886e22)e((n<<31|2139095040)>>>0,r,s);else if(t<11754943508222875e-54)e((n<<31|Math.round(t/1401298464324817e-60))>>>0,r,s);else{var i=Math.floor(Math.log(t)/Math.LN2);e((n<<31|i+127<<23|8388607&Math.round(t*Math.pow(2,-i)*8388608))>>>0,r,s)}}function o(e,t,r){var s=e(t,r),n=2*(s>>31)+1,i=s>>>23&255,o=8388607&s;return 255===i?o?NaN:n*(1/0):0===i?1401298464324817e-60*n*o:n*Math.pow(2,i-150)*(o+8388608)}e.writeFloatLE=i.bind(null,t),e.writeFloatBE=i.bind(null,r),e.readFloatLE=o.bind(null,s),e.readFloatBE=o.bind(null,n)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),s=128===r[7];function n(e,s,n){t[0]=e,s[n]=r[0],s[n+1]=r[1],s[n+2]=r[2],s[n+3]=r[3],s[n+4]=r[4],s[n+5]=r[5],s[n+6]=r[6],s[n+7]=r[7]}function i(e,s,n){t[0]=e,s[n]=r[7],s[n+1]=r[6],s[n+2]=r[5],s[n+3]=r[4],s[n+4]=r[3],s[n+5]=r[2],s[n+6]=r[1],s[n+7]=r[0]}function o(e,s){return r[0]=e[s],r[1]=e[s+1],r[2]=e[s+2],r[3]=e[s+3],r[4]=e[s+4],r[5]=e[s+5],r[6]=e[s+6],r[7]=e[s+7],t[0]}function a(e,s){return r[7]=e[s],r[6]=e[s+1],r[5]=e[s+2],r[4]=e[s+3],r[3]=e[s+4],r[2]=e[s+5],r[1]=e[s+6],r[0]=e[s+7],t[0]}e.writeDoubleLE=s?n:i,e.writeDoubleBE=s?i:n,e.readDoubleLE=s?o:a,e.readDoubleBE=s?a:o}():function(){function i(e,t,r,s,n,i){var o=s<0?1:0;if(o&&(s=-s),0===s)e(0,n,i+t),e(1/s>0?0:2147483648,n,i+r);else if(isNaN(s))e(0,n,i+t),e(2146959360,n,i+r);else if(s>17976931348623157e292)e(0,n,i+t),e((o<<31|2146435072)>>>0,n,i+r);else{var a;if(s<22250738585072014e-324)e((a=s/5e-324)>>>0,n,i+t),e((o<<31|a/4294967296)>>>0,n,i+r);else{var c=Math.floor(Math.log(s)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=s*Math.pow(2,-c))>>>0,n,i+t),e((o<<31|c+1023<<20|1048576*a&1048575)>>>0,n,i+r)}}}function o(e,t,r,s,n){var i=e(s,n+t),o=e(s,n+r),a=2*(o>>31)+1,c=o>>>20&2047,d=4294967296*(1048575&o)+i;return 2047===c?d?NaN:a*(1/0):0===c?5e-324*a*d:a*Math.pow(2,c-1075)*(d+4503599627370496)}e.writeDoubleLE=i.bind(null,t,0,4),e.writeDoubleBE=i.bind(null,r,4,0),e.readDoubleLE=o.bind(null,s,0,4),e.readDoubleBE=o.bind(null,n,4,0)}(),e}function t(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function r(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function n(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}return vi=1,yi=e(e)}(),s.utf8=(bi||(bi=1,r=65533,(t=Ei).length=function(e){for(var t=0,r=0,s=0;s<e.length;++s)(r=e.charCodeAt(s))<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(s+1))?(++s,t+=4):t+=3;return t},t.read=function(e,t,s){if(s-t<1)return"";for(var n,i,o,a,c=null,d=[],u=0;t<s;)(n=e[t++])<=127?d[u++]=n:n>=192&&n<224?(o=(31&n)<<6|63&e[t++],d[u++]=o>=128?o:r):n>=224&&n<240?(a=(15&n)<<12|(63&e[t++])<<6|63&e[t++],d[u++]=a>=2048?a:r):n>=240&&((i=(7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])<65536||i>1114111?d[u++]=r:(i-=65536,d[u++]=55296+(i>>10),d[u++]=56320+(1023&i))),u>8191&&((c||(c=[])).push(String.fromCharCode.apply(String,d.slice(0,u))),u=0);return c?(u&&c.push(String.fromCharCode.apply(String,d.slice(0,u))),c.join("")):String.fromCharCode.apply(String,d.slice(0,u))},t.write=function(e,t,r){for(var s,n,i=r,o=0;o<e.length;++o)(s=e.charCodeAt(o))<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(n=e.charCodeAt(o+1)))?(s=65536+((1023&s)<<10)+(1023&n),++o,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-i}),Ei),s.pool=Ti?_i:(Ti=1,_i=function(e,t,r){var s=r||8192,n=s>>>1,i=null,o=s;return function(r){if(r<1||r>n)return e(r);o+r>s&&(i=e(s),o=0);var a=t.call(i,o,o+=r);return 7&o&&(o=1+(7|o)),a}}),s.LongBits=function(){if(Si)return Ci;Si=1,Ci=t;var e=Fi();function t(e,t){this.lo=e>>>0,this.hi=t>>>0}var r=t.zero=new t(0,0);r.toNumber=function(){return 0},r.zzEncode=r.zzDecode=function(){return this},r.length=function(){return 1};var s=t.zeroHash="\0\0\0\0\0\0\0\0";t.fromNumber=function(e){if(0===e)return r;var s=e<0;s&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return s&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new t(n,i)},t.from=function(s){if("number"==typeof s)return t.fromNumber(s);if(e.isString(s)){if(!e.Long)return t.fromNumber(parseInt(s,10));s=e.Long.fromString(s)}return s.low||s.high?new t(s.low>>>0,s.high>>>0):r},t.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},t.prototype.toLong=function(t){return e.Long?new e.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var n=String.prototype.charCodeAt;return t.fromHash=function(e){return e===s?r:new t((n.call(e,0)|n.call(e,1)<<8|n.call(e,2)<<16|n.call(e,3)<<24)>>>0,(n.call(e,4)|n.call(e,5)<<8|n.call(e,6)<<16|n.call(e,7)<<24)>>>0)},t.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},t.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},t.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},t.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10},Ci}(),s.isUnsafeProperty=n,s.isNode=Boolean(void 0!==oi&&oi&&oi.process&&oi.process.versions&&oi.process.versions.node),s.global=s.isNode&&oi||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||hi,s.emptyArray=Object.freeze?Object.freeze([]):[],s.emptyObject=Object.freeze?Object.freeze({}):{},s.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},s.isString=function(e){return"string"==typeof e||e instanceof String},s.isObject=function(e){return e&&"object"==typeof e},s.isset=s.isSet=function(e,t){var r=e[t];return!(null==r||!Object.hasOwnProperty.call(e,t))&&("object"!=typeof r||(Array.isArray(r)?r.length:Object.keys(r).length)>0)},s.Buffer=function(){try{var e=s.global.Buffer;return e.prototype.utf8Write?e:null}catch(t){return null}}(),s._Buffer_from=null,s._Buffer_allocUnsafe=null,s.newBuffer=function(e){return"number"==typeof e?s.Buffer?s._Buffer_allocUnsafe(e):new s.Array(e):s.Buffer?s._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},s.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,s.Long=s.global.dcodeIO&&s.global.dcodeIO.Long||s.global.Long||function(){try{var e=xi();return e&&e.isLong?e:null}catch(t){return null}}(),s.key2Re=/^true|false|0|1$/,s.key32Re=/^-?(?:0|[1-9][0-9]*)$/,s.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,s.longToHash=function(e){return e?s.LongBits.from(e).toHash():s.LongBits.zeroHash},s.longFromHash=function(e,t){var r=s.LongBits.fromHash(e);return s.Long?s.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},s.merge=i,s.nestingLimit=32,s.recursionLimit=100,s.makeProp=function(e,t){Object.defineProperty(e,t,{enumerable:!0,configurable:!0,writable:!0})},s.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},s.newError=o,s.ProtocolError=o("ProtocolError"),s.oneOfGetter=function(e){for(var t={},r=0;r<e.length;++r)t[e[r]]=1;return function(){for(var e=Object.keys(this),r=e.length-1;r>-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},s.oneOfSetter=function(e){return function(t){for(var r=0;r<e.length;++r)e[r]!==t&&delete this[e[r]]}},s.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},s._configure=function(){var e=s.Buffer;e?(s._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,r){return new e(t,r)},s._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):s._Buffer_from=s._Buffer_allocUnsafe=null}}(hi)),hi}function Bi(){if(Ni)return Ri;Ni=1,Ri=c;var e,t=Fi(),r=t.LongBits,s=t.base64,n=t.utf8;function i(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function o(){}function a(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function c(){this.len=0,this.head=new i(o,0,0),this.tail=this.head,this.states=null}var d=function(){return t.Buffer?function(){return(c.create=function(){return new e})()}:function(){return new c}};function u(e,t,r){t[r]=255&e}function l(e,t){this.len=e,this.next=void 0,this.val=t}function h(e,t,r){for(var s=e.lo,n=e.hi;n;)t[r++]=127&s|128,s=(s>>>7|n<<25)>>>0,n>>>=7;for(;s>127;)t[r++]=127&s|128,s>>>=7;t[r++]=s}function p(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}c.create=d(),c.alloc=function(e){return new t.Array(e)},t.Array!==Array&&(c.alloc=t.pool(c.alloc,t.Array.prototype.subarray)),c.prototype._push=function(e,t,r){return this.tail=this.tail.next=new i(e,t,r),this.len+=t,this},l.prototype=Object.create(i.prototype),l.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},c.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new l((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},c.prototype.int32=function(e){return(e|=0)<0?this._push(h,10,r.fromNumber(e)):this.uint32(e)},c.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},c.prototype.uint64=function(e){var t=r.from(e);return this._push(h,t.length(),t)},c.prototype.int64=c.prototype.uint64,c.prototype.sint64=function(e){var t=r.from(e).zzEncode();return this._push(h,t.length(),t)},c.prototype.bool=function(e){return this._push(u,1,e?1:0)},c.prototype.fixed32=function(e){return this._push(p,4,e>>>0)},c.prototype.sfixed32=c.prototype.fixed32,c.prototype.fixed64=function(e){var t=r.from(e);return this._push(p,4,t.lo)._push(p,4,t.hi)},c.prototype.sfixed64=c.prototype.fixed64,c.prototype.float=function(e){return this._push(t.float.writeFloatLE,4,e)},c.prototype.double=function(e){return this._push(t.float.writeDoubleLE,8,e)};var m=t.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var s=0;s<e.length;++s)t[r+s]=e[s]};return c.prototype.bytes=function(e){var r=e.length>>>0;if(!r)return this._push(u,1,0);if(t.isString(e)){var n=c.alloc(r=s.length(e));s.decode(e,n,0),e=n}return this.uint32(r)._push(m,r,e)},c.prototype.string=function(e){var t=n.length(e);return t?this.uint32(t)._push(n.write,t,e):this._push(u,1,0)},c.prototype.fork=function(){return this.states=new a(this),this.head=this.tail=new i(o,0,0),this.len=0,this},c.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new i(o,0,0),this.len=0),this},c.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},c.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},c._configure=function(t){e=t,c.create=d(),e._configure()},Ri}function Gi(){if(Li)return Ui;Li=1,Ui=i;var e,t=Fi(),r=t.LongBits,s=t.utf8;function n(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function i(e){this.buf=e,this.pos=0,this.len=e.length}var o="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new i(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new i(e);throw Error("illegal buffer")},a=function(){return t.Buffer?function(r){return(i.create=function(r){return t.Buffer.isBuffer(r)?new e(r):o(r)})(r)}:o};function c(){var e=new r(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw n(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw n(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function d(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function u(){if(this.pos+8>this.len)throw n(this,8);return new r(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}return i.create=a(),i.prototype._slice=t.Array.prototype.subarray||t.Array.prototype.slice,i.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,n(this,10);return e}}(),i.prototype.int32=function(){return 0|this.uint32()},i.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},i.prototype.bool=function(){return 0!==this.uint32()},i.prototype.fixed32=function(){if(this.pos+4>this.len)throw n(this,4);return d(this.buf,this.pos+=4)},i.prototype.sfixed32=function(){if(this.pos+4>this.len)throw n(this,4);return 0|d(this.buf,this.pos+=4)},i.prototype.float=function(){if(this.pos+4>this.len)throw n(this,4);var e=t.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},i.prototype.double=function(){if(this.pos+8>this.len)throw n(this,4);var e=t.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},i.prototype.bytes=function(){var e=this.uint32(),r=this.pos,s=this.pos+e;if(s>this.len)throw n(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(r,s);if(r===s){var i=t.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,s)},i.prototype.string=function(){var e=this.bytes();return s.read(e,0,e.length)},i.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw n(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw n(this)}while(128&this.buf[this.pos++]);return this},i.recursionLimit=t.recursionLimit,i.prototype.skipType=function(e,t){if(void 0===t&&(t=0),t>i.recursionLimit)throw Error("maximum nesting depth exceeded");switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e,t+1);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},i._configure=function(r){e=r,i.create=a(),e._configure();var s=t.Long?"toLong":"toNumber";t.merge(i.prototype,{int64:function(){return c.call(this)[s](!1)},uint64:function(){return c.call(this)[s](!0)},sint64:function(){return c.call(this).zzDecode()[s](!1)},fixed64:function(){return u.call(this)[s](!0)},sfixed64:function(){return u.call(this)[s](!1)}})},Ui}var qi,$i,ji,Vi,Ki,zi,Hi={};function Wi(){return ji||(ji=1,Hi.Service=function(){if($i)return qi;$i=1,qi=t;var e=Fi();function t(t,r,s){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");e.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=Boolean(r),this.responseDelimited=Boolean(s)}return(t.prototype=Object.create(e.EventEmitter.prototype)).constructor=t,t.prototype.rpcCall=function t(r,s,n,i,o){if(!i)throw TypeError("request must be specified");var a=this;if(!o)return e.asPromise(t,a,r,s,n,i);if(a.rpcImpl)try{return a.rpcImpl(r,s[a.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(e,t){if(e)return a.emit("error",e,r),o(e);if(null!==t){if(!(t instanceof n))try{t=n[a.responseDelimited?"decodeDelimited":"decode"](t)}catch(s){return a.emit("error",s,r),o(s)}return a.emit("data",t,r),o(null,t)}a.end(!0)})}catch(c){return a.emit("error",c,r),void setTimeout(function(){o(c)},0)}else setTimeout(function(){o(Error("already ended"))},0)},t.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this},qi}()),Hi}function Ji(){return Ki?Vi:(Ki=1,Vi=Object.create(null))}function Qi(){return zi||(zi=1,function(e){var t=e;function r(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}t.build="minimal",t.Writer=Bi(),t.BufferWriter=function(){if(Mi)return Oi;Mi=1,Oi=r;var e=Bi();(r.prototype=Object.create(e.prototype)).constructor=r;var t=Fi();function r(){e.call(this)}function s(e,r,s){e.length<40?t.utf8.write(e,r,s):r.utf8Write?r.utf8Write(e,s):r.write(e,s)}return r._configure=function(){r.alloc=t._Buffer_allocUnsafe,r.writeBytesBuffer=t.Buffer&&t.Buffer.prototype instanceof Uint8Array&&"set"===t.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var s=0;s<e.length;)t[r++]=e[s++]}},r.prototype.bytes=function(e){t.isString(e)&&(e=t._Buffer_from(e,"base64"));var s=e.length>>>0;return this.uint32(s),s&&this._push(r.writeBytesBuffer,s,e),this},r.prototype.string=function(e){var r=t.Buffer.byteLength(e);return this.uint32(r),r&&this._push(s,r,e),this},r._configure(),Oi}(),t.Reader=Gi(),t.BufferReader=function(){if(Di)return ki;Di=1,ki=r;var e=Gi();(r.prototype=Object.create(e.prototype)).constructor=r;var t=Fi();function r(t){e.call(this,t)}return r._configure=function(){t.Buffer&&(r.prototype._slice=t.Buffer.prototype.slice)},r.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},r._configure(),ki}(),t.util=Fi(),t.rpc=Wi(),t.roots=Ji(),t.configure=r,r()}(li)),li}var Zi,Yi,Xi={},eo={exports:{}};function to(){if(Yi)return Zi;Yi=1,Zi=t;var e=/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/;function t(r,s){"string"==typeof r&&(s=r,r=void 0);var n=[];function i(e){if("string"!=typeof e){var r=o();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var s=Object.keys(e),a=new Array(s.length+1),c=new Array(s.length),d=0;d<s.length;)a[d]=s[d],c[d]=e[s[d++]];return a[d]=r,Function.apply(null,a).apply(null,c)}return Function(r)()}for(var u=new Array(arguments.length-1),l=0;l<u.length;)u[l]=arguments[++l];if(l=0,e=e.replace(/%([%dfijs])/g,function(e,t){var r=u[l++];switch(t){case"d":case"f":return String(Number(r));case"i":return String(Math.floor(r));case"j":return JSON.stringify(r);case"s":return String(r)}return"%"}),l!==u.length)throw Error("parameter count mismatch");return n.push(e),i}function o(t){return"function "+function(t){if(!t)return"";if(!(t=String(t).replace(/[^\w$]/g,"")))return"";/^\d/.test(t)&&(t="_"+t);return e.test(t)?t+"_":t}(t||s)+"("+(r&&r.join(",")||"")+"){\n "+n.join("\n ")+"\n}"}return i.toString=o,i}return t.verbose=!1,Zi}const ro=ai(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var so,no,io,oo;function ao(){if(oo)return io;oo=1,io=r;var e=pi(),t=function(){if(no)return so;no=1;var e=null;try{(e=ro)&&e.readFile&&e.readFileSync||(e=null)}catch(t){}return so=e}();function r(s,n,i){return"function"==typeof n?(i=n,n={}):n||(n={}),i?!n.xhr&&t&&t.readFile?t.readFile(s,function(e,t){return e&&"undefined"!=typeof XMLHttpRequest?r.xhr(s,n,i):e?i(e):i(null,n.binary?t:t.toString("utf8"))}):r.xhr(s,n,i):e(r,this,s,n)}return r.xhr=function(e,t,r){var s=new XMLHttpRequest;s.onreadystatechange=function(){if(4===s.readyState){if(0!==s.status&&200!==s.status)return r(Error("status "+s.status));if(t.binary){var e=s.response;if(!e){e=[];for(var n=0;n<s.responseText.length;++n)e.push(255&s.responseText.charCodeAt(n))}return r(null,"undefined"!=typeof Uint8Array?new Uint8Array(e):e)}return r(null,s.responseText)}},t.binary&&("overrideMimeType"in s&&s.overrideMimeType("text/plain; charset=x-user-defined"),s.responseType="arraybuffer"),s.open("GET",e),s.send()},io}var co,uo={};var lo,ho,po,mo,go,fo,yo,vo,Io,bo,_o,To,Co,So,Eo,wo,Ao,Ro={};function No(){if(go)return mo;go=1,mo=c;var e=pa();((c.prototype=Object.create(e.prototype)).constructor=c).className="Namespace";var t,r,s,n=la(),i=da(),o=ha();function a(e,t){if(e&&e.length){for(var r={},s=0;s<e.length;++s)r[e[s].name]=e[s].toJSON(t);return r}}function c(t,r){e.call(this,t,r),this.nested=void 0,this._nestedArray=null,this._lookupCache=Object.create(null),this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0}function d(e){e._nestedArray=null,e._lookupCache=Object.create(null);for(var t=e;t=t.parent;)t._lookupCache=Object.create(null);return e}return c.fromJSON=function(e,t,r){return r=i.checkDepth(r),new c(e,t.options).addJSON(t.nested,r)},c.arrayToJSON=a,c.isReservedId=function(e,t){if(e)for(var r=0;r<e.length;++r)if("string"!=typeof e[r]&&e[r][0]<=t&&e[r][1]>t)return!0;return!1},c.isReservedName=function(e,t){if(e)for(var r=0;r<e.length;++r)if(e[r]===t)return!0;return!1},Object.defineProperty(c.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=i.toArray(this.nested))}}),c.prototype.toJSON=function(e){return i.toObject(["options",this.options,"nested",a(this.nestedArray,e)])},c.prototype.addJSON=function(e,o){o=i.checkDepth(o);if(e)for(var a,d=Object.keys(e),u=0;u<d.length;++u)a=e[d[u]],this.add((void 0!==a.fields?t.fromJSON:void 0!==a.values?s.fromJSON:void 0!==a.methods?r.fromJSON:void 0!==a.id?n.fromJSON:c.fromJSON)(d[u],a,o+1));return this},c.prototype.get=function(e){return this.nested&&Object.prototype.hasOwnProperty.call(this.nested,e)?this.nested[e]:null},c.prototype.getEnum=function(e){if(this.nested&&Object.prototype.hasOwnProperty.call(this.nested,e)&&this.nested[e]instanceof s)return this.nested[e].values;throw Error("no such enum: "+e)},c.prototype.add=function(e){if(!(e instanceof n&&void 0!==e.extend||e instanceof t||e instanceof o||e instanceof s||e instanceof r||e instanceof c))throw TypeError("object must be a valid nested object");if("__proto__"===e.name)return this;if(this.nested){var i=this.get(e.name);if(i){if(!(i instanceof c&&e instanceof c)||i instanceof t||i instanceof r)throw Error("duplicate name '"+e.name+"' in "+this);for(var a=i.nestedArray,u=0;u<a.length;++u)e.add(a[u]);this.remove(i),this.nested||(this.nested={}),e.setOptions(i.options,!0)}}else this.nested={};this.nested[e.name]=e,this instanceof t||this instanceof r||this instanceof s||this instanceof n||e._edition||(e._edition=e._defaultEdition),this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0;for(var l=this;l=l.parent;)l._needsRecursiveFeatureResolution=!0,l._needsRecursiveResolve=!0;return e.onAdd(this),d(this)},c.prototype.remove=function(t){if(!(t instanceof e))throw TypeError("object must be a ReflectionObject");if(t.parent!==this)throw Error(t+" is not a member of "+this);return delete this.nested[t.name],Object.keys(this.nested).length||(this.nested=void 0),t.onRemove(this),d(this)},c.prototype.define=function(e,t){if(i.isString(e))e=e.split(".");else if(!Array.isArray(e))throw TypeError("illegal path");if(e&&e.length&&""===e[0])throw Error("path must be relative");if(e.length>i.recursionLimit)throw Error("max depth exceeded");for(var r=this;e.length>0;){var s=e.shift();if(r.nested&&r.nested[s]){if(!((r=r.nested[s])instanceof c))throw Error("path conflicts with non-namespace objects")}else r.add(r=new c(s))}return t&&r.addJSON(t),r},c.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;this._resolveFeaturesRecursive(this._edition);var e=this.nestedArray,t=0;for(this.resolve();t<e.length;)e[t]instanceof c?e[t++].resolveAll():e[t++].resolve();return this._needsRecursiveResolve=!1,this},c.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(this._needsRecursiveFeatureResolution=!1,t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.nestedArray.forEach(e=>{e._resolveFeaturesRecursive(t)}),this):this},c.prototype.lookup=function(e,t,r){if("boolean"==typeof t?(r=t,t=void 0):t&&!Array.isArray(t)&&(t=[t]),i.isString(e)&&e.length){if("."===e)return this.root;e=e.split(".")}else if(!e.length)return this;var s=e.join(".");if(""===e[0])return this.root.lookup(e.slice(1),t);var n=this.root._fullyQualifiedObjects&&this.root._fullyQualifiedObjects["."+s];if(n&&(!t||t.indexOf(n.constructor)>-1))return n;if((n=this._lookupImpl(e,s))&&(!t||t.indexOf(n.constructor)>-1))return n;if(r)return null;for(var o=this;o.parent;){if((n=o.parent._lookupImpl(e,s))&&(!t||t.indexOf(n.constructor)>-1))return n;o=o.parent}return null},c.prototype._lookupImpl=function(e,t){if(Object.prototype.hasOwnProperty.call(this._lookupCache,t))return this._lookupCache[t];var r=this.get(e[0]),s=null;if(r)1===e.length?s=r:r instanceof c&&(e=e.slice(1),s=r._lookupImpl(e,e.join(".")));else for(var n=0;n<this.nestedArray.length;++n)if(this._nestedArray[n]instanceof c&&(r=this._nestedArray[n]._lookupImpl(e,t))){s=r;break}return this._lookupCache[t]=s,s},c.prototype.lookupType=function(e){var r=this.lookup(e,[t]);if(!r)throw Error("no such type: "+e);return r},c.prototype.lookupEnum=function(e){var t=this.lookup(e,[s]);if(!t)throw Error("no such Enum '"+e+"' in "+this);return t},c.prototype.lookupTypeOrEnum=function(e){var r=this.lookup(e,[t,s]);if(!r)throw Error("no such Type or Enum '"+e+"' in "+this);return r},c.prototype.lookupService=function(e){var t=this.lookup(e,[r]);if(!t)throw Error("no such Service '"+e+"' in "+this);return t},c._configure=function(e,n,i){t=e,r=n,s=i},mo}function Oo(){if(yo)return fo;yo=1,fo=s;var e=la();((s.prototype=Object.create(e.prototype)).constructor=s).className="MapField";var t=ua(),r=da();function s(t,s,n,i,o,a){if(e.call(this,t,s,i,void 0,void 0,o,a),!r.isString(n))throw TypeError("keyType must be a string");this.keyType=n,this.resolvedKeyType=null,this.map=!0}return s.fromJSON=function(e,t){return new s(e,t.id,t.keyType,t.type,t.options,t.comment)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},s.prototype.resolve=function(){if(this.resolved)return this;if(void 0===t.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return e.prototype.resolve.call(this)},s.d=function(e,t,n){return"function"==typeof n?n=r.decorateType(n).name:n&&"object"==typeof n&&(n=r.decorateEnum(n).name),function(i,o){r.decorateType(i.constructor).add(new s(o,e,t,n))}},fo}function Mo(){if(Io)return vo;Io=1,vo=r;var e=pa();((r.prototype=Object.create(e.prototype)).constructor=r).className="Method";var t=da();function r(r,s,n,i,o,a,c,d,u){if(t.isObject(o)?(c=o,o=a=void 0):t.isObject(a)&&(c=a,a=void 0),void 0!==s&&!t.isString(s))throw TypeError("type must be a string");if(!t.isString(n))throw TypeError("requestType must be a string");if(!t.isString(i))throw TypeError("responseType must be a string");e.call(this,r,c),this.type=s||"rpc",this.requestType=n,this.requestStream=!!o||void 0,this.responseType=i,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=d,this.parsedOptions=u}return r.fromJSON=function(e,t){return new r(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},r.prototype.toJSON=function(e){var r=!!e&&Boolean(e.keepComments);return t.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",r?this.comment:void 0,"parsedOptions",this.parsedOptions])},r.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),e.prototype.resolve.call(this))},vo}function Uo(){if(_o)return bo;_o=1,bo=n;var e=No();((n.prototype=Object.create(e.prototype)).constructor=n).className="Service";var t=Mo(),r=da(),s=Wi();function n(t,r){e.call(this,t,r),this.methods={},this._methodsArray=null}function i(e){return e._methodsArray=null,e}return n.fromJSON=function(e,s,i){i=r.checkDepth(i);var o=new n(e,s.options);if(s.methods)for(var a=Object.keys(s.methods),c=0;c<a.length;++c)o.add(t.fromJSON(a[c],s.methods[a[c]]));return s.nested&&o.addJSON(s.nested,i),s.edition&&(o._edition=s.edition),o.comment=s.comment,o._defaultEdition="proto3",o},n.prototype.toJSON=function(t){var s=e.prototype.toJSON.call(this,t),n=!!t&&Boolean(t.keepComments);return r.toObject(["edition",this._editionToJSON(),"options",s&&s.options||void 0,"methods",e.arrayToJSON(this.methodsArray,t)||{},"nested",s&&s.nested||void 0,"comment",n?this.comment:void 0])},Object.defineProperty(n.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=r.toArray(this.methods))}}),n.prototype.get=function(t){return Object.prototype.hasOwnProperty.call(this.methods,t)?this.methods[t]:e.prototype.get.call(this,t)},n.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;e.prototype.resolve.call(this);for(var t=this.methodsArray,r=0;r<t.length;++r)t[r].resolve();return this},n.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.methodsArray.forEach(e=>{e._resolveFeaturesRecursive(t)}),this):this},n.prototype.add=function(r){if(this.get(r.name))throw Error("duplicate name '"+r.name+"' in "+this);return r instanceof t?"__proto__"===r.name?this:(this.methods[r.name]=r,r.parent=this,i(this)):e.prototype.add.call(this,r)},n.prototype.remove=function(r){if(r instanceof t){if(this.methods[r.name]!==r)throw Error(r+" is not a member of "+this);return delete this.methods[r.name],r.parent=null,i(this)}return e.prototype.remove.call(this,r)},n.prototype.create=function(e,t,n){for(var i,o=new s.Service(e,t,n),a=0;a<this.methodsArray.length;++a){o[r.lcFirst((i=this._methodsArray[a]).resolve().name).replace(/[^$\w_]/g,"")]=function(e,t,r){return function(n,i){return s.Service.prototype.rpcCall.call(this,e,t,r,n,i)}}(i,i.resolvedRequestType.ctor,i.resolvedResponseType.ctor)}return o},bo}function Lo(){if(Co)return To;Co=1,To=t;var e=Fi();function t(e){if(e)for(var t=Object.keys(e),r=0;r<t.length;++r){var s=t[r];"__proto__"!==s&&(this[s]=e[s])}}return t.create=function(e){return this.$type.create(e)},t.encode=function(e,t){return this.$type.encode(e,t)},t.encodeDelimited=function(e,t){return this.$type.encodeDelimited(e,t)},t.decode=function(e){return this.$type.decode(e)},t.decodeDelimited=function(e){return this.$type.decodeDelimited(e)},t.verify=function(e){return this.$type.verify(e)},t.fromObject=function(e){return this.$type.fromObject(e)},t.toObject=function(e,t){return this.$type.toObject(e,t)},t.prototype.toJSON=function(){return this.$type.toObject(this,e.toJSONOptions)},To}function ko(){if(Eo)return So;Eo=1,So=function(n){for(var i=r.codegen(["r","l","e","n"],n.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("if(n===undefined)n=0")("if(n>Reader.recursionLimit)")('throw Error("maximum nesting depth exceeded")')("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(n.fieldsArray.filter(function(e){return e.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),o=0;o<n.fieldsArray.length;++o){var a=n._fieldsArray[o].resolve(),c=a.resolvedType instanceof e?"int32":a.type,d="m"+r.safeProp(a.name);i("case %i: {",a.id),a.map?(i("if(%s===util.emptyObject)",d)("%s={}",d)("var c2 = r.uint32()+r.pos"),void 0!==t.defaults[a.keyType]?i("k=%j",t.defaults[a.keyType]):i("k=null"),void 0!==t.defaults[c]?i("value=%j",t.defaults[c]):i("value=null"),i("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===t.basic[c]?i("value=types[%i].decode(r,r.uint32(),undefined,n+1)",o):i("value=r.%s()",c),i("break")("default:")("r.skipType(tag2&7,n)")("break")("}")("}"),void 0!==t.long[a.keyType]?i('%s[typeof k==="object"?util.longToHash(k):k]=value',d):("string"===a.keyType&&i('if(k==="__proto__")')("util.makeProp(%s,k)",d),i("%s[k]=value",d))):a.repeated?(i("if(!(%s&&%s.length))",d,d)("%s=[]",d),void 0!==t.packed[c]&&i("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",d,c)("}else"),void 0===t.basic[c]?i(a.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4),n+1))":"%s.push(types[%i].decode(r,r.uint32(),undefined,n+1))",d,o):i("%s.push(r.%s())",d,c)):void 0===t.basic[c]?i(a.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4),n+1)":"%s=types[%i].decode(r,r.uint32(),undefined,n+1)",d,o):i("%s=r.%s()",d,c),i("break")("}")}for(i("default:")("r.skipType(t&7,n)")("break")("}")("}"),o=0;o<n._fieldsArray.length;++o){var u=n._fieldsArray[o];u.required&&i("if(!Object.hasOwnProperty.call(m,%j))",u.name)("throw util.ProtocolError(%j,{instance:m})",s(u))}return i("return m")};var e=ma(),t=ua(),r=da();function s(e){return"missing required '"+e.name+"'"}return So}function Do(){if(Ao)return wo;Ao=1,wo=function(e){var i=t.codegen(["m","n"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected")("if(n===undefined)n=0")("if(n>util.recursionLimit)")("return%j","maximum nesting depth exceeded"),o=e.oneofsArray,a={};o.length&&i("var p={}");for(var c=0;c<e.fieldsArray.length;++c){var d=e._fieldsArray[c].resolve(),u="m"+t.safeProp(d.name);if(d.optional&&i("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",u,d.name),d.map)i("if(!util.isObject(%s))",u)("return%j",r(d,"object"))("var k=Object.keys(%s)",u)("for(var i=0;i<k.length;++i){"),n(i,d,"k[i]"),s(i,d,c,u+"[k[i]]")("}");else if(d.repeated)i("if(!Array.isArray(%s))",u)("return%j",r(d,"array"))("for(var i=0;i<%s.length;++i){",u),s(i,d,c,u+"[i]")("}");else{if(d.partOf){var l=t.safeProp(d.partOf.name);1===a[d.partOf.name]&&i("if(p%s===1)",l)("return%j",d.partOf.name+": multiple values"),a[d.partOf.name]=1,i("p%s=1",l)}s(i,d,c,u)}d.optional&&i("}")}return i("return null")};var e=ma(),t=da();function r(e,t){return e.name+": "+t+(e.repeated&&"array"!==t?"[]":e.map&&"object"!==t?"{k:"+e.keyType+"}":"")+" expected"}function s(t,s,n,i){if(s.resolvedType)if(s.resolvedType instanceof e){t("switch(%s){",i)("default:")("return%j",r(s,"enum value"));for(var o=Object.keys(s.resolvedType.values),a=0;a<o.length;++a)t("case %i:",s.resolvedType.values[o[a]]);t("break")("}")}else t("{")("var e=types[%i].verify(%s,n+1);",n,i)("if(e)")("return%j+e",s.name+".")("}");else switch(s.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.isInteger(%s))",i)("return%j",r(s,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",i,i,i,i)("return%j",r(s,"integer|Long"));break;case"float":case"double":t('if(typeof %s!=="number")',i)("return%j",r(s,"number"));break;case"bool":t('if(typeof %s!=="boolean")',i)("return%j",r(s,"boolean"));break;case"string":t("if(!util.isString(%s))",i)("return%j",r(s,"string"));break;case"bytes":t('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',i,i,i)("return%j",r(s,"buffer"))}return t}function n(e,t,s){switch(t.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.key32Re.test(%s))",s)("return%j",r(t,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.key64Re.test(%s))",s)("return%j",r(t,"integer|Long key"));break;case"bool":e("if(!util.key2Re.test(%s))",s)("return%j",r(t,"boolean key"))}return e}return wo}var Po,xo={};function Fo(){return Po||(Po=1,function(e){var t=e,r=ma(),s=da();function n(e,t,s,n){var i=!1;if(t.resolvedType)if(t.resolvedType instanceof r){e("switch(d%s){",n);for(var o=t.resolvedType.values,a=Object.keys(o),c=0;c<a.length;++c)o[a[c]]!==t.typeDefault||i||(e("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',n,n,n),t.repeated||e("break"),i=!0),e("case%j:",a[c])("case %i:",o[a[c]])("m%s=%j",n,o[a[c]])("break");e("}")}else e("if(!util.isObject(d%s))",n)("throw TypeError(%j)",t.fullName+": object expected")("m%s=types[%i].fromObject(d%s,n+1)",n,s,n);else{var d=!1;switch(t.type){case"double":case"float":e("m%s=Number(d%s)",n,n);break;case"uint32":case"fixed32":e("m%s=d%s>>>0",n,n);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",n,n);break;case"uint64":case"fixed64":d=!0;case"int64":case"sint64":case"sfixed64":e("if(util.Long)")("m%s=util.Long.fromValue(d%s,%j)",n,n,d)('else if(typeof d%s==="string")',n)("m%s=parseInt(d%s,10)",n,n)('else if(typeof d%s==="number")',n)("m%s=d%s",n,n)('else if(typeof d%s==="object")',n)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",n,n,n,d?"true":"");break;case"bytes":e('if(typeof d%s==="string")',n)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",n,n,n)("else if(d%s.length >= 0)",n)("m%s=d%s",n,n);break;case"string":e("m%s=String(d%s)",n,n);break;case"bool":e("m%s=Boolean(d%s)",n,n)}}return e}function i(e,t,s,n){if(t.resolvedType)t.resolvedType instanceof r?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,s,n,n,s,n,n):e("d%s=types[%i].toObject(m%s,o,q+1)",n,s,n);else{var i=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":case"fixed64":i=!0;case"int64":case"sint64":case"sfixed64":e('if(typeof BigInt!=="undefined"&&o.longs===BigInt)')('d%s=typeof m%s==="number"?BigInt(m%s):util.Long.fromBits(m%s.low>>>0,m%s.high>>>0,%j).toBigInt()',n,n,n,n,n,i)('else if(typeof m%s==="number")',n)("d%s=o.longs===String?String(m%s):m%s",n,n,n)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",n,n,n,n,i?"true":"",n);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}t.fromObject=function(e){var t=e.fieldsArray,i=s.codegen(["d","n"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return i("return new this.ctor");i("if(!util.isObject(d))")("throw TypeError(%j)",e.fullName+": object expected")("if(n===undefined)n=0")("if(n>util.recursionLimit)")('throw Error("maximum nesting depth exceeded")'),i("var m=new this.ctor");for(var o=0;o<t.length;++o){var a=t[o].resolve(),c=s.safeProp(a.name);a.map?(i("if(d%s){",c)("if(!util.isObject(d%s))",c)("throw TypeError(%j)",a.fullName+": object expected")("m%s={}",c)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",c),i('if(ks[i]==="__proto__")')("util.makeProp(m%s,ks[i])",c),n(i,a,o,c+"[ks[i]]")("}")("}")):a.repeated?(i("if(d%s){",c)("if(!Array.isArray(d%s))",c)("throw TypeError(%j)",a.fullName+": array expected")("m%s=[]",c)("for(var i=0;i<d%s.length;++i){",c),n(i,a,o,c+"[i]")("}")("}")):(a.resolvedType instanceof r||i("if(d%s!=null){",c),n(i,a,o,c),a.resolvedType instanceof r||i("}"))}return i("return m")},t.toObject=function(e){var t=e.fieldsArray.slice().sort(s.compareFieldsById);if(!t.length)return s.codegen()("return {}");for(var n=s.codegen(["m","o","q"],e.name+"$toObject")("if(!o)")("o={}")("if(q===undefined)q=0")("if(q>util.recursionLimit)")('throw Error("max depth exceeded")')("var d={}"),o=[],a=[],c=[],d=0;d<t.length;++d)t[d].partOf||(t[d].resolve().repeated?o:t[d].map?a:c).push(t[d]);if(o.length){for(n("if(o.arrays||o.defaults){"),d=0;d<o.length;++d)n("d%s=[]",s.safeProp(o[d].name));n("}")}if(a.length){for(n("if(o.objects||o.defaults){"),d=0;d<a.length;++d)n("d%s={}",s.safeProp(a[d].name));n("}")}if(c.length){for(n("if(o.defaults){"),d=0;d<c.length;++d){var u=c[d],l=s.safeProp(u.name);if(u.resolvedType instanceof r)n("d%s=o.enums===String?%j:%j",l,u.resolvedType.valuesById[u.typeDefault],u.typeDefault);else if(u.long)n("if(util.Long){")("var n=new util.Long(%i,%i,%j)",u.typeDefault.low,u.typeDefault.high,u.typeDefault.unsigned)('d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():typeof BigInt!=="undefined"&&o.longs===BigInt?n.toBigInt():n',l)("}else")('d%s=o.longs===String?%j:typeof BigInt!=="undefined"&&o.longs===BigInt?BigInt(%j):%i',l,u.typeDefault.toString(),u.typeDefault.toString(),u.typeDefault.toNumber());else if(u.bytes){var h=Array.prototype.slice.call(u.typeDefault);n("if(o.bytes===String)d%s=%j",l,String.fromCharCode.apply(String,u.typeDefault))("else{")("d%s=%j",l,h)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",l,l)("}")}else n("d%s=%j",l,u.typeDefault)}n("}")}var p=!1;for(d=0;d<t.length;++d){u=t[d];var m=e._fieldsArray.indexOf(u);l=s.safeProp(u.name);u.map?(p||(p=!0,n("var ks2")),n("if(m%s&&(ks2=Object.keys(m%s)).length){",l,l)("d%s={}",l)("for(var j=0;j<ks2.length;++j){"),n('if(ks2[j]==="__proto__")')("util.makeProp(d%s,ks2[j])",l),i(n,u,m,l+"[ks2[j]]")("}")):u.repeated?(n("if(m%s&&m%s.length){",l,l)("d%s=[]",l)("for(var j=0;j<m%s.length;++j){",l),i(n,u,m,l+"[j]")("}")):(n("if(m%s!=null&&Object.hasOwnProperty.call(m,%j)){",l,u.name),i(n,u,m,l),u.partOf&&n("if(o.oneofs)")("d%s=%j",s.safeProp(u.partOf.name),u.name)),n("}")}return n("return d")}}(xo)),xo}var Bo,Go,qo,$o,jo,Vo,Ko,zo,Ho,Wo,Jo,Qo,Zo,Yo,Xo,ea,ta,ra,sa,na,ia={};function oa(){return Bo||(Bo=1,e=ia,t=Lo(),r=Fi(),e[".google.protobuf.Any"]={fromObject:function(e,t){if(e&&e["@type"]){var r=e["@type"].substring(e["@type"].lastIndexOf("/")+1),s=this.lookup(r);if(s){var n="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===n.indexOf("/")&&(n="/"+n),this.create({type_url:n,value:s.encode(s.fromObject(e,void 0===t?1:t+1)).finish()})}}return this.fromObject(e,t)},toObject:function(e,s,n){if(void 0===n&&(n=0),n>r.recursionLimit)throw Error("max depth exceeded");var i="",o="";if(s&&s.json&&e.type_url&&e.value){o=e.type_url.substring(e.type_url.lastIndexOf("/")+1),i=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var a=this.lookup(o);a&&(e=a.decode(e.value,void 0,void 0,n+1))}if(!(e instanceof this.ctor)&&e instanceof t){var c=e.$type.toObject(e,s,n+1);return""===i&&(i="type.googleapis.com/"),o=i+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),c["@type"]=o,c}return this.toObject(e,s,n)}}),ia;var e,t,r}function aa(){if(qo)return Go;qo=1,Go=g;var e=No();((g.prototype=Object.create(e.prototype)).constructor=g).className="Type";var t=ma(),r=ha(),s=la(),n=Oo(),i=Uo(),o=Lo(),a=Gi(),c=Bi(),d=da(),u=ga(),l=ko(),h=Do(),p=Fo(),m=oa();function g(t,r){t=t.replace(/\W/g,""),e.call(this,t,r),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function f(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}return Object.defineProperties(g.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t<e.length;++t){var r=this.fields[e[t]],s=r.id;if(this._fieldsById[s])throw Error("duplicate id "+s+" in "+this);this._fieldsById[s]=r}return this._fieldsById}},fieldsArray:{get:function(){return this._fieldsArray||(this._fieldsArray=d.toArray(this.fields))}},oneofsArray:{get:function(){return this._oneofsArray||(this._oneofsArray=d.toArray(this.oneofs))}},ctor:{get:function(){return this._ctor||(this.ctor=g.generateConstructor(this)())},set:function(e){var t=e.prototype;t instanceof o||((e.prototype=new o).constructor=e,d.merge(e.prototype,t)),e.$type=e.prototype.$type=this,d.merge(e,o,!0),this._ctor=e;for(var r=0;r<this.fieldsArray.length;++r)this._fieldsArray[r].resolve();var s={};for(r=0;r<this.oneofsArray.length;++r)s[this._oneofsArray[r].resolve().name]={get:d.oneOfGetter(this._oneofsArray[r].oneof),set:d.oneOfSetter(this._oneofsArray[r].oneof)};r&&Object.defineProperties(e.prototype,s)}}}),g.generateConstructor=function(e){for(var t,r=d.codegen(["p"],e.name),s=0;s<e.fieldsArray.length;++s)(t=e._fieldsArray[s]).map?r("this%s={}",d.safeProp(t.name)):t.repeated&&r("this%s=[]",d.safeProp(t.name));return r('if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null&&ks[i]!=="__proto__")')("this[ks[i]]=p[ks[i]]")},g.fromJSON=function(o,a,c){if(void 0===c&&(c=0),c>d.nestingLimit)throw Error("max depth exceeded");var u=new g(o,a.options);u.extensions=a.extensions,u.reserved=a.reserved;for(var l=Object.keys(a.fields),h=0;h<l.length;++h)u.add((void 0!==a.fields[l[h]].keyType?n.fromJSON:s.fromJSON)(l[h],a.fields[l[h]]));if(a.oneofs)for(l=Object.keys(a.oneofs),h=0;h<l.length;++h)u.add(r.fromJSON(l[h],a.oneofs[l[h]]));if(a.nested)for(l=Object.keys(a.nested),h=0;h<l.length;++h){var p=a.nested[l[h]];u.add((void 0!==p.id?s.fromJSON:void 0!==p.fields?g.fromJSON:void 0!==p.values?t.fromJSON:void 0!==p.methods?i.fromJSON:e.fromJSON)(l[h],p,c+1))}return a.extensions&&a.extensions.length&&(u.extensions=a.extensions),a.reserved&&a.reserved.length&&(u.reserved=a.reserved),a.group&&(u.group=!0),a.comment&&(u.comment=a.comment),a.edition&&(u._edition=a.edition),u._defaultEdition="proto3",u},g.prototype.toJSON=function(t){var r=e.prototype.toJSON.call(this,t),s=!!t&&Boolean(t.keepComments);return d.toObject(["edition",this._editionToJSON(),"options",r&&r.options||void 0,"oneofs",e.arrayToJSON(this.oneofsArray,t),"fields",e.arrayToJSON(this.fieldsArray.filter(function(e){return!e.declaringField}),t)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:void 0,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"group",this.group||void 0,"nested",r&&r.nested||void 0,"comment",s?this.comment:void 0])},g.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;e.prototype.resolveAll.call(this);var t=this.oneofsArray;for(s=0;s<t.length;)t[s++].resolve();for(var r=this.fieldsArray,s=0;s<r.length;)r[s++].resolve();return this},g.prototype._resolveFeaturesRecursive=function(t){return this._needsRecursiveFeatureResolution?(t=this._edition||t,e.prototype._resolveFeaturesRecursive.call(this,t),this.oneofsArray.forEach(e=>{e._resolveFeatures(t)}),this.fieldsArray.forEach(e=>{e._resolveFeatures(t)}),this):this},g.prototype.get=function(e){return Object.prototype.hasOwnProperty.call(this.fields,e)?this.fields[e]:this.oneofs&&Object.prototype.hasOwnProperty.call(this.oneofs,e)?this.oneofs[e]:this.nested&&Object.prototype.hasOwnProperty.call(this.nested,e)?this.nested[e]:null},g.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);if(t instanceof s&&void 0===t.extend){if(this._fieldsById?this._fieldsById[t.id]:this.fieldsById[t.id])throw Error("duplicate id "+t.id+" in "+this);if(this.isReservedId(t.id))throw Error("id "+t.id+" is reserved in "+this);if(this.isReservedName(t.name)||"$"===t.name.charAt(0))throw Error("name '"+t.name+"' is reserved in "+this);return"__proto__"===t.name?this:(t.parent&&t.parent.remove(t),this.fields[t.name]=t,t.message=this,t.onAdd(this),f(this))}if(t instanceof r){if("$"===t.name.charAt(0))throw Error("name '"+t.name+"' is reserved in "+this);return"__proto__"===t.name?this:(this.oneofs||(this.oneofs={}),this.oneofs[t.name]=t,t.onAdd(this),f(this))}return e.prototype.add.call(this,t)},g.prototype.remove=function(t){if(t instanceof s&&void 0===t.extend){if(!this.fields||this.fields[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.fields[t.name],t.parent=null,t.onRemove(this),f(this)}if(t instanceof r){if(!this.oneofs||this.oneofs[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.oneofs[t.name],t.parent=null,t.onRemove(this),f(this)}return e.prototype.remove.call(this,t)},g.prototype.isReservedId=function(t){return e.isReservedId(this.reserved,t)},g.prototype.isReservedName=function(t){return e.isReservedName(this.reserved,t)},g.prototype.create=function(e){return new this.ctor(e)},g.prototype.setup=function(){for(var e=this.fullName,t=[],r=0;r<this.fieldsArray.length;++r)t.push(this._fieldsArray[r].resolve().resolvedType);this.encode=u(this)({Writer:c,types:t,util:d}),this.decode=l(this)({Reader:a,types:t,util:d}),this.verify=h(this)({types:t,util:d}),this.fromObject=p.fromObject(this)({types:t,util:d}),this.toObject=p.toObject(this)({types:t,util:d});var s=m[e];if(s){var n=Object.create(this);n.fromObject=this.fromObject,this.fromObject=s.fromObject.bind(n),n.toObject=this.toObject,this.toObject=s.toObject.bind(n)}return this},g.prototype.encode=function(e,t){return this.setup().encode.apply(this,arguments)},g.prototype.encodeDelimited=function(e,t){return this.encode(e,t&&t.len?t.fork():t).ldelim()},g.prototype.decode=function(e,t,r,s){return this.setup().decode(e,t,r,s)},g.prototype.decodeDelimited=function(e){return e instanceof a||(e=a.create(e)),this.decode(e,e.uint32())},g.prototype.verify=function(e,t){return this.setup().verify(e,t)},g.prototype.fromObject=function(e,t){return this.setup().fromObject(e,t)},g.prototype.toObject=function(e,t){return this.setup().toObject.apply(this,arguments)},g.d=function(e){return function(t){d.decorateType(t,e)}},Go}function ca(){if(jo)return $o;jo=1,$o=c;var e=No();((c.prototype=Object.create(e.prototype)).constructor=c).className="Root";var t,r,s,n=la(),i=ma(),o=ha(),a=da();function c(t){e.call(this,"",t),this.deferred=[],this.files=[],this._edition="proto2",this._fullyQualifiedObjects={}}function d(){}c.fromJSON=function(e,t,r){return r=a.checkDepth(r),t||(t=new c),e.options&&t.setOptions(e.options),t.addJSON(e.nested,r).resolveAll()},c.prototype.resolvePath=a.path.resolve,c.prototype.fetch=a.fetch,c.prototype.load=function e(t,n,i){"function"==typeof n&&(i=n,n=void 0);var o=this;if(!i)return a.asPromise(e,o,t,n);var c=i===d;function u(e,t){if(i){if(c)throw e;t&&t.resolveAll();var r=i;i=null,r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in s)return r}return null}function h(e,t,s){void 0===s&&(s=0);try{if(s>a.recursionLimit)throw Error("max depth exceeded");if(a.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),a.isString(t)){r.filename=e;var i,d=r(t,o,n),h=0;if(d.imports)for(;h<d.imports.length;++h)(i=l(d.imports[h])||o.resolvePath(e,d.imports[h]))&&p(i,!1,s+1);if(d.weakImports)for(h=0;h<d.weakImports.length;++h)(i=l(d.weakImports[h])||o.resolvePath(e,d.weakImports[h]))&&p(i,!0,s+1)}else o.setOptions(t.options).addJSON(t.nested)}catch(g){u(g)}c||m||u(null,o)}function p(e,t,r){if(void 0===r&&(r=0),e=l(e)||e,!(o.files.indexOf(e)>-1))if(o.files.push(e),e in s)c?h(e,s[e],r):(++m,setTimeout(function(){--m,h(e,s[e],r)}));else if(c){var n;try{n=a.fs.readFileSync(e).toString("utf8")}catch(d){return void(t||u(d))}h(e,n,r)}else++m,o.fetch(e,function(s,n){--m,i&&(s?t?m||u(null,o):u(s):h(e,n,r))})}var m=0;a.isString(t)&&(t=[t]);for(var g,f=0;f<t.length;++f)(g=o.resolvePath("",t[f]))&&p(g);return c?(o.resolveAll(),o):(m||u(null,o),o)},c.prototype.loadSync=function(e,t){if(!a.isNode)throw Error("not supported");return this.load(e,t,d)},c.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(e){return"'extend "+e.extend+"' in "+e.parent.fullName}).join(", "));return e.prototype.resolveAll.call(this)};var u=/^[A-Z]/;function l(e,t){var r=t.parent.lookup(t.extend);if(r){var s=new n(t.fullName,t.id,t.type,t.rule,void 0,t.options);return r.get(s.name)||(s.declaringField=t,t.extensionField=s,r.add(s)),!0}return!1}return c.prototype._handleAdd=function(e){if(e instanceof n)void 0===e.extend||e.extensionField||l(0,e)||this.deferred.push(e);else if(e instanceof i)u.test(e.name)&&(e.parent[e.name]=e.values);else if(!(e instanceof o)){if(e instanceof t)for(var r=0;r<this.deferred.length;)l(0,this.deferred[r])?this.deferred.splice(r,1):++r;for(var s=0;s<e.nestedArray.length;++s)this._handleAdd(e._nestedArray[s]);u.test(e.name)&&(e.parent[e.name]=e)}(e instanceof t||e instanceof i||e instanceof n)&&(this._fullyQualifiedObjects[e.fullName]=e)},c.prototype._handleRemove=function(t){if(t instanceof n){if(void 0!==t.extend)if(t.extensionField)t.extensionField.parent.remove(t.extensionField),t.extensionField=null;else{var r=this.deferred.indexOf(t);r>-1&&this.deferred.splice(r,1)}}else if(t instanceof i)u.test(t.name)&&delete t.parent[t.name];else if(t instanceof e){for(var s=0;s<t.nestedArray.length;++s)this._handleRemove(t._nestedArray[s]);u.test(t.name)&&delete t.parent[t.name]}delete this._fullyQualifiedObjects[t.fullName]},c._configure=function(e,n,i){t=e,r=n,s=i},$o}function da(){if(Vo)return eo.exports;Vo=1;var e,t,r,s,n,i,o=eo.exports=Fi(),a=Ji();o.codegen=to(),o.fetch=ao(),o.path=(co||(co=1,s=(r=uo).isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},n=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=s(e),n="";r&&(n=t.shift()+"/");for(var i=0;i<t.length;)".."===t[i]?i>0&&".."!==t[i-1]?t.splice(--i,2):r?t.splice(i,1):++i:"."===t[i]?t.splice(i,1):++i;return n+t.join("/")},r.resolve=function(e,t,r){return r||(t=n(t)),s(t)?t:(r||(e=n(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?n(e+"/"+t):t)}),uo),o.patterns=(lo||(lo=1,(i=Ro).numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,i.typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,i.reservedRe=/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/),Ro);var c=o.patterns.reservedRe;o.fs=function(){if(po)return ho;po=1;var e=null;try{(e=ro)&&e.readFile&&e.readFileSync||(e=null)}catch(t){}return ho=e}(),o.checkDepth=function(e){if(void 0===e&&(e=0),e>o.recursionLimit)throw Error("max depth exceeded");return e},o.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),s=0;s<t.length;)r[s]=e[t[s++]];return r}return[]},o.toObject=function(e){for(var t={},r=0;r<e.length;){var s=e[r++],n=e[r++];void 0!==n&&(t[s]=n)}return t},o.isReserved=function(e){return c.test(e)},o.safeProp=function(e){return!/^[$\w_]+$/.test(e)||c.test(e)?"["+JSON.stringify(e)+"]":"."+e},o.ucFirst=function(e){return e.charAt(0).toUpperCase()+e.substring(1)};var d=/_([a-z])/g;o.camelCase=function(e){return e.substring(0,1)+e.substring(1).replace(d,function(e,t){return t.toUpperCase()})},o.compareFieldsById=function(e,t){return e.id-t.id},o.decorateType=function(t,r){if(t.$type)return r&&t.$type.name!==r&&(o.decorateRoot.remove(t.$type),t.$type.name=r,o.decorateRoot.add(t.$type)),t.$type;e||(e=aa());var s=new e(r||t.name);return o.decorateRoot.add(s),s.ctor=t,Object.defineProperty(t,"$type",{value:s,enumerable:!1}),Object.defineProperty(t.prototype,"$type",{value:s,enumerable:!1}),s};var u=0;return o.decorateEnum=function(e){if(e.$type)return e.$type;t||(t=ma());var r=new t("Enum"+u++,e);return o.decorateRoot.add(r),Object.defineProperty(e,"$type",{value:r,enumerable:!1}),r},o.setProperty=function(e,t,r,s){if("object"!=typeof e)throw TypeError("dst must be an object");if(!t)throw TypeError("path must be specified");if((t=t.split(".")).length>o.recursionLimit)throw Error("max depth exceeded");return function e(t,r,n){var i=r.shift();if(o.isUnsafeProperty(i))return t;if(r.length>0)t[i]=e(t[i]||{},r,n);else{var a=t[i];if(a&&s)return t;a&&(n=[].concat(a).concat(n)),t[i]=n}return t}(e,t,r)},Object.defineProperty(o,"decorateRoot",{get:function(){return a.decorated||(a.decorated=new(ca()))}}),eo.exports}function ua(){return Ko||(Ko=1,function(e){var t=e,r=da(),s=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function n(e,t){var r=0,n=Object.create(null);for(t|=0;r<e.length;)n[s[r+t]]=e[r++];return n}t.basic=n([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),t.defaults=n([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",r.emptyArray,null]),t.long=n([0,0,0,1,1],7),t.mapKey=n([0,0,0,5,5,0,0,0,1,1,0,2],2),t.packed=n([1,5,0,0,0,5,5,0,0,0,1,1,0])}(Xi)),Xi}function la(){if(Ho)return zo;Ho=1,zo=o;var e=pa();((o.prototype=Object.create(e.prototype)).constructor=o).className="Field";var t,r=ma(),s=ua(),n=da(),i=/^required|optional|repeated$/;function o(t,r,o,a,c,d,u){if(n.isObject(a)?(u=c,d=a,a=c=void 0):n.isObject(c)&&(u=d,d=c,c=void 0),e.call(this,t,d),!n.isInteger(r)||r<0)throw TypeError("id must be a non-negative integer");if(!n.isString(o))throw TypeError("type must be a string");if(void 0!==a&&!i.test(a=a.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==c&&!n.isString(c))throw TypeError("extend must be a string");"proto3_optional"===a&&(a="optional"),this.rule=a&&"optional"!==a?a:void 0,this.type=o,this.id=r,this.extend=c||void 0,this.repeated="repeated"===a,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!n.Long&&void 0!==s.long[o],this.bytes="bytes"===o,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=u}return o.fromJSON=function(e,t){var r=new o(e,t.id,t.type,t.rule,t.extend,t.options,t.comment);return t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},Object.defineProperty(o.prototype,"required",{get:function(){return"LEGACY_REQUIRED"===this._features.field_presence}}),Object.defineProperty(o.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(o.prototype,"delimited",{get:function(){return this.resolvedType instanceof t&&"DELIMITED"===this._features.message_encoding}}),Object.defineProperty(o.prototype,"packed",{get:function(){return"PACKED"===this._features.repeated_field_encoding}}),Object.defineProperty(o.prototype,"hasPresence",{get:function(){return!this.repeated&&!this.map&&(this.partOf||this.declaringField||this.extensionField||"IMPLICIT"!==this._features.field_presence)}}),o.prototype.setOption=function(t,r,s){return e.prototype.setOption.call(this,t,r,s)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return n.toObject(["edition",this._editionToJSON(),"rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},o.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=s.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof t?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof r&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof r||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=n.Long.fromNumber(this.typeDefault,"uint64"===this.type||"fixed64"===this.type),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"==typeof this.typeDefault){var i;n.base64.test(this.typeDefault)?n.base64.decode(this.typeDefault,i=n.newBuffer(n.base64.length(this.typeDefault)),0):n.utf8.write(this.typeDefault,i=n.newBuffer(n.utf8.length(this.typeDefault)),0),this.typeDefault=i}return this.map?this.defaultValue=n.emptyObject:this.repeated?this.defaultValue=n.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof t&&(this.parent.ctor.prototype[this.name]=this.defaultValue),e.prototype.resolve.call(this)},o.prototype._inferLegacyProtoFeatures=function(e){if("proto2"!==e&&"proto3"!==e)return{};var r={};if("required"===this.rule&&(r.field_presence="LEGACY_REQUIRED"),this.parent&&void 0===s.defaults[this.type]){var n=this.parent.get(this.type.split(".").pop());n&&n instanceof t&&n.group&&(r.message_encoding="DELIMITED")}return!0===this.getOption("packed")?r.repeated_field_encoding="PACKED":!1===this.getOption("packed")&&(r.repeated_field_encoding="EXPANDED"),r},o.prototype._resolveFeatures=function(t){return e.prototype._resolveFeatures.call(this,this._edition||t)},o.d=function(e,t,r,s){return"function"==typeof t?t=n.decorateType(t).name:t&&"object"==typeof t&&(t=n.decorateEnum(t).name),function(i,a){n.decorateType(i.constructor).add(new o(a,e,t,r,{default:s}))}},o._configure=function(e){t=e},zo}function ha(){if(Jo)return Wo;Jo=1,Wo=s;var e=pa();((s.prototype=Object.create(e.prototype)).constructor=s).className="OneOf";var t=la(),r=da();function s(t,r,s,n){if(Array.isArray(r)||(s=r,r=void 0),e.call(this,t,s),void 0!==r&&!Array.isArray(r))throw TypeError("fieldNames must be an Array");this.oneof=r||[],this.fieldsArray=[],this.comment=n}function n(e){if(e.parent)for(var t=0;t<e.fieldsArray.length;++t)e.fieldsArray[t].parent||e.parent.add(e.fieldsArray[t])}return s.fromJSON=function(e,t){return new s(e,t.oneof,t.options,t.comment)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["options",this.options,"oneof",this.oneof,"comment",t?this.comment:void 0])},s.prototype.add=function(e){if(!(e instanceof t))throw TypeError("field must be a Field");return e.parent&&e.parent!==this.parent&&e.parent.remove(e),this.oneof.push(e.name),this.fieldsArray.push(e),e.partOf=this,n(this),this},s.prototype.remove=function(e){if(!(e instanceof t))throw TypeError("field must be a Field");var r=this.fieldsArray.indexOf(e);if(r<0)throw Error(e+" is not a member of "+this);return this.fieldsArray.splice(r,1),(r=this.oneof.indexOf(e.name))>-1&&this.oneof.splice(r,1),e.partOf=null,this},s.prototype.onAdd=function(t){e.prototype.onAdd.call(this,t);for(var r=0;r<this.oneof.length;++r){var s=t.get(this.oneof[r]);s&&!s.partOf&&(s.partOf=this,this.fieldsArray.push(s))}n(this)},s.prototype.onRemove=function(t){for(var r,s=0;s<this.fieldsArray.length;++s)(r=this.fieldsArray[s]).parent&&r.parent.remove(r);e.prototype.onRemove.call(this,t)},Object.defineProperty(s.prototype,"isProto3Optional",{get:function(){if(null==this.fieldsArray||1!==this.fieldsArray.length)return!1;var e=this.fieldsArray[0];return null!=e.options&&!0===e.options.proto3_optional}}),s.d=function(){for(var e=new Array(arguments.length),t=0;t<arguments.length;)e[t]=arguments[t++];return function(t,n){r.decorateType(t.constructor).add(new s(n,e)),Object.defineProperty(t,n,{get:r.oneOfGetter(e),set:r.oneOfSetter(e)})}},Wo}function pa(){if(Zo)return Qo;Zo=1,Qo=o,o.className="ReflectionObject";const e=ha();var t,r=da(),s={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},n={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},i={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function o(e,t){if(!r.isString(e))throw TypeError("name must be a string");if(t&&!r.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this._edition=null,this._defaultEdition="proto2",this._features={},this._featuresResolved=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}return Object.defineProperties(o.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),o.prototype.toJSON=function(){throw Error()},o.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var r=e.root;r instanceof t&&r._handleAdd(this)},o.prototype.onRemove=function(e){var r=e.root;r instanceof t&&r._handleRemove(this),this.parent=null,this.resolved=!1},o.prototype.resolve=function(){return this.resolved||this.root instanceof t&&(this.resolved=!0),this},o.prototype._resolveFeaturesRecursive=function(e){return this._resolveFeatures(this._edition||e)},o.prototype._resolveFeatures=function(t){if(!this._featuresResolved){var o={};if(!t)throw new Error("Unknown edition for "+this.fullName);var a=r.merge({},this.options&&this.options.features,this._inferLegacyProtoFeatures(t));if(this._edition){if("proto2"===t)o=Object.assign({},n);else if("proto3"===t)o=Object.assign({},i);else{if("2023"!==t)throw new Error("Unknown edition: "+t);o=Object.assign({},s)}return this._features=r.merge(o,a),void(this._featuresResolved=!0)}if(this.partOf instanceof e){var c=r.merge({},this.partOf._features);this._features=r.merge(c,a)}else if(this.declaringField);else{if(!this.parent)throw new Error("Unable to find a parent for "+this.fullName);var d=r.merge({},this.parent._features);this._features=r.merge(d,a)}this.extensionField&&(this.extensionField._features=this._features),this._featuresResolved=!0}},o.prototype._inferLegacyProtoFeatures=function(){return{}},o.prototype.getOption=function(e){if(this.options)return this.options[e]},o.prototype.setOption=function(e,t,s){return"__proto__"===e||(this.options||(this.options={}),/^features\./.test(e)?r.setProperty(this.options,e,t,s):s&&void 0!==this.options[e]||(this.getOption(e)!==t&&(this.resolved=!1),this.options[e]=t)),this},o.prototype.setParsedOption=function(e,t,s){if("__proto__"===e)return this;this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(s){var i=n.find(function(t){return Object.prototype.hasOwnProperty.call(t,e)});if(i){var o=i[e];r.setProperty(o,s,t)}else(i={})[e]=r.setProperty({},s,t),n.push(i)}else{var a={};a[e]=t,n.push(a)}return this},o.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),s=0;s<r.length;++s)this.setOption(r[s],e[r[s]],t);return this},o.prototype.toString=function(){var e=this.constructor.className,t=this.fullName;return t.length?e+" "+t:e},o.prototype._editionToJSON=function(){if(this._edition&&"proto3"!==this._edition)return this._edition},o._configure=function(e){t=e},Qo}function ma(){if(Xo)return Yo;Xo=1,Yo=s;var e=pa();((s.prototype=Object.create(e.prototype)).constructor=s).className="Enum";var t=No(),r=da();function s(t,r,s,n,i,o){if(e.call(this,t,s),r&&"object"!=typeof r)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=n,this.comments=i||{},this.valuesOptions=o,this._valuesFeatures={},this.reserved=void 0,r)for(var a=Object.keys(r),c=0;c<a.length;++c)"__proto__"!==a[c]&&"number"==typeof r[a[c]]&&(this.valuesById[this.values[a[c]]=r[a[c]]]=a[c])}return s.prototype._resolveFeatures=function(t){return t=this._edition||t,e.prototype._resolveFeatures.call(this,t),Object.keys(this.values).forEach(e=>{var t=r.merge({},this._features);this._valuesFeatures[e]=r.merge(t,this.valuesOptions&&this.valuesOptions[e]&&this.valuesOptions[e].features||{})}),this},s.fromJSON=function(e,t){var r=new s(e,t.values,t.options,t.comment,t.comments);return r.reserved=t.reserved,t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return r.toObject(["edition",this._editionToJSON(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",t?this.comment:void 0,"comments",t?this.comments:void 0])},s.prototype.add=function(e,t,s,n){if(!r.isString(e))throw TypeError("name must be a string");if(!r.isInteger(t))throw TypeError("id must be an integer");if("__proto__"===e)return this;if(void 0!==this.values[e])throw Error("duplicate name '"+e+"' in "+this);if(this.isReservedId(t))throw Error("id "+t+" is reserved in "+this);if(this.isReservedName(e))throw Error("name '"+e+"' is reserved in "+this);if(void 0!==this.valuesById[t]){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+t+" in "+this);this.values[e]=t}else this.valuesById[this.values[e]=t]=e;return n&&(void 0===this.valuesOptions&&(this.valuesOptions={}),this.valuesOptions[e]=n||null),this.comments[e]=s||null,this},s.prototype.remove=function(e){if(!r.isString(e))throw TypeError("name must be a string");var t=this.values[e];if(null==t)throw Error("name '"+e+"' does not exist in "+this);return delete this.valuesById[t],delete this.values[e],delete this.comments[e],this.valuesOptions&&delete this.valuesOptions[e],this},s.prototype.isReservedId=function(e){return t.isReservedId(this.reserved,e)},s.prototype.isReservedName=function(e){return t.isReservedName(this.reserved,e)},Yo}function ga(){if(ta)return ea;ta=1,ea=function(n){for(var i,o=r.codegen(["m","w","q"],n.name+"$encode")("if(!w)")("w=Writer.create()")("if(q===undefined)q=0")("if(q>util.recursionLimit)")('throw Error("max depth exceeded")'),a=n.fieldsArray.slice().sort(r.compareFieldsById),c=0;c<a.length;++c){var d=a[c].resolve(),u=n._fieldsArray.indexOf(d),l=d.resolvedType instanceof e?"int32":d.type,h=t.basic[l];i="m"+r.safeProp(d.name),d.map?(o("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",i,d.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",i)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(d.id<<3|2)>>>0,8|t.mapKey[d.keyType],d.keyType),void 0===h?o("types[%i].encode(%s[ks[i]],w.uint32(18).fork(),q+1).ldelim().ldelim()",u,i):o(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|h,l,i),o("}")("}")):d.repeated?(o("if(%s!=null&&%s.length){",i,i),d.packed&&void 0!==t.packed[l]?o("w.uint32(%i).fork()",(d.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",i)("w.%s(%s[i])",l,i)("w.ldelim()"):(o("for(var i=0;i<%s.length;++i)",i),void 0===h?s(o,d,u,i+"[i]"):o("w.uint32(%i).%s(%s[i])",(d.id<<3|h)>>>0,l,i)),o("}")):(d.optional&&o("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",i,d.name),void 0===h?s(o,d,u,i):o("w.uint32(%i).%s(%s)",(d.id<<3|h)>>>0,l,i))}return o("return w")};var e=ma(),t=ua(),r=da();function s(e,t,r,s){return t.delimited?e("types[%i].encode(%s,w.uint32(%i),q+1).uint32(%i)",r,s,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork(),q+1).ldelim()",r,s,(t.id<<3|2)>>>0)}return ea}var fa=na?sa:(na=1,sa=function(){if(ra)return ui.exports;ra=1;var e=ui.exports=Qi();return e.build="light",e.load=function(t,r,s){return"function"==typeof r?(s=r,r=new e.Root):r||(r=new e.Root),r.load(t,s)},e.loadSync=function(t,r){return r||(r=new e.Root),r.loadSync(t)},e.encoder=ga(),e.decoder=ko(),e.verifier=Do(),e.converter=Fo(),e.ReflectionObject=pa(),e.Namespace=No(),e.Root=ca(),e.Enum=ma(),e.Type=aa(),e.Field=la(),e.OneOf=ha(),e.MapField=Oo(),e.Service=Uo(),e.Method=Mo(),e.Message=Lo(),e.wrappers=oa(),e.types=ua(),e.util=da(),e.ReflectionObject._configure(e.Root),e.Namespace._configure(e.Type,e.Service,e.Enum),e.Root._configure(e.Type),e.Field._configure(e.Type),ui.exports}());const ya={nested:{easemob:{nested:{pb:{nested:{MessageBody:{fields:{type:{type:"Type",id:1},from:{type:"JID",id:2},to:{type:"JID",id:3},contents:{rule:"repeated",type:"Content",id:4},ext:{rule:"repeated",type:"KeyValue",id:5},ackMessageId:{type:"uint64",id:6},msgConfig:{type:"MessageConfig",id:7},ackContent:{type:"string",id:8},meta:{type:"string",id:9},editMessageId:{type:"uint64",id:11},editScope:{type:"EditScope",id:12},stream:{type:"Stream",id:13},userInfoUpdateTime:{type:"int32",id:14},namecardUpdateTime:{type:"int32",id:15},sendToPeer:{type:"bool",id:16},ackMessageIds:{rule:"repeated",type:"uint64",id:17},clearAllUnreadMessageCount:{type:"bool",id:18}},nested:{Content:{fields:{type:{type:"Type",id:1},text:{type:"string",id:2},latitude:{type:"double",id:3},longitude:{type:"double",id:4},address:{type:"string",id:5},displayName:{type:"string",id:6},remotePath:{type:"string",id:7},secretKey:{type:"string",id:8},fileLength:{type:"int32",id:9},action:{type:"string",id:10},params:{rule:"repeated",type:"KeyValue",id:11},duration:{type:"int32",id:12},size:{type:"Size",id:13},thumbnailRemotePath:{type:"string",id:14},thumbnailSecretKey:{type:"string",id:15},thumbnailDisplayName:{type:"string",id:16},thumbnailFileLength:{type:"int32",id:17},thumbnailSize:{type:"Size",id:18},customEvent:{type:"string",id:19},customExts:{rule:"repeated",type:"KeyValue",id:20},buildingName:{type:"string",id:21},subType:{type:"SubType",id:22},title:{type:"string",id:23},summary:{type:"string",id:24},combineLevel:{type:"int32",id:25},imageType:{type:"int32",id:26}},nested:{Type:{values:{TEXT:0,IMAGE:1,VIDEO:2,LOCATION:3,VOICE:4,FILE:5,COMMAND:6,CUSTOM:7,COMBINE:8}},Size:{fields:{width:{type:"double",id:1},height:{type:"double",id:2}}},SubType:{values:{COMBINE:0,GIF:1,SUB_STREAM:10}}}},Type:{values:{NORMAL:0,CHAT:1,GROUPCHAT:2,CHATROOM:3,READ_ACK:4,DELIVER_ACK:5,RECALL:6,CHANNEL_ACK:7,EDIT:8}},EditScope:{values:{BODY:1,BODY_AND_EXT:2}},MessageConfig:{fields:{allowGroupAck:{type:"bool",id:1}}},Stream:{fields:{streamType:{type:"string",id:1},streamSeq:{type:"uint64",id:2},streamStatus:{type:"StreamStatus",id:3},streamError:{type:"uint32",id:4},streamFinishReason:{type:"int32",id:5}},nested:{StreamStatus:{values:{STREAM_START:0,STREAM_START_COMPLETED:1,STREAM_IN_PROGRESS:2,STREAM_COMPLETED:3,STREAM_FULL:4}}}}}},KeyValue:{oneofs:{value:{oneof:["varintValue","floatValue","doubleValue","stringValue"]}},fields:{key:{type:"string",id:1},type:{type:"ValueType",id:2},varintValue:{type:"int64",id:3},floatValue:{type:"float",id:4},doubleValue:{type:"double",id:5},stringValue:{type:"string",id:6}},nested:{ValueType:{values:{BOOL:1,INT:2,UINT:3,LLINT:4,FLOAT:5,DOUBLE:6,STRING:7,JSON_STRING:8}}}},JID:{fields:{appKey:{type:"string",id:1},name:{type:"string",id:2},domain:{type:"string",id:3},clientResource:{type:"string",id:4}}},ConferenceBody:{fields:{sessionId:{type:"string",id:1},operation:{type:"Operation",id:2},conferenceId:{type:"string",id:3},type:{type:"Type",id:4},content:{type:"string",id:5},network:{type:"string",id:6},version:{type:"string",id:7},identity:{type:"Identity",id:8},duration:{type:"string",id:9},peerName:{type:"string",id:10},endReason:{type:"EndReason",id:11},status:{type:"Status",id:12},isDirect:{type:"bool",id:13},controlType:{type:"StreamControlType",id:14},routeFlag:{type:"int32",id:15},routeKey:{type:"string",id:16}},nested:{Status:{fields:{errorCode:{type:"int32",id:1}}},Operation:{values:{JOIN:0,INITIATE:1,ACCEPT_INITIATE:2,ANSWER:3,TERMINATE:4,REMOVE:5,STREAM_CONTROL:6,MEDIA_REQUEST:7}},Type:{values:{VOICE:0,VIDEO:1}},Identity:{values:{CALLER:0,CALLEE:1}},EndReason:{values:{HANGUP:0,NORESPONSE:1,REJECT:2,BUSY:3,FAIL:4,UNSUPPORTED:5,OFFLINE:6}},StreamControlType:{values:{PAUSE_VOICE:0,RESUME_VOICE:1,PAUSE_VIDEO:2,RESUME_VIDEO:3}}}},MSync:{fields:{version:{type:"Version",id:1,options:{default:"MSYNC_V1"}},guid:{type:"JID",id:2},auth:{type:"string",id:3},compressAlgorimth:{type:"uint32",id:4},crypto:{type:"uint32",id:5},userAgent:{type:"string",id:6},pov:{type:"uint64",id:7},command:{type:"Command",id:8},deviceId:{type:"uint32",id:10},encryptType:{rule:"repeated",type:"EncryptType",id:11,options:{packed:!1}},encryptKey:{type:"string",id:12},payload:{type:"bytes",id:9},traceId:{type:"uint64",id:20}},nested:{Version:{values:{MSYNC_V1:0,MSYNC_V2:1}},Command:{values:{SYNC:0,UNREAD:1,NOTICE:2,PROVISION:3,LOGOUT:4}}}},EncryptType:{values:{ENCRYPT_NONE:0,ENCRYPT_AES_128_CBC:1,ENCRYPT_AES_256_CBC:2}},CommSyncUL:{fields:{meta:{type:"Meta",id:1},key:{type:"uint64",id:2},queue:{type:"JID",id:3},isRoam:{type:"bool",id:4},lastFullRoamKey:{type:"uint64",id:5}}},CommSyncDL:{fields:{status:{type:"Status",id:1},metaId:{type:"uint64",id:2},serverId:{type:"uint64",id:3},metas:{rule:"repeated",type:"Meta",id:4},nextKey:{type:"uint64",id:5},queue:{type:"JID",id:6},isLast:{type:"bool",id:7},timestamp:{type:"uint64",id:8},isRoam:{type:"bool",id:9}}},CommNotice:{fields:{queue:{type:"JID",id:1}}},CommUnreadUL:{fields:{}},CommUnreadDL:{fields:{status:{type:"Status",id:1},unread:{rule:"repeated",type:"MetaQueue",id:2},timestamp:{type:"uint64",id:3}}},MetaQueue:{fields:{queue:{type:"JID",id:1},n:{type:"uint32",id:2}}},Meta:{fields:{id:{type:"uint64",id:1},from:{type:"JID",id:2},to:{type:"JID",id:3},timestamp:{type:"uint64",id:4},ns:{type:"NameSpace",id:5},payload:{type:"bytes",id:6},routetype:{type:"RouteType",id:7},ext:{rule:"repeated",type:"KeyValue",id:8},meta:{type:"bytes",id:9},directedUsers:{rule:"repeated",type:"string",id:10},env:{type:"string",id:13}},nested:{NameSpace:{values:{STATISTIC:0,CHAT:1,MUC:2,ROSTER:3,CONFERENCE:4,NOTIFY:5,QUERY:6}},RouteType:{values:{ROUTE_ALL:0,ROUTE_ONLINE:1,ROUTE_DIRECT:2}}}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},reason:{type:"string",id:2},redirectInfo:{rule:"repeated",type:"RedirectInfo",id:3}},nested:{ErrorCode:{values:{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}}}},RedirectInfo:{fields:{host:{type:"string",id:1},port:{type:"uint32",id:2}}},Provision:{fields:{osType:{type:"OsType",id:1},version:{type:"string",id:2},networkType:{type:"NetworkType",id:3},appSign:{type:"string",id:4},compressType:{rule:"repeated",type:"CompressType",id:5,options:{packed:!1}},encryptType:{rule:"repeated",type:"EncryptType",id:6,options:{packed:!1}},encryptKey:{type:"string",id:7},status:{type:"Status",id:8},deviceUuid:{type:"string",id:9},isManualLogin:{type:"bool",id:10},password:{type:"string",id:11},deviceName:{type:"string",id:12},resource:{type:"string",id:13},auth:{type:"string",id:14},serviceId:{type:"string",id:16},actionVersion:{type:"string",id:17},authToken:{type:"string",id:18},osCustomValue:{type:"uint32",id:19},sessionId:{type:"string",id:20},reason:{type:"string",id:21},protocolCompressType:{rule:"repeated",type:"CompressType",id:22},protocolCompressDirection:{type:"CompressDirection",id:23}},nested:{OsType:{values:{OS_IOS:0,OS_ANDROID:1,OS_LINUX:2,OS_OSX:3,OS_WIN:4,OS_CUSTOM:5,OS_OTHER:16}},NetworkType:{values:{NETWORK_NONE:0,NETWORK_WIFI:1,NETWORK_4G:2,NETWORK_3G:3,NETWORK_2G:4,NETWORK_WIRE:5}},CompressType:{values:{COMPRESS_NONE:0,COMPRESS_ZLIB:1,COMPRESS_LZ4:2}},CompressDirection:{values:{ONLY_UP:0,ONLY_DOWN:1,BI:2}}}},Logout:{fields:{sessionId:{type:"string",id:1},reason:{type:"string",id:2},status:{type:"Status",id:3}}},MUCBody:{fields:{mucId:{type:"JID",id:1},operation:{type:"Operation",id:2},from:{type:"JID",id:3},to:{rule:"repeated",type:"JID",id:4},setting:{type:"Setting",id:5},reason:{type:"string",id:6},isChatroom:{type:"bool",id:7},status:{type:"Status",id:8},isThread:{type:"bool",id:9},mucParentId:{type:"JID",id:10},mucName:{type:"string",id:11},eventInfo:{type:"EventInfo",id:12},mucMemberCount:{type:"int32",id:13},ext:{type:"string",id:14},leaveOtherRooms:{type:"bool",id:15},members:{rule:"repeated",type:"string",id:16}},nested:{Operation:{values:{CREATE:0,DESTROY:1,JOIN:2,LEAVE:3,APPLY:4,APPLY_ACCEPT:5,APPLY_DECLINE:6,INVITE:7,INVITE_ACCEPT:8,INVITE_DECLINE:9,KICK:10,GET_BLACKLIST:11,BAN:12,ALLOW:13,UPDATE:14,BLOCK:15,UNBLOCK:16,PRESENCE:17,ABSENCE:18,DIRECT_JOINED:19,ASSIGN_OWNER:20,ADD_ADMIN:21,REMOVE_ADMIN:22,ADD_MUTE:23,REMOVE_MUTE:24,UPDATE_ANNOUNCEMENT:25,DELETE_ANNOUNCEMENT:26,UPLOAD_FILE:27,DELETE_FILE:28,ADD_USER_WHITE_LIST:29,REMOVE_USER_WHITE_LIST:30,BAN_GROUP:31,REMOVE_BAN_GROUP:32,THREAD_CREATE:33,THREAD_DESTROY:34,THREAD_JOIN:35,THREAD_LEAVE:36,THREAD_KICK:37,THREAD_UPDATE:38,THREAD_PRESENCE:39,THREAD_ABSENCE:40,DISABLE_GROUP:41,ABLE_GROUP:42,SET_METADATA:43,DELETE_METADATA:44,GROUP_MEMBER_METADATA_UPDATE:45}},Setting:{fields:{name:{type:"string",id:1},desc:{type:"string",id:2},type:{type:"Type",id:3},maxUsers:{type:"int32",id:4},owner:{type:"string",id:5}},nested:{Type:{values:{PRIVATE_OWNER_INVITE:0,PRIVATE_MEMBER_INVITE:1,PUBLIC_JOIN_APPROVAL:2,PUBLIC_JOIN_OPEN:3,PUBLIC_ANONYMOUS:4}}}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},description:{type:"string",id:2},chatroomInfo:{type:"string",id:3}},nested:{ErrorCode:{values:{OK:0,PERMISSION_DENIED:1,WRONG_PARAMETER:2,MUC_NOT_EXIST:3,USER_NOT_EXIST:4,UNKNOWN:5}}}},EventInfo:{fields:{eventType:{type:"EventType",id:1,options:{default:"EVENT_NONE"}},ext:{type:"string",id:2}},nested:{EventType:{values:{EVENT_NONE:0,CIRCLE_CHANNEL:1}}}}}},RosterBody:{fields:{operation:{type:"Operation",id:1},status:{type:"Status",id:2},from:{type:"JID",id:3},to:{rule:"repeated",type:"JID",id:4},reason:{type:"string",id:5},rosterVer:{type:"string",id:6},biDirection:{type:"bool",id:7}},nested:{Operation:{values:{GET_ROSTER:0,GET_BLACKLIST:1,ADD:2,REMOVE:3,ACCEPT:4,DECLINE:5,BAN:6,ALLOW:7,REMOTE_ACCEPT:8,REMOTE_DECLINE:9}},Status:{fields:{errorCode:{type:"ErrorCode",id:1},description:{type:"string",id:2}},nested:{ErrorCode:{values:{OK:0,USER_NOT_EXIST:1,USER_ALREADY_FRIEND:2,USER_ALREADY_BLACKLIST:3}}}}}},StatisticsBody:{fields:{operation:{type:"Operation",id:1},os:{type:"OsType",id:2},version:{type:"string",id:3},network:{type:"NetworkType",id:4},imTime:{type:"uint32",id:5},chatTime:{type:"uint32",id:6},location:{type:"string",id:7},reason:{type:"string",id:10}},nested:{Operation:{values:{INFORMATION:0,USER_REMOVED:1,USER_LOGIN_ANOTHER_DEVICE:2,USER_KICKED_BY_CHANGE_PASSWORD:3,USER_KICKED_BY_OTHER_DEVICE:4}},OsType:{values:{OS_IOS:0,OS_ANDROID:1,OS_LINUX:2,OS_OSX:3,OS_WIN:4,OS_CUSTOM:5,OS_OTHER:16}},NetworkType:{values:{NETWORK_NONE:0,NETWORK_WIFI:1,NETWORK_4G:2,NETWORK_3G:3,NETWORK_2G:4,NETWORK_WIRE:5}}}}}}}}}},va=e=>{if(!e||0===e.trim().length)throw un("Proto type name is required.",{code:dn,stage:tn,retryable:!1,details:{typeName:e}})};class Ia{constructor(){this.codecMap=new Map}register(e,t){va(e),this.codecMap.set(e,t)}registerType(e,t){this.register(e,{encode:r=>{const s=((e,t)=>{if("object"==typeof e&&null!==e)return e;throw un("Proto payload must be an object.",{code:dn,stage:tn,retryable:!1,details:{typeName:t,payloadType:typeof e}})})(r,e),n=t.fromObject(s);return t.encode(n).finish()},decode:e=>{const r=t.decode(e);return t.toObject(r,{longs:String,enums:Number,defaults:!1})}})}get(e){return va(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw un("Proto codec not found.",{code:dn,stage:tn,retryable:!1,details:{typeName:e}})}}const ba=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),_a=e=>{class t extends fa.Message{constructor(e){super(),((e,t)=>{if(t)for(const r of Object.keys(t)){const s=t[r];null!=s&&(e[r]=s)}})(this,e)}}const r=t;return r.$type=e,r.prototype.$type=e,r},Ta=e=>Pn.isLong(e),Ca=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"number"==typeof e.byteLength,Sa=e=>Object.prototype.hasOwnProperty.call(fa.types.packed,e),Ea=e=>{const t=e.resolve();return t.resolvedType instanceof fa.Enum||Sa(t.type)},wa=(e,t)=>t in e?e[t]:void 0,Aa=e=>{const t=e.resolve();return t.resolvedType instanceof fa.Enum?0:(r=t.type,Object.prototype.hasOwnProperty.call(fa.types.basic,r)?fa.types.basic[t.type]:2);var r},Ra=(e,t)=>Ta(e)||"number"==typeof e||"string"==typeof e?e:ba(e)&&"number"==typeof e.low&&"number"==typeof e.high?new Pn(e.low,e.high,t):t?Pn.UZERO:Pn.ZERO,Na=(e,t,r)=>{switch(t){case"double":return e.double(Number(r));case"float":return e.float(Number(r));case"int32":return e.int32(Number(r));case"uint32":return e.uint32(Number(r));case"sint32":return e.sint32(Number(r));case"fixed32":return e.fixed32(Number(r));case"sfixed32":return e.sfixed32(Number(r));case"int64":return e.int64(Ra(r,!1));case"uint64":return e.uint64(Ra(r,!0));case"sint64":return e.sint64(Ra(r,!1));case"fixed64":return e.fixed64(Ra(r,!0));case"sfixed64":return e.sfixed64(Ra(r,!1));case"bool":return e.bool(Boolean(r));case"string":return e.string(String(r));case"bytes":return e.bytes((e=>"string"==typeof e?e:Ca(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)?Uint8Array.from(e.filter(e=>"number"==typeof e)):new Uint8Array)(r));default:throw new TypeError(`Unsupported protobuf field type: ${t}`)}},Oa=(e,t,r)=>{if(t<0||e.pos+t>r)throw RangeError(`index out of range: ${e.pos} + ${t} > ${r}`)},Ma=(e,t)=>{const r=e.uint32();return Oa(e,r,t),r},Ua=(e,t,r)=>{const s=e.len;e.len=r;try{switch(t){case 0:return void e.skip();case 1:return Oa(e,8,r),void e.skip(8);case 2:{const t=Ma(e,r);return void e.skip(t)}case 5:return Oa(e,4,r),void e.skip(4);default:throw new Error(`Unsupported protobuf wire type: ${String(t)}`)}}finally{e.len=s}},La=(e,t,r)=>{const s=t.resolve(),n=s.resolvedType;if(n instanceof fa.Type){const t=e.fork();return Da(n,ba(r)?r:{},t),t.ldelim(),e}return n instanceof fa.Enum?(e.int32("number"==typeof r?r:Number(r)),e):Na(e,s.type,r)},ka=(e,t,r)=>{if(0===r.length)return e;const s=t.resolve();if(Sa(s.type)&&t.packed){e.uint32(t.id<<3|2).fork();for(const s of r)La(e,t,s);return e.ldelim(),e}const n=Aa(t);for(const i of r)e.uint32(t.id<<3|n),La(e,t,i);return e},Da=(e,t,r=fa.Writer.create())=>{const s=e.fieldsArray.slice().sort(fa.util.compareFieldsById);for(const n of s){const e=wa(t,n.name);null!=e&&(n.repeated?ka(r,n,Array.isArray(e)?e:[]):(r.uint32(n.id<<3|Aa(n)),La(r,n,e)))}return r},Pa=(e,t,r,s)=>{const n=t.resolve(),i=n.resolvedType;return i instanceof fa.Type?2!==r?void Ua(e,r,s):xa(i,e,Ma(e,s)):i instanceof fa.Enum?e.int32():((e,t)=>{switch(t){case"double":return e.double();case"float":return e.float();case"int32":return e.int32();case"uint32":return e.uint32();case"sint32":return e.sint32();case"fixed32":return e.fixed32();case"sfixed32":return e.sfixed32();case"int64":return e.int64();case"uint64":return e.uint64();case"sint64":return e.sint64();case"fixed64":return e.fixed64();case"sfixed64":return e.sfixed64();case"bool":return e.bool();case"string":return e.string();case"bytes":return e.bytes();default:throw new TypeError(`Unsupported protobuf field type: ${t}`)}})(e,n.type)},xa=(e,t,r)=>{const s=t instanceof fa.Reader?t:fa.Reader.create(t),n=void 0===r?s.len:s.pos+r,i=(e=>{const t={};for(const r of e.fieldsArray)r.repeated&&(t[r.name]=[]);return t})(e),o=e.fieldsById;for(;s.pos<n;){const t=s.pos,r=s.uint32(),c=o[r>>>3],d=7&r;try{if(!c){Ua(s,d,n);continue}if(c.repeated){const e=Array.isArray(i[c.name])?i[c.name]:[];if(Ea(c)&&2===d){const t=Ma(s,n)+s.pos;for(;s.pos<t;)e.push(Pa(s,c,0,t))}else{const t=Pa(s,c,d,n);void 0!==t&&e.push(t)}i[c.name]=e;continue}const e=Pa(s,c,d,n);void 0!==e&&(i[c.name]=e)}catch(a){if(a instanceof RangeError){const i=c?`${c.name}#${c.id}`:`unknown#${r>>>3}`;throw new RangeError(`${a.message}; protobufType=${e.fullName}; field=${i}; tag=${r}; wireType=${d}; tagPosition=${t}; readerPosition=${s.pos}; messageEnd=${n}`)}throw a}}return i},Fa=(e,t)=>t?.longs===String?e.toString():t?.longs===Number?e.toNumber():e,Ba=(e,t)=>{const r=e.resolve();if(r.resolvedType instanceof fa.Type)return null;if(r.resolvedType instanceof fa.Enum){if(t?.enums===String){return r.resolvedType.valuesById[r.typeDefault]??r.typeDefault}return r.typeDefault}return"bytes"===r.type?t?.bytes===String?"":t?.bytes===Array?[]:new Uint8Array:r.long&&Ta(r.typeDefault)?Fa(r.typeDefault,t):r.typeDefault},Ga=(e,t,r)=>{const s=e.resolve();if(void 0!==t)return s.resolvedType instanceof fa.Type?ba(t)?qa(s.resolvedType,t,r):t:s.resolvedType instanceof fa.Enum?r?.enums===String&&"number"==typeof t?s.resolvedType.valuesById[t]??t:t:s.long&&Ta(t)?Fa(t,r):"bytes"===s.type&&Ca(t)?((e,t)=>t?.bytes===String?fa.util.base64.encode(e,0,e.length):t?.bytes===Array?Array.prototype.slice.call(e):e)(t,r):t},qa=(e,t,r)=>{const s={};for(const n of e.fieldsArray.slice().sort(fa.util.compareFieldsById)){const e=wa(t,n.name);n.repeated?Array.isArray(e)?s[n.name]=e.map(e=>Ga(n,e,r)):(r?.arrays||r?.defaults)&&(s[n.name]=[]):null==e?r?.defaults&&(s[n.name]=Ba(n,r)):s[n.name]=Ga(n,e,r)}return s},$a=e=>{const t=e;t.__reflectionCodecInstalled||(t.__reflectionCodecInstalled=!0,e.encode=(t,r)=>Da(e,ba(t)?t:{},r),e.decode=(t,r)=>xa(e,t,r),e.fromObject=e=>ba(e)?e:{},e.toObject=(t,r)=>qa(e,ba(t)?t:{},r),e.create=e=>e?{...e}:{},e.verify=()=>null)},ja=e=>{$a(e);for(const t of e.nestedArray)if(t instanceof fa.Type)ja(t);else if(t instanceof fa.Namespace)for(const e of t.nestedArray)e instanceof fa.Type&&ja(e)},Va=e=>{for(const t of e.nestedArray)t instanceof fa.Type?ja(t):t instanceof fa.Namespace&&Va(t)},Ka=()=>{const e=fa.Type;e.__reflectionRuntimeInstalled||(e.generateConstructor=e=>()=>_a(e),fa.Type.prototype.setup=function(){return $a(this),this},fa.Type.prototype.create=function(e){return e?{...e}:{}},fa.Type.prototype.encode=function(e,t){return Da(this,ba(e)?e:{},t)},fa.Type.prototype.decode=function(e,t){return xa(this,e,t)},fa.Type.prototype.fromObject=function(e){return ba(e)?e:{}},fa.Type.prototype.toObject=function(e,t){return qa(this,ba(e)?e:{},t)},fa.Type.prototype.verify=function(){return null},e.__reflectionRuntimeInstalled=!0)};let za=!1,Ha=null,Wa=null,Ja=null;const Qa=e=>e.startsWith(".")?e.slice(1):e,Za=e=>e instanceof fa.Namespace,Ya=e=>e instanceof fa.Type,Xa=e=>{for(const t of e.nestedArray)Ya(t)?ja(t):Za(t)&&Xa(t)},ec=()=>{za||(fa.util.Long=Pn,fa.configure(),za=!0),Ka();const e=fa.Root.fromJSON(ya);return Xa(e),e},tc=(e,t)=>{const r=e.nestedArray;for(const s of r){if(Ya(s)){const e=Qa(s.fullName);ja(s),t.registerType(e,s);continue}Za(s)&&tc(s,t)}},rc=(e,t,r)=>{const s=t instanceof Error?t.message:String(t);return un(`Static proto ${r} failed.`,{code:dn,stage:tn,retryable:!1,details:{typeName:e,operation:r,cause:s}})},sc=()=>Ha||(Ha=ec(),Ha),nc=()=>{if(Ja)return Ja;const e=(()=>{if(Wa)return Wa;const e=new Ia,t=sc();return tc(t,e),Wa=e,e})();return Ja={encode(t,r){try{return e.getOrThrow(Qa(t)).encode(r)}catch(s){throw rc(t,s,"encode")}},decode(t,r){try{return e.getOrThrow(Qa(t)).decode(r)}catch(s){throw rc(t,s,"decode")}}},Ja},ic=e=>{const t={};if(!e)return t;if("function"==typeof e.forEach)return e.forEach((e,r)=>{t[r]=e}),t;const r=e.get?.("content-type");return r&&(t["content-type"]=r),t},oc=async(e,t)=>{const r=e;if("function"!=typeof r.text){if("function"!=typeof r.json)return"";const e=await r.json();return t?e:JSON.stringify(e)}const s=await r.text();if(!t||0===s.length)return s;try{return JSON.parse(s)}catch{return s}},ac=e=>{const t=e?.fetchImpl;if("function"==typeof t)return{async request(r){const s=r.method??"GET",n={...r.headers??{}},i=new AbortController,o=r.timeoutMs??e?.timeoutMs??15e3;let a=!1;const c=()=>i.abort(r.signal?.reason);r.signal?.aborted?c():r.signal?.addEventListener("abort",c,{once:!0});const d=setTimeout(()=>{a=!0,i.abort()},o),u=((e,t,r)=>{if(e.body instanceof Uint8Array)return new Uint8Array(e.body).buffer;if("string"==typeof e.body)return e.body;if(e.body&&"GET"!==r)return Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),JSON.stringify(e.body)})(r,n,s);try{const e=await t(r.url,{method:s,headers:n,body:u,signal:i.signal});let o;if("arraybuffer"===r.responseType)o=await e.arrayBuffer();else if("text"===r.responseType)o=await e.text();else if("json"===r.responseType)o=await oc(e,!0);else{const t=e.headers.get("content-type")??"";o=await oc(e,t.includes("application/json"))}return{status:e.status,statusText:e.statusText,headers:ic(e.headers),data:o}}catch(l){const e=((e,t,r)=>t?"timeout":r?.aborted||e instanceof Error&&"AbortError"===e.name?"abort":"network")(l,a,r.signal);throw un("Request adapter execution failed.",{code:on,stage:Ys,retryable:"abort"!==e,details:{url:r.url,method:s,reason:e,cause:l instanceof Error?l.message:String(l)}})}finally{clearTimeout(d),r.signal?.removeEventListener("abort",c)}}}},cc=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,dc=e=>"function"==typeof e.on&&"function"==typeof e.off,uc=(e,t,r)=>{if(cc(e))return e.addEventListener(t,r),()=>{e.removeEventListener(t,r)};if(dc(e)){const s=e;return s.on(t,r),()=>{s.off(t,r)}}throw un("Socket event listener API is unsupported.",{code:cn,stage:en,retryable:!1,details:{event:t}})},lc=(e,t,r)=>{if(cc(e)){const s=(...n)=>{e.removeEventListener(t,s),r(...n)};return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)}}if(dc(e)){const s=e;if("function"==typeof s.once)return s.once?.(t,r),()=>{s.off(t,r)};let n=()=>{};return n=uc(e,t,(...e)=>{n(),r(...e)}),n}throw un("Socket one-time listener API is unsupported.",{code:cn,stage:en,retryable:!1,details:{event:t}})},hc=e=>{return"string"==typeof e||(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))||"undefined"!=typeof Blob&&e instanceof Blob?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:e&&"object"==typeof e&&"data"in e?hc(e.data):null;var t},pc=e=>{const t=new Set,r=new Set,s=new Set,n=new Set;return uc(e,"open",()=>{t.forEach(e=>{e()})}),uc(e,"message",(...e)=>{const t=hc(e[0]);null!==t&&r.forEach(e=>{e(t)})}),uc(e,"error",(...e)=>{const t=e[0];s.forEach(e=>{e(t)})}),uc(e,"close",(...e)=>{const t=(e=>{const[t,r]=e;if(t&&"object"==typeof t){const e=t;return{code:"number"==typeof e.code?e.code:void 0,reason:"string"==typeof e.reason?e.reason:void 0}}return{code:"number"==typeof t?t:void 0,reason:"string"==typeof r?r:ArrayBuffer.isView(r)?(new TextDecoder).decode(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)):void 0}})(e);n.forEach(e=>{e(t)})}),{get readyState(){return e.readyState},send(t){if(e.readyState!==hn)throw un("Socket is not open.",{code:cn,stage:en,retryable:!0,details:{readyState:e.readyState}});return e.send(t),Promise.resolve()},close(t,r){e.close(t,r)},onOpen:e=>(t.add(e),()=>{t.delete(e)}),onMessage:e=>(r.add(e),()=>{r.delete(e)}),onError:e=>(s.add(e),()=>{s.delete(e)}),onClose:e=>(n.add(e),()=>{n.delete(e)})}},mc=e=>{const t=e?.webSocketCtor;if(void 0!==t)return{connect:e=>new Promise((r,s)=>{let n;try{n=new t(e.url,e.protocols);try{n.binaryType="arraybuffer"}catch{}}catch(l){return void s(un("Socket creation failed.",{code:cn,stage:en,retryable:!0,details:{cause:l instanceof Error?l.message:String(l)}}))}let i,o=()=>{},a=()=>{},c=!1;const d=()=>{void 0!==i&&(clearTimeout(i),i=void 0)},u=()=>{c||(c=!0,o(),a(),d(),n.close(),s(un("Socket connection timed out.",{code:cn,stage:en,retryable:!0,details:{url:e.url,reason:"timeout"}})))};o=lc(n,"open",()=>{c||(c=!0,o(),a(),d(),r(pc(n)))}),a=lc(n,"error",e=>{if(c)return;c=!0,o(),a(),d();const t=e&&"object"==typeof e&&"type"in e?String(e.type):void 0;s(un("Socket connection failed before open.",{code:cn,stage:en,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(u,e.timeoutMs))})}},gc=(e,t)=>{throw un("Upload adapter execution failed.",{code:an,stage:Xs,retryable:"abort"!==e,details:{reason:e,url:t.url}})},fc=e=>{const t=new FormData;return Object.entries(e.fields??{}).forEach(([e,r])=>{t.append(e,r)}),((e,t)=>{if("web-file"!==t.source.sourceType)throw un("Web upload adapter only supports web-file source.",{code:an,stage:Xs,retryable:!1,details:{sourceType:t.source.sourceType}});const r=t.source.file;if(!r)throw un("Upload source file is required for web-file uploads.",{code:an,stage:Xs,retryable:!1,details:{sourceType:t.source.sourceType}});const s="undefined"!=typeof Blob&&r instanceof Blob,n=t.source.name??"upload.bin",i=t.fileFieldName??"file";s?e.append(i,r,n):e.append(i,r)})(t,e),t},yc=(e,t,r)=>new Promise((s,n)=>{const i=e(),o=r.timeoutMs??t?.timeoutMs??3e4;((e,t)=>{e.upload&&t.onProgress&&e.upload.addEventListener("progress",e=>{if(!e.lengthComputable)return void t.onProgress?.({loaded:e.loaded});const r=e.total>0?e.loaded/e.total*100:void 0;t.onProgress?.({loaded:e.loaded,total:e.total,percent:r})})})(i,r),i.addEventListener("abort",()=>{try{gc("abort",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("timeout",()=>{try{gc("timeout",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("error",()=>{try{gc("network",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("load",()=>{s({status:i.status,body:i.responseText})});try{const e=fc(r);i.timeout=o,i.open(r.method??"POST",r.url),((e,t)=>{Object.entries(t??{}).forEach(([t,r])=>{e.setRequestHeader(t,r)})})(i,r.headers),i.send(e)}catch(a){n(un("Upload adapter execution failed.",{code:an,stage:Xs,retryable:!1,details:{url:r.url,reason:"invalid-config",cause:a instanceof Error?a.message:String(a)}}))}}),vc=(e,t)=>e?"timeout":"abort",Ic=e=>{const t=Boolean(e&&"xhrFactory"in e)?e?.xhrFactory:"undefined"!=typeof XMLHttpRequest?()=>new XMLHttpRequest:void 0,r=e?.fetchImpl;if("function"==typeof t||"function"==typeof r)return{upload(s){if("function"==typeof t)return yc(t,e,s);if("function"==typeof r)return(async(e,t,r)=>{const s=r.timeoutMs??t?.timeoutMs??3e4;let n=!1;const i="undefined"!=typeof AbortController?new AbortController:void 0,o=i&&Number.isFinite(s)?setTimeout(()=>{n=!0,i.abort()},s):void 0,a=((e,t)=>e??t?.signal)(r.signal,i);try{const t=fc(r),s=await e(r.url,{method:r.method??"POST",headers:r.headers,body:t,signal:a}),n=await s.text(),i=r.source.size;return"number"==typeof i&&r.onProgress?.({loaded:i,total:i,percent:i>0?100:void 0}),{status:s.status,body:n}}catch(c){const e=c instanceof Error&&"AbortError"===c.name;throw un("Upload adapter execution failed.",{code:an,stage:Xs,retryable:!e,details:{reason:e?vc(n):"network",url:r.url,cause:c instanceof Error?c.message:String(c)}})}finally{o&&clearTimeout(o)}})(r,e,s);throw un("Upload adapter execution failed.",{code:an,stage:Xs,retryable:!1,details:{reason:"missing-upload-runtime",url:s.url}})}}},bc=(e,t)=>{const r=new e;return Object.entries(t.fields??{}).forEach(([e,t])=>{r.append(e,t)}),r.append(t.fileFieldName??"file",(e=>{const t=e.source;if("rn-uri"!==t.sourceType||!t.uri)throw un("React Native upload adapter only supports rn-uri source.",{code:an,stage:Xs,retryable:!1,details:{sourceType:t.sourceType}});return{uri:t.uri,name:t.name??"upload.bin",type:t.mimeType??"application/octet-stream"}})(t)),r},_c=e=>{const t=e?.fetchImpl,r=e?.formDataCtor;if("function"==typeof t&&"function"==typeof r)return{async upload(s){const n=s.timeoutMs??e?.timeoutMs??3e4,i="function"==typeof AbortController?new AbortController:void 0;let o=!1;const a=i&&Number.isFinite(n)?setTimeout(()=>{o=!0,i.abort()},n):void 0;try{const e=bc(r,s),n=await t(s.url,{method:s.method??"POST",headers:s.headers,body:e,signal:s.signal??i?.signal}),o=await n.text(),a=s.source.size;return"number"==typeof a&&s.onProgress?.({loaded:a,total:a,percent:a>0?100:void 0}),{status:n.status,body:o}}catch(c){if((e=>{if("object"!=typeof e||null===e)return!1;const t=e;return t.code===an&&t.stage===Xs})(c))throw c;const e=c instanceof Error&&"AbortError"===c.name;throw un("React Native upload adapter execution failed.",{code:an,stage:Xs,retryable:!e||o,details:{url:s.url,reason:e?o?"timeout":"abort":"network",cause:c instanceof Error?c.message:String(c)}})}finally{void 0!==a&&clearTimeout(a)}}}},Tc=(e,t)=>e+t&4294967295,Cc=(e,t,r,s,n,i)=>{return Tc((o=Tc(Tc(t,e),Tc(s,i)))<<(a=n)|o>>>32-a,r);var o,a},Sc=(e,t,r,s,n,i,o)=>Cc(t&r|~t&s,e,t,n,i,o),Ec=(e,t,r,s,n,i,o)=>Cc(t&s|r&~s,e,t,n,i,o),wc=(e,t,r,s,n,i,o)=>Cc(t^r^s,e,t,n,i,o),Ac=(e,t,r,s,n,i,o)=>Cc(r^(t|~s),e,t,n,i,o),Rc=(e,t)=>{let[r,s,n,i]=e;r=Sc(r,s,n,i,t[0]??0,7,-680876936),i=Sc(i,r,s,n,t[1]??0,12,-389564586),n=Sc(n,i,r,s,t[2]??0,17,606105819),s=Sc(s,n,i,r,t[3]??0,22,-1044525330),r=Sc(r,s,n,i,t[4]??0,7,-176418897),i=Sc(i,r,s,n,t[5]??0,12,1200080426),n=Sc(n,i,r,s,t[6]??0,17,-1473231341),s=Sc(s,n,i,r,t[7]??0,22,-45705983),r=Sc(r,s,n,i,t[8]??0,7,1770035416),i=Sc(i,r,s,n,t[9]??0,12,-1958414417),n=Sc(n,i,r,s,t[10]??0,17,-42063),s=Sc(s,n,i,r,t[11]??0,22,-1990404162),r=Sc(r,s,n,i,t[12]??0,7,1804603682),i=Sc(i,r,s,n,t[13]??0,12,-40341101),n=Sc(n,i,r,s,t[14]??0,17,-1502002290),s=Sc(s,n,i,r,t[15]??0,22,1236535329),r=Ec(r,s,n,i,t[1]??0,5,-165796510),i=Ec(i,r,s,n,t[6]??0,9,-1069501632),n=Ec(n,i,r,s,t[11]??0,14,643717713),s=Ec(s,n,i,r,t[0]??0,20,-373897302),r=Ec(r,s,n,i,t[5]??0,5,-701558691),i=Ec(i,r,s,n,t[10]??0,9,38016083),n=Ec(n,i,r,s,t[15]??0,14,-660478335),s=Ec(s,n,i,r,t[4]??0,20,-405537848),r=Ec(r,s,n,i,t[9]??0,5,568446438),i=Ec(i,r,s,n,t[14]??0,9,-1019803690),n=Ec(n,i,r,s,t[3]??0,14,-187363961),s=Ec(s,n,i,r,t[8]??0,20,1163531501),r=Ec(r,s,n,i,t[13]??0,5,-1444681467),i=Ec(i,r,s,n,t[2]??0,9,-51403784),n=Ec(n,i,r,s,t[7]??0,14,1735328473),s=Ec(s,n,i,r,t[12]??0,20,-1926607734),r=wc(r,s,n,i,t[5]??0,4,-378558),i=wc(i,r,s,n,t[8]??0,11,-2022574463),n=wc(n,i,r,s,t[11]??0,16,1839030562),s=wc(s,n,i,r,t[14]??0,23,-35309556),r=wc(r,s,n,i,t[1]??0,4,-1530992060),i=wc(i,r,s,n,t[4]??0,11,1272893353),n=wc(n,i,r,s,t[7]??0,16,-155497632),s=wc(s,n,i,r,t[10]??0,23,-1094730640),r=wc(r,s,n,i,t[13]??0,4,681279174),i=wc(i,r,s,n,t[0]??0,11,-358537222),n=wc(n,i,r,s,t[3]??0,16,-722521979),s=wc(s,n,i,r,t[6]??0,23,76029189),r=wc(r,s,n,i,t[9]??0,4,-640364487),i=wc(i,r,s,n,t[12]??0,11,-421815835),n=wc(n,i,r,s,t[15]??0,16,530742520),s=wc(s,n,i,r,t[2]??0,23,-995338651),r=Ac(r,s,n,i,t[0]??0,6,-198630844),i=Ac(i,r,s,n,t[7]??0,10,1126891415),n=Ac(n,i,r,s,t[14]??0,15,-1416354905),s=Ac(s,n,i,r,t[5]??0,21,-57434055),r=Ac(r,s,n,i,t[12]??0,6,1700485571),i=Ac(i,r,s,n,t[3]??0,10,-1894986606),n=Ac(n,i,r,s,t[10]??0,15,-1051523),s=Ac(s,n,i,r,t[1]??0,21,-2054922799),r=Ac(r,s,n,i,t[8]??0,6,1873313359),i=Ac(i,r,s,n,t[15]??0,10,-30611744),n=Ac(n,i,r,s,t[6]??0,15,-1560198380),s=Ac(s,n,i,r,t[13]??0,21,1309151649),r=Ac(r,s,n,i,t[4]??0,6,-145523070),i=Ac(i,r,s,n,t[11]??0,10,-1120210379),n=Ac(n,i,r,s,t[2]??0,15,718787259),s=Ac(s,n,i,r,t[9]??0,21,-343485551),e[0]=Tc(r,e[0]),e[1]=Tc(s,e[1]),e[2]=Tc(n,e[2]),e[3]=Tc(i,e[3])},Nc=(e,t)=>{const r=new Array(16).fill(0);for(let s=0;s<16;s+=1){const n=t+4*s;r[s]=(e[n]??0)|(e[n+1]??0)<<8|(e[n+2]??0)<<16|(e[n+3]??0)<<24}return r},Oc=e=>{let t="";for(let r=0;r<4;r+=1){t+=(e>>8*r&255).toString(16).padStart(2,"0")}return t},Mc=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let r=0;for(;r+64<=e.length;r+=64)Rc(t,Nc(e,r));const s=new Array(16).fill(0);let n=0;for(;r<e.length;r+=1){const t=n>>2;s[t]=(s[t]??0)|(e[r]??0)<<n%4*8,n+=1}const i=n>>2;s[i]=(s[i]??0)|128<<n%4*8,n>55&&(Rc(t,s),s.fill(0));const o=8*e.length;return s[14]=4294967295&o,s[15]=Math.floor(o/4294967296),Rc(t,s),t.map(Oc).join("")},Uc=async e=>{if("function"==typeof createImageBitmap){const t=await createImageBitmap(e);return{image:t,width:t.width,height:t.height,cleanup:()=>{t.close()}}}if("undefined"==typeof Image||"undefined"==typeof URL)throw un("Image decode capability is missing for current platform",{code:nn,stage:rn,retryable:!1,details:{reason:"image decode unavailable"}});const t=URL.createObjectURL(e);return new Promise((e,r)=>{const s=new Image;s.onload=()=>{e({image:s,width:s.naturalWidth||s.width,height:s.naturalHeight||s.height,cleanup:()=>{URL.revokeObjectURL(t)}})},s.onerror=()=>{URL.revokeObjectURL(t),r(un("Image decode failed",{code:an,stage:rn,retryable:!1,details:{reason:"image load error"}}))},s.src=t})},Lc=e=>{if(!(e=>"web-file"===e.sourceType&&"undefined"!=typeof Blob&&e.file instanceof Blob)(e))throw un("Web image processor only supports web file source",{code:nn,stage:rn,retryable:!1,details:{sourceType:e.sourceType}});return e.file},kc=()=>({async getImageInfo(e){const t=Lc(e),r=await Uc(t);try{return{width:r.width,height:r.height,mimeType:e.mimeType,fileSize:e.size,isGif:"image/gif"===e.mimeType}}finally{r.cleanup()}},async generateBigImage(e,t){const r=Lc(e),s=await Uc(r);try{const r=((e,t,r)=>{const s=Math.min(e,t);if(s<=r)return{width:e,height:t};const n=r/s;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(s.width,s.height,t.maxShortEdge),i=((e,t)=>{if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(e,t);if("undefined"!=typeof document){const r=document.createElement("canvas");return r.width=e,r.height=t,r}throw un("Canvas capability is missing for current platform",{code:nn,stage:rn,retryable:!1,details:{reason:"canvas unavailable"}})})(r.width,r.height),o=i.getContext("2d");if(!o)throw un("Canvas 2d context is missing",{code:nn,stage:rn,retryable:!1});o.drawImage(s.image,0,0,r.width,r.height);const a="image/png"===(n=e.mimeType)||"image/webp"===n?n:"image/jpeg",c=await(async(e,t,r)=>{if("convertToBlob"in e&&"function"==typeof e.convertToBlob)return e.convertToBlob({type:t,quality:r});if("toBlob"in e&&"function"==typeof e.toBlob)return new Promise((s,n)=>{e.toBlob(e=>{e?s(e):n(un("Image encode failed",{code:an,stage:rn,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},t,r)});throw un("Canvas encode capability is missing for current platform",{code:nn,stage:rn,retryable:!1,details:{reason:"canvas encode unavailable"}})})(i,a,t.quality),d=(e=>e.name??"image")(e),u="undefined"!=typeof File?new File([c],d,{type:a,lastModified:Date.now()}):void 0;return{source:{sourceType:"web-file",file:u??c,name:d,mimeType:a,size:u?.size??c.size},width:r.width,height:r.height,fileName:d,fileType:a,fileSize:u?.size??c.size,webFile:u}}finally{s.cleanup()}var n},async computeMd5(e){const t=Lc(e),r=await(async e=>{if("function"==typeof e.arrayBuffer)return e.arrayBuffer();if("undefined"==typeof FileReader)throw un("Binary read capability is missing for current platform",{code:nn,stage:rn,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((t,r)=>{const s=new FileReader;s.onerror=()=>{r(un("Binary read failed",{code:an,stage:rn,retryable:!1}))},s.onload=()=>{s.result instanceof ArrayBuffer?t(s.result):r(un("Binary read returned invalid result",{code:an,stage:rn,retryable:!1}))},s.readAsArrayBuffer(e)})})(t);return Mc(new Uint8Array(r))}}),Dc=e=>{if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"errMsg"in e){const t=e.errMsg;if("string"==typeof t)return t}return String(e)},Pc=e=>{if(!(e=>"miniapp-path"===e.sourceType&&"string"==typeof e.path&&e.path.length>0)(e))throw un("Miniapp image processor only supports miniapp path source",{code:nn,stage:rn,retryable:!1,details:{sourceType:e.sourceType}});return e.path},xc=e=>{const t=e.getFileSystemManager?.();if(t)return t;throw un("Miniapp file system capability is missing",{code:nn,stage:rn,retryable:!1,details:{capability:"getFileSystemManager"}})},Fc=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},Bc=async(e,t)=>new Promise((r,s)=>{e.getImageInfo({src:t,success:e=>{r(e)},fail:e=>{s(e instanceof Error?e:new Error(Dc(e)))}})}).catch(e=>{throw un("Miniapp image info read failed",{code:an,stage:rn,retryable:!1,details:{src:t,cause:Dc(e)}})}),Gc=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,qc=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const r=await Bc(e,t);return Gc(t,r)},$c=async(e,t,r)=>{if("function"==typeof e.getFileInfo)try{const s=await new Promise((s,n)=>{const i=setTimeout(()=>n(new Error("File digest timed out")),r),o=e=>{clearTimeout(i),e()};try{e.getFileInfo?.({filePath:t,digestAlgorithm:"md5",success:e=>o(()=>s(e)),fail:e=>o(()=>n(new Error(Dc(e))))})}catch(a){o(()=>n(new Error(Dc(a))))}});return"string"==typeof s.digest&&/^[a-f\d]{32}$/i.test(s.digest)?s.digest.toLowerCase():void 0}catch(s){throw un("Miniapp file digest failed",{code:an,stage:rn,retryable:!1,details:{filePath:t,cause:Dc(s)}})}},jc=e=>({async getImageInfo(t){const r=Pc(t),s=await Bc(e,r),n=Fc(s.type)??t.mimeType;return{width:s.width,height:s.height,mimeType:n,fileSize:t.size,isGif:"image/gif"===n}},async generateBigImage(t,r){const s=Pc(t);if("function"!=typeof e.compressImage)throw un("Miniapp image compress capability is missing",{code:nn,stage:rn,retryable:!1,details:{capability:"compressImage"}});const n=await Bc(e,s),i=Gc(s,n),o=((e,t,r)=>{const s=Math.min(e,t);if(s<=r)return{width:e,height:t};const n=r/s;return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}})(n.width,n.height,r.maxShortEdge),a=await new Promise((t,s)=>{e.compressImage?.({src:i,quality:Math.max(0,Math.min(100,Math.round(100*r.quality))),compressedWidth:o.width,compressedHeight:o.height,success:e=>{e.tempFilePath?t(e.tempFilePath):s(new Error("compressImage missing tempFilePath"))},fail:e=>{s(e instanceof Error?e:new Error(Dc(e)))}})}).catch(e=>{throw un("Miniapp image compress failed",{code:an,stage:rn,retryable:!1,details:{src:i,cause:Dc(e)}})}),c=await qc(e,a),d=await Bc(e,c),u=Fc(d.type)??t.mimeType,l=await(async(e,t,r)=>{const s=xc(e);return s.getFileInfo?new Promise((e,r)=>{s.getFileInfo?.({filePath:t,success:t=>{e(t.size)},fail:e=>{r(e instanceof Error?e:new Error(Dc(e)))}})}).catch(e=>{throw un("Miniapp file info read failed",{code:an,stage:rn,retryable:!1,details:{filePath:t,cause:Dc(e)}})}):r})(e,c,t.size);return{source:{sourceType:"miniapp-path",path:c,name:t.name,mimeType:u,size:l},width:d.width,height:d.height,fileName:t.name,fileType:u,fileSize:l}},async computeMd5(t){const r=Pc(t),s=await qc(e,r),n=e.getFileSystemManager?.(),i=Date.now()+Qr;let o;for(const d of[n,e]){if(!d)continue;const e=i-Date.now();if(e<=0)break;try{const t=await $c(d,s,e);if(t)return t}catch(c){o=c instanceof Error?c:new Error(Dc(c))}}if(o&&"function"!=typeof n?.readFile)throw o;const a=await(async(e,t)=>{const r=xc(e);if("function"!=typeof r.readFile)throw un("Miniapp file read capability is missing",{code:nn,stage:rn,retryable:!1,details:{capability:"FileSystemManager.readFile"}});const s=await new Promise((e,s)=>{r.readFile?.({filePath:t,success:t=>{e(t.data)},fail:e=>{s(e instanceof Error?e:new Error(Dc(e)))}})}).catch(e=>{throw un("Miniapp file read failed",{code:an,stage:rn,retryable:!1,details:{filePath:t,cause:Dc(e)}})});return s instanceof ArrayBuffer?new Uint8Array(s):"function"==typeof TextEncoder?(new TextEncoder).encode(s):Uint8Array.from(Array.from(s).map(e=>255&e.charCodeAt(0)))})(e,s);return Mc(a)}}),Vc=new Set(["quotaexceedederror","ns_error_dom_quota_reached"]),Kc=[/\bquota\b/i,/\bexceed(?:ed)?\s+storage\s+max(?:imum)?\s+size\b/i,/\b(?:storage\s+)?max(?:imum)?\s+size\b.*\bexceed(?:ed)?\b/i,/\bstorage\b.*\blimit\b.*\b(?:exceed(?:ed)?|reach(?:ed)?)\b/i],zc=(e,t)=>{if("object"!=typeof e||null===e)return null;const r=e[t];return"string"==typeof r?r:null},Hc=e=>{if(!e)return!1;const t=zc(e,"name");if(t&&Vc.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,zc(e,"message"),zc(e,"errMsg")].some(e=>null!==e&&Kc.some(t=>t.test(e)))},Wc=e=>{if(e instanceof Error)return e;const t=zc(e,"message")??zc(e,"errMsg")??"Storage quota exceeded";return Object.assign(new Error(t),{name:"QuotaExceededError",cause:e})},Jc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Qc=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),Zc=e=>e===Qs.ALIPAY_MINIAPP||e===Qs.DINGTALK_MINIAPP,Yc=e=>{const t=e.replace(/\s/g,"").replace(/-/g,"+").replace(/_/g,"/"),r=t.endsWith("==")?2:t.endsWith("=")?1:0,s=Math.max(0,Math.floor(3*t.length/4)-r),n=new Uint8Array(s);let i=0;for(let o=0;o<t.length;o+=4){const e=Jc.indexOf(t[o]??""),r=Jc.indexOf(t[o+1]??""),a=t[o+2]??"=",c=t[o+3]??"=",d="="===a?0:Jc.indexOf(a),u="="===c?0:Jc.indexOf(c);if(e<0||r<0||d<0||u<0)return new ArrayBuffer(0);const l=e<<18|r<<12|d<<6|u;for(const t of[16,8,0])i<s&&(n[i]=l>>t&255,i+=1)}return n.buffer},Xc=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),ed=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},td=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(Xc(e)||ArrayBuffer.isView(e))return e;const r=e;return"data"in r&&r.data!==e?td(r.data,t+1):e},rd=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return ed(e);if(Xc(e))try{return ed(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return ed(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));if(Array.isArray(e))return e.every(e=>Number.isInteger(e)&&e>=0&&e<=255)?Uint8Array.from(e):void 0;if("object"!=typeof e)return;const r=e;if("data"in r&&r.data!==e){const e=rd(r.data,t+1);if(e)return e}if("buffer"in r&&r.buffer!==e){const e=rd(r.buffer,t+1);if(!e)return;const s="number"==typeof r.byteOffset&&Number.isInteger(r.byteOffset)?r.byteOffset:0,n="number"==typeof r.byteLength&&Number.isInteger(r.byteLength)?r.byteLength:e.byteLength-s;if(s<0||n<0||s+n>e.byteLength)return;return e.slice(s,s+n)}},sd=(e,t)=>{if("string"==typeof e)return e;const r=e instanceof Uint8Array?e:new Uint8Array(e);if(Zc(t)){const s=(e=>{let t="";for(let r=0;r<e.length;r+=3){const s=e[r]??0,n=e[r+1],i=e[r+2],o=s<<16|(n??0)<<8|(i??0);t+=Jc[o>>18&63],t+=Jc[o>>12&63],t+=void 0===n?"=":Jc[o>>6&63],t+=void 0===i?"=":Jc[63&o]}return t})(r);return Ks("Mini program socket frame encoded as Base64",{operation:"platform.socket.frame.encode-base64",hostPlatform:t,sourceType:e instanceof Uint8Array?"uint8array":"arraybuffer",sourceBytes:r.byteLength,encodedCharacters:s.length,sourcePrefixHex:Qc(r.subarray(0,8))}),s}const s=new ArrayBuffer(r.byteLength);return new Uint8Array(s).set(r),s},nd=(e,t)=>"string"!=typeof e&&Zc(t),id=(e,t)=>{const r=td(e.data);if("string"==typeof r){if(!Zc(t))return r;const s=Yc(r),n=new Uint8Array(s);return Ks("Mini program socket Base64 frame decoded",{operation:"platform.socket.frame.decode-base64",hostPlatform:t,sourceType:r===e.data?"string":"wrapped-string",sourceCharacters:r.length,decodedBytes:s.byteLength,decodedPrefixHex:Qc(n.subarray(0,8)),decodedSuffixHex:Qc(n.subarray(Math.max(0,n.length-8)))}),s}const s=rd(r);if(!s){const s="object"==typeof e.data&&null!==e.data?e.data:void 0;return void Ks("Mini program socket frame shape is unsupported",{operation:"platform.socket.frame.unsupported-shape",hostPlatform:t,sourceType:typeof r,sourceTag:Object.prototype.toString.call(e.data),sourceKeys:s?Object.keys(s).slice(0,10):[],isBuffer:e.isBuffer})}if(!Zc(t))return s.buffer;const n=(e=>{let t="";for(const s of e){if(9!==s&&10!==s&&13!==s&&32!==s&&!(s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||43===s||45===s||47===s||61===s||95===s))return;t+=String.fromCharCode(s)}const r=t.replace(/\s/g,"");if(0!==r.length&&r.length%4!=1&&/^[A-Za-z0-9+/_-]+={0,2}$/.test(r))return r})(s);if(!n)return Ks("Mini program socket binary frame preserved",{operation:"platform.socket.frame.preserve-binary",hostPlatform:t,sourceType:Object.prototype.toString.call(r),sourceBytes:s.byteLength,sourcePrefixHex:Qc(s.subarray(0,8))}),s.buffer;const i=Yc(n),o=new Uint8Array(i);return Ks("Mini program socket Base64 buffer decoded",{operation:"platform.socket.frame.decode-base64-buffer",hostPlatform:t,sourceType:Object.prototype.toString.call(r),sourceBytes:s.byteLength,decodedBytes:i.byteLength,decodedPrefixHex:Qc(o.subarray(0,8)),decodedSuffixHex:Qc(o.subarray(Math.max(0,o.length-8)))}),i},od=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ad=(e,t)=>("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e[t],cd=e=>e instanceof Error?e.message:od(e)&&"string"==typeof e.errMsg?e.errMsg:od(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),ud=e=>e?{...e}:{},ld=e=>"number"==typeof e&&Number.isInteger(e)&&e>=100&&e<=599,hd=e=>ld(e.statusCode)?e.statusCode:ld(e.status)?e.status:void 0,pd=e=>{if(!od(e))return{};const t={};return Object.entries(e).forEach(([e,r])=>{"string"==typeof r&&(t[e]=r)}),t},md=e=>({...pd(e.headers),...pd(e.header)}),gd=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const r=()=>{t()};return e.addEventListener("abort",r,{once:!0}),()=>{e.removeEventListener("abort",r)}},fd=e=>{try{e.close()}catch{}},yd=(e,t)=>new Promise((r,s)=>{let n=!1,i=()=>{};const o=(e,r,o)=>{n||(n=!0,i(),s(un(e,{code:on,stage:Ys,retryable:o,details:{url:t.url,method:"GET",cause:cd(r)}})))},a=e.downloadFile?.({url:t.url,header:ud(t.headers),timeout:t.timeoutMs??15e3,success:s=>{const a=s.tempFilePath??s.apFilePath;a?((e,t)=>new Promise((r,s)=>{const n=e.getFileSystemManager?.();n?n.readFile({filePath:t,success:e=>{const t=rd(e.data);t?r(t.buffer):s(new Error("downloaded file response is not binary"))},fail:s}):s(new Error("getFileSystemManager returned no file system manager"))}))(e,a).then(e=>{n||(n=!0,i(),Ks("Mini program binary response read from downloaded file",{operation:"platform.request.arraybuffer.download-file",url:t.url,filePathType:s.apFilePath?"apFilePath":"tempFilePath",status:s.statusCode??200,bytes:e.byteLength}),r({status:s.statusCode??200,headers:s.header??{},data:e}))}).catch(e=>{o("Mini program downloaded file read failed.",e,!1)}):o("Mini program download did not return a file path.",s,!1)},fail:e=>{o("Mini program file download failed.",e,!0)}});i=gd(t.signal,()=>{a?.abort(),o("Mini program file download aborted.","abort",!1)})}),vd=e=>({request:t=>"arraybuffer"!==t.responseType||void 0!==t.method&&"GET"!==t.method||!(e=>"function"==typeof e.downloadFile&&"function"==typeof e.getFileSystemManager)(e)?new Promise((r,s)=>{let n=()=>{};const i=e.request({url:t.url,method:t.method??"GET",header:ud(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{n();const i=hd(e);void 0!==i?r({status:i,headers:md(e),data:e.data}):s(un("Mini program request response status is invalid.",{code:on,stage:Ys,retryable:!1,details:{url:t.url,method:t.method??"GET",statusCode:e.statusCode,status:e.status}}))},fail:e=>{n(),s(un("Mini program request failed.",{code:on,stage:Ys,retryable:!0,details:{url:t.url,method:t.method??"GET",cause:cd(e)}}))}});n=gd(t.signal,()=>{i.abort(),s(un("Mini program request aborted.",{code:on,stage:Ys,retryable:!1,details:{url:t.url,method:t.method??"GET",reason:"abort"}}))})}):yd(e,t)}),Id=(e,t)=>({connect:r=>new Promise((s,n)=>{let i,o,a=!1;const c=()=>{void 0!==o&&(clearTimeout(o),o=void 0)},d=(e,t,s)=>{a||(a=!0,c(),i&&fd(i),n(un(t,{code:cn,stage:en,retryable:s,details:{url:r.url,cause:cd(e)}})))},u=e=>{if(!(ad(r=e,"send")&&ad(r,"close")&&ad(r,"onOpen")&&ad(r,"onMessage")&&ad(r,"onError")&&ad(r,"onClose")))return void d(new Error("returnedType="+typeof e),"Mini program connectSocket did not return a SocketTask.",!1);var r;const n=e;if(a)return void fd(n);i=n;const o=()=>{n.offOpen?.(u),n.offError?.(l)},u=()=>{a?fd(n):(a=!0,c(),o(),s(((e,t,r=ln)=>{const s=new Set,n=new Set,i=new Set,o=new Set;let a=r;return e.onOpen(()=>{a=hn,s.forEach(e=>{e()})}),e.onMessage(e=>{const r=id(e,t);void 0!==r&&n.forEach(e=>{e(r)})}),e.onError(e=>{i.forEach(t=>{t(e)})}),e.onClose(e=>{a=mn,o.forEach(t=>{t({code:e.code,reason:e.reason})})}),{get readyState(){return a},send(r){if(a!==hn)throw un("Mini program socket is not open.",{code:cn,stage:en,retryable:!0,details:{readyState:a}});return new Promise((s,n)=>{e.send({data:sd(r,t),...nd(r,t)?{isBuffer:!0}:{},success:s,fail:e=>{n(un("Mini program socket send failed.",{code:cn,stage:en,retryable:!0,details:{cause:cd(e)}}))}})})},close(t,r){a=pn,e.close({code:t,reason:r})},onOpen:e=>(s.add(e),()=>{s.delete(e)}),onMessage:e=>(n.add(e),()=>{n.delete(e)}),onError:e=>(i.add(e),()=>{i.delete(e)}),onClose:e=>(o.add(e),()=>{o.delete(e)})}})(n,t,hn)))},l=e=>{o(),d(e.errMsg??"socket error","Mini program socket connection failed before open.",!0)};n.onOpen(u),n.onError(l)};let l;"number"==typeof r.timeoutMs&&r.timeoutMs>0&&(o=setTimeout(()=>{d("timeout","Mini program socket connection timed out.",!0)},r.timeoutMs));try{l=e.connectSocket({url:r.url,...t===Qs.ALIPAY_MINIAPP?{multiple:!0}:{},protocols:Array.isArray(r.protocols)?[...r.protocols]:"string"==typeof r.protocols?[r.protocols]:void 0,fail:e=>{d(e,"Mini program socket connect failed.",!0)}})}catch(p){return void d(p,"Mini program socket creation failed.",!0)}var h;"object"!=typeof(h=l)||null===h||"function"!=typeof h.then?u(l):Promise.resolve(l).then(e=>u(e),e=>d(e,"Mini program socket connect failed.",!0))})}),bd=e=>({upload(t){const r=t.method??"POST";return"POST"!==r?Promise.reject(un("Mini program upload only supports POST.",{code:an,stage:Xs,retryable:!1,details:{url:t.url,method:r,reason:"unsupported-method"}})):new Promise((r,s)=>{const n=(e=>{if("miniapp-path"!==e.sourceType||!e.path)throw un("Mini program upload only supports miniapp-path source.",{code:an,stage:Xs,retryable:!1,details:{sourceType:e.sourceType}});return e})(t.source);let i=()=>{};const o=e.uploadFile({url:t.url,filePath:n.path,name:t.fileFieldName??"file",header:ud(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{i();const o=hd(e);void 0!==o?r({status:o,body:e.data}):s(un("Mini program upload response status is invalid.",{code:an,stage:Xs,retryable:!1,details:{url:t.url,path:n.path,statusCode:e.statusCode,status:e.status}}))},fail:e=>{i(),s(un("Mini program upload failed.",{code:an,stage:Xs,retryable:!0,details:{url:t.url,path:n.path,cause:cd(e)}}))}});o.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),i=gd(t.signal,()=>{o.abort(),s(un("Mini program upload aborted.",{code:an,stage:Xs,retryable:!1,details:{url:t.url,path:n.path,reason:"abort"}}))})})}}),_d=(e,t)=>{const r=(e=>e===Qs.ALIPAY_MINIAPP||e===Qs.DINGTALK_MINIAPP)(t);return{async getItem(t){if(ad(e,"getStorageSync"))try{const s=(e=>od(e)&&"data"in e?e.data:e)(e.getStorageSync(r?{key:t}:t));return"string"==typeof s&&s.length>0?s:null}catch{return null}return ad(e,"getStorage")?new Promise(r=>{e.getStorage({key:t,success:e=>{r("string"==typeof e.data&&e.data.length>0?e.data:null)},fail:()=>{r(null)}})}):null},async setItem(t,s){if(ad(e,"setStorageSync"))try{r?e.setStorageSync({key:t,data:s}):e.setStorageSync(t,s)}catch(n){if(Hc(n))throw Wc(n)}else if(ad(e,"setStorage"))return new Promise((r,i)=>{try{e.setStorage({key:t,data:s,success:r,fail:e=>{Hc(e)?i(Wc(e)):r()}})}catch(n){if(Hc(n))return void i(Wc(n));r()}})},async removeItem(t){if(ad(e,"removeStorageSync"))try{e.removeStorageSync(r?{key:t}:t)}catch{}else if(ad(e,"removeStorage"))return new Promise(r=>{try{e.removeStorage({key:t,success:r,fail:()=>{r()}})}catch{r()}})}}},Td=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>ad(e,"getNetworkType")?new Promise(t=>{e.getNetworkType?.({success:e=>{t(e.networkType??"unknown")},fail:()=>{t("unknown")}})}):Promise.resolve("unknown"),onNetworkChange(t){const r=e=>{t(e.isConnected)};return ad(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(r),ad(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{ad(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(r)}},onAppVisibilityChange(t){const r=()=>{t(!0)},s=()=>{t(!1)};return ad(e,"onAppShow")&&e.onAppShow(r),ad(e,"onAppHide")&&e.onAppHide(s),t(!0),()=>{ad(e,"offAppShow")&&e.offAppShow(r),ad(e,"offAppHide")&&e.offAppHide(s)}}}),Cd=(e,t=Qs.WECHAT_MINIAPP,r=t)=>{const s=(e=>{if(ad(e,"request")&&ad(e,"connectSocket")&&ad(e,"uploadFile"))return e;throw un("Mini program platform capability is missing.",{code:nn,stage:Zs,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(e),n="function"==typeof s.getImageInfo?jc(s):void 0;return{request:vd(s),socket:Id(s,r),upload:bd(s),runtime:Td(s,t),storage:_d(s,r),imageProcessor:n}},Sd=["request","upload","socket"],Ed={request:"request",upload:"upload",socket:"connect"},wd=[Qs.WEB,Qs.ELECTRON_RENDERER,Qs.REACT_NATIVE],Ad=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Rd=e=>wd.includes(e),Nd=(e,t)=>e!==Qs.UNIAPP?Rd(e):!Rn(t)&&!Md(t)&&Sn(t),Od=e=>Ad(e,"getImageInfo")&&(Ad(e,"getFileSystemManager")||Ad(e,"getFileInfo")),Md=e=>!Rn(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;return"string"==typeof r?r:void 0}catch{return}})(e),Ud=(e,t)=>{if(Rd(e)&&e!==Qs.REACT_NATIVE)return kc();if(Un(e)&&Od(t))return jc(t);if(e===Qs.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(Sn(e))return kc();if(Od(e.uni))return jc(e.uni);if(Od(e.wx))return jc(e.wx)}},Ld=e=>{const t=e.localStorage;if(t)return{getItem:e=>Promise.resolve(t.getItem(e)),setItem:(e,r)=>(t.setItem(e,r),Promise.resolve()),removeItem:e=>(t.removeItem(e),Promise.resolve())};const r=new Map;return{getItem(e){const t=r.has(e)?r.get(e)??null:null;return Promise.resolve(t)},setItem:(e,t)=>(r.set(e,t),Promise.resolve()),removeItem:e=>(r.delete(e),Promise.resolve())}},kd=(e,t,r,s)=>{if(e===Qs.UNIAPP&&Md(r)&&void 0!==r.uni&&In(r.uni))return{...Cd(r.uni,e,t),proto:nc()};if(((e,t)=>!Nd(e,t)&&Un(e))(e,r)&&In(s))return{...Cd(s,e,t),proto:nc()};const n=r.XMLHttpRequest,i=Nd(e,r),o=i?ac({fetchImpl:r.fetch}):void 0,a=i?mc({webSocketCtor:r.WebSocket}):void 0,c=e===Qs.REACT_NATIVE?_c({fetchImpl:r.fetch,formDataCtor:r.FormData}):i?Ic({xhrFactory:"function"==typeof n?()=>new n:void 0,fetchImpl:r.fetch}):void 0,d=i&&e!==Qs.REACT_NATIVE?(u={platform:e,windowRef:r.window,documentRef:r.document,navigatorRef:r.navigator},{getPlatform:()=>u.platform,getNetworkType:()=>!1===u.navigatorRef?.onLine?Promise.resolve("none"):Promise.resolve(u.navigatorRef?.connection?.type??u.navigatorRef?.connection?.effectiveType??"unknown"),onNetworkChange(e){const t=u.windowRef;if(!t)return()=>{};const r=()=>{e(!0)},s=()=>{e(!1)};return t.addEventListener("online",r),t.addEventListener("offline",s),"boolean"==typeof u.navigatorRef?.onLine&&e(u.navigatorRef.onLine),()=>{t.removeEventListener("online",r),t.removeEventListener("offline",s)}},onAppVisibilityChange(e){const t=u.documentRef;if(!t)return()=>{};const r=()=>{e((e=>"hidden"!==e?.visibilityState)(t))};return t.addEventListener("visibilitychange",r),r(),()=>{t.removeEventListener("visibilitychange",r)}}}):(e=>({getPlatform:()=>e,onNetworkChange:e=>()=>{},onAppVisibilityChange:e=>()=>{}}))(e);var u;return{request:o,upload:c,socket:a,runtime:d,proto:nc(),storage:Ld(r),imageProcessor:i&&e!==Qs.REACT_NATIVE?kc():Ud(e,s)}},Dd=(e,t,r)=>{if(!t)return{...e,...r};const s=Sd.filter(e=>void 0!==r[e]);if(s.length>0)throw un("Transport adapter conflicts with network overrides.",{code:sn,stage:Zs,retryable:!1,details:{conflictingCapabilities:s}});const n=(e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)))(r);return{...e,request:t.request,upload:t.upload,socket:t.socket,...n}},Pd=(e,t)=>{if(void 0!==e)return e;throw un("Platform adapter initialization failed.",{code:sn,stage:Zs,retryable:!1,details:{capability:t}})},xd=e=>{(e=>{if(!e)return;const t=Sd.flatMap(t=>{const r=Ed[t];return Ad(e[t],r)?[]:[`${t}.${r}`]});if(0!==t.length)throw un("Transport adapter has invalid capabilities.",{code:sn,stage:Zs,retryable:!1,details:{source:"transportAdapter",invalidCapabilities:t}})})(e?.transportAdapter);const t=fn(e?.runtimeInput),r=Mn(t,e?.prefer),s=r.platform,n=kd(s,r.hostPlatform,t,r.global),i=((e,t)=>e?"function"==typeof e?e(t):e:{})(e?.overrides,n),o=Dd(n,e?.transportAdapter,i),a=(e=>({request:void 0!==e.request,upload:void 0!==e.upload,socket:void 0!==e.socket,runtime:void 0!==e.runtime,proto:void 0!==e.proto,storage:void 0!==e.storage,imageProcessor:void 0!==e.imageProcessor}))(o);kn(a);return{platform:s,platformId:s,capability:a,request:Pd(o.request,"request"),upload:Pd(o.upload,"upload"),socket:Pd(o.socket,"socket"),runtime:Pd(o.runtime,"runtime"),proto:Pd(o.proto,"proto"),storage:Pd(o.storage,"storage"),imageProcessor:o.imageProcessor}},Fd=e=>{if(e instanceof bt)return e;if((e=>"object"==typeof e&&null!==e)(e)){const t=e.details;if(e.code===nn){const r=t?.capability;if(e.stage===rn&&"string"==typeof r&&r.includes("FileSystem")){const r=e instanceof Error?e.message:"Upload failed";return new bt(r,{code:ot.UPLOAD_REQUEST_FAILED,details:t})}return new bt("Upload capability is missing for current platform",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:t})}if(e.stage===Xs)return(e=>{const t=e?.reason;return!("string"!=typeof t||!t.toLowerCase().includes("abort"))})(t)?new bt("Upload canceled",{code:ot.UPLOAD_ABORTED,details:t}):(e=>{const t=e?.reason;return!("string"!=typeof t||!t.toLowerCase().includes("timeout"))})(t)?new bt("Upload timeout",{code:ot.UPLOAD_TIMEOUT,details:t}):new bt("Upload failed",{code:ot.UPLOAD_REQUEST_FAILED,details:t})}const t=e instanceof Error?e.message:"Upload failed";return new bt(t,{code:ot.UPLOAD_REQUEST_FAILED,details:{cause:e}})},Bd=e=>{if(e)return e;const t=fn(),r=mc({webSocketCtor:t.WebSocket});if(r)return r;throw un("Socket capability is missing for current platform.",{code:nn,stage:en,retryable:!1,details:{capability:"socket"}})},Gd={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class qd{constructor(e={}){this.attemptCount=0,this.config={...Gd,...e}}getRetryDelay(){const e=Math.max(this.attemptCount-1,0),t=this.config.initialDelay*Math.pow(this.config.backoffMultiplier,e),r=Math.min(t,this.config.maxDelay);return r/2+r/2*Math.min(1,Math.max(0,this.config.randomSource()))}recordAttempt(){this.attemptCount++}reset(){this.attemptCount=0}shouldRetry(){return this.attemptCount<this.config.maxAttempts}getAttemptCount(){return this.attemptCount}async waitForRetry(){const e=this.getRetryDelay();return Vs(`Waiting ${e}ms before retry (attempt ${this.attemptCount})`),new Promise(t=>setTimeout(t,e))}}const $d={interval:3e4,timeout:6e4},Vd="function"==typeof TextDecoder?new TextDecoder:null;class Kd{constructor(e={}){this.websocket=null,this.heartbeatTimer=null,this.timeoutTimer=null,this.lastPongTime=0,this.onTimeoutCallback=null,this.sendPing=null,this.probeResolvers=[],this.messageDisposer=null,this.handlePong=e=>{const t=this.extractMessageText(e);if(!t)return;const r=this.parseJson(t);if(!Kd.isRecord(r))return;"pong"===Kd.readString(r.type)&&(this.markAlive(),Vs("Pong received"))},this.config={...$d,...e}}start(e,t,r){this.heartbeatTimer&&this.stop(),this.attachWebSocket(e),this.onTimeoutCallback=t||null,this.sendPing=r??null,this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{this.sendPingInternal()},this.config.interval),Vs("Heartbeat started",{interval:this.config.interval})}stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.timeoutTimer&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null),this.messageDisposer?.(),this.messageDisposer=null,this.websocket=null,this.sendPing=null,this.resolveProbe(!1),Vs("Heartbeat stopped")}sendPingInternal(){if(this.websocket&&this.websocket.readyState===hn)try{if(this.sendPing)this.sendPing();else{const e=JSON.stringify({type:"ping",timestamp:Date.now()});Promise.resolve(this.websocket.send(e)).catch(e=>{zs("Failed to send ping:",e),this.resolveProbe(!1)})}this.resetTimeout(),Vs("Ping sent")}catch(e){zs("Failed to send ping:",e),this.resolveProbe(!1)}else this.resolveProbe(!1)}extractMessageText(e){if("string"==typeof e)return e;if(e instanceof ArrayBuffer){const t=new Uint8Array(e);return(e=>{for(const t of e)if(32!==t&&9!==t&&10!==t&&13!==t)return 123===t;return!1})(t)?Vd?.decode(t)??Ws(t):null}return null}parseJson(e){try{return JSON.parse(e)}catch{return null}}static isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}static readString(e){return"string"==typeof e?e:void 0}resetTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=setTimeout(()=>{Ks("Heartbeat timeout"),this.onTimeoutCallback&&this.onTimeoutCallback()},this.config.timeout)}markAlive(){this.lastPongTime=Date.now(),this.resetTimeout(),this.resolveProbe(!0)}getLastPongTime(){return this.lastPongTime}async probeOnce(e,t){try{if(e.readyState!==hn)return!1;this.attachWebSocket(e);const r=t??this.config.timeout;return await new Promise(e=>{const t=setTimeout(()=>{this.removeProbeResolver(e),e(!1)},r);this.probeResolvers.push(r=>{clearTimeout(t),e(r)}),this.sendPingInternal()})}catch(r){return Ks("Heartbeat probe failed",r),!1}}attachWebSocket(e){this.websocket!==e&&(this.messageDisposer?.(),this.websocket=e,this.messageDisposer=e.onMessage(e=>{this.handlePong(e)}))}resolveProbe(e){if(0===this.probeResolvers.length)return;const t=[...this.probeResolvers];this.probeResolvers=[];for(const r of t)r(e)}removeProbeResolver(e){this.probeResolvers=this.probeResolvers.filter(t=>t!==e)}}const zd=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 s=[];for(const n of r)n&&"object"==typeof n&&"code"in n&&"text"in n&&"string"==typeof n.code&&n.code.trim()&&"string"==typeof n.text&&s.push([n.code,n.text]);return s.length>0?Object.fromEntries(s):void 0};let Hd=null;function Wd(){return Hd||(Hd=sc()),Hd}const Jd="websdk2:device-info",Qd="webim",Zd="web",Yd=e=>{const t=Date.now(),r=e.deviceId,s=e.customOSPlatform,n=void 0!==s?e.customDeviceName:void 0,i=fn().localStorage,o=()=>{if(!i)return null;try{const t=i.getItem(Jd);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},a=e=>{if(i)try{i.setItem(Jd,JSON.stringify(e))}catch{}},c=e=>void 0===s?e:{deviceId:`custom${s}_${e.deviceUuid}`,deviceName:n??r,deviceUuid:e.deviceUuid};if(e.useFixedDeviceId){const e=o();if(e)return c(e);if(r===Qd){const e=`${Zd}_${t}`,s=c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e});return a(s),s}if(void 0!==s){const e=c({deviceId:`webim_${Zd}_${r}`,deviceName:r,deviceUuid:`${Zd}_${t}`});return a(e),e}const n={deviceId:`webim_${Zd}_${r}`,deviceName:`webim_${Zd}_${r}`,deviceUuid:`webim_${Zd}_${r}`};return a(n),n}if(r===Qd){const e=`random_${Zd}_${t}`;return c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e})}if(void 0!==s){return c({deviceId:`webim_${Zd}_${r}`,deviceName:r,deviceUuid:`random_${Zd}_${t}`})}return{deviceId:`webim_${Zd}_${r}`,deviceName:`webim_${Zd}_${r}`,deviceUuid:`webim_${Zd}_${r}`}},Xd=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),eu=e=>{if(/^\d+$/.test(e))return e;const t=Pn.fromString("1099511628211",!0);let r=Pn.fromString("1469598103934665603",!0);for(let s=0;s<e.length;s+=1)r=r.xor(Pn.fromInt(e.charCodeAt(s),!0)).multiply(t).toUnsigned();return r.isZero()?"1":r.toString()},tu=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 Pn(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},ru=e=>{const t=[];for(const[r,s]of Object.entries(e))if(void 0!==s)if("boolean"!=typeof s)if("number"!=typeof s)if("string"!=typeof s)try{t.push({key:r,type:kr,stringValue:JSON.stringify(s)})}catch{t.push({key:r,type:Lr,stringValue:Object.prototype.toString.call(s)})}else t.push({key:r,type:Lr,stringValue:s});else Number.isInteger(s)?t.push({key:r,type:Rr,varintValue:s}):t.push({key:r,type:Ur,doubleValue:s});else t.push({key:r,type:Ar,varintValue:s?1:0});return t},su=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 s="number"==typeof r.type?r.type:Lr;if(s!==Ar)if(s!==Rr&&s!==Nr&&s!==Or)if(s!==Mr)if(s!==Ur){if(s!==kr)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},nu=new Set(["text","image","file","voice","video","location","custom"]),iu={txt:"text",text:"text",img:"image",image:"image",audio:"voice",voice:"voice",loc:"location",location:"location",video:"video",file:"file",custom:"custom",cmd:"cmd",combine:"combine"},ou=new WeakMap,au=e=>nu.has(e),cu=(e,t)=>`${e}:${t}`,du=e=>{const t="string"==typeof e.type?e.type:"";if("combine"===t)return!0;if("txt"!==t&&"text"!==t)return!1;if(0===e.subType)return!0;const r=e=>"string"==typeof e&&e.length>0;return r(e.remotePath)||r(e.title)||r(e.summary)||"number"==typeof e.combineLevel&&e.combineLevel>0},uu=(e,t)=>({...t,type:e}),lu=(e,t)=>(Ks("Multi-segment message keeps the first body only",{operation:"message.multi_body.keep_first",segmentCount:e.length,reason:t}),e.slice(0,1)),hu=e=>{if(0===e.length)return null;const t=e[0];if(1===e.length)return t??null;const r=[];for(const s of e){if(!s||!au(s.type))return lu(e,"a segment is missing or is not allowed in a multi_body message"),t??null;r.push(uu(s.type,s.body))}return{type:"multi_body",body:r}},pu=(e,t)=>hu(e.map(e=>{return"object"!=typeof(r=e)||null===r||Array.isArray(r)?null:t(e);var r})),mu=e=>"image"===e||"voice"===e||"video"===e||"file"===e,gu=(e,t)=>{if(!(e instanceof ut))return;const r={...e.details??{},msgLocalId:t};delete r.bodyIndex,e.details=r},fu=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),yu=e=>{const t=Array.isArray(e.contents)?e.contents[0]:void 0;return fu(t)?t:void 0};class vu{constructor(e,t=!1){this.userId=e,this.useCustomAttachmentUpload=t}decodeMetadata(e,t,r,s){const n=this.resolveMessageMetaPayload(e.meta,s),i={},o={modifiedInfo:this.resolveModifiedInfo(n),reactions:this.resolveReactions(n),isContentReplaced:this.resolveContentReplaced(n),chatThread:this.resolveChatThreadMessageContext(n),chatThreadOverview:this.resolveChatThreadOverview(n),isPeerRead:this.resolvePeerRead(n,t,r),groupReadCount:this.resolveGroupReadCount(n,t),stream:this.decodeStreamMeta(e.stream,yu(e))};for(const[a,c]of Object.entries(o))void 0!==c&&Object.assign(i,{[a]:c});return o.chatThread&&(i.isChatThread=!0),fu(e.msgConfig)&&e.msgConfig.allowGroupAck&&(i.needReadReceipt=!0),i}decodeContent(e,t){const r="number"==typeof e.type?e.type:Dt,s="string"==typeof e.remotePath&&e.remotePath.length>0||"string"==typeof e.title&&e.title.length>0||"string"==typeof e.summary&&e.summary.length>0||"number"==typeof e.combineLevel&&e.combineLevel>0,n=Object.prototype.hasOwnProperty.call(e,"subType")&&0===e.subType;if(r===jt||r===Dt&&(n||s)){return{type:"combine",body:{title:"string"==typeof e.title?e.title:"",summary:"string"==typeof e.summary?e.summary:"",filename:"string"==typeof e.displayName?e.displayName:"combine",filetype:"application/octet-stream",url:"string"==typeof e.remotePath?e.remotePath:void 0,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,combineLevel:"number"==typeof e.combineLevel?e.combineLevel:0}}}if(r===Dt){const r=zd(t);return{type:"text",body:{content:"string"==typeof e.text?e.text:"",...r?{translations:r}:{}}}}if(r===qt)return{type:"cmd",body:{action:"string"==typeof e.action?e.action:""}};if(r===$t){const t=su(e.customExts);return{type:"custom",body:{event:"string"==typeof e.customEvent?e.customEvent:"",params:t}}}if(r===Ft)return{type:"location",body:{latitude:"number"==typeof e.latitude?e.latitude:0,longitude:"number"==typeof e.longitude?e.longitude:0,address:"string"==typeof e.address?e.address:void 0,buildingName:"string"==typeof e.buildingName?e.buildingName:void 0}};if(r===Pt){const t=e.size??{},r="number"==typeof t.width?t.width:0,s="number"==typeof t.height?t.height:0,n=Es(e.imageType)===ps,i="string"==typeof e.remotePath?e.remotePath:"",o=Cs(i,{deriveVariants:!this.useCustomAttachmentUpload}),a="string"==typeof e.thumbnailRemotePath&&e.thumbnailRemotePath.length>0?e.thumbnailRemotePath:void 0;return{type:"image",body:{localUrl:"",filename:"string"==typeof e.displayName?e.displayName:"image",filetype:"application/octet-stream",width:r,height:s,isGif:1===e.subType,isOriginalImage:n,originalImageUrl:o.originalImageUrl,bigImageUrl:o.bigImageUrl,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:a??o.thumbnailUrl}}}if(r===xt){const t=e.size??{},r="number"==typeof t.width?t.width:void 0,s="number"==typeof t.height?t.height:void 0,n="string"==typeof e.thumbnailRemotePath?e.thumbnailRemotePath:void 0;return{type:"video",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"video",filetype:"application/octet-stream",duration:"number"==typeof e.duration?e.duration:0,width:r,height:s,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0,thumbnailUrl:n}}}if(r===Bt){return{type:"voice",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"voice",filetype:"application/octet-stream",duration:"number"==typeof e.duration?e.duration:0,secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0}}}if(r===Gt){return{type:"file",body:{url:"string"==typeof e.remotePath?e.remotePath:"",filename:"string"==typeof e.displayName?e.displayName:"file",filetype:"application/octet-stream",secret:"string"==typeof e.secretKey?e.secretKey:void 0,fileLength:"number"==typeof e.fileLength?e.fileLength:void 0}}}return null}decodeStreamMeta(e,t){if(!e||"object"!=typeof e)return;const r=e,s=Number(tu(r.streamSeq));if(!Number.isFinite(s))return;const n="number"==typeof r.streamStatus?r.streamStatus:zt,i="number"==typeof r.streamError?r.streamError:0,o="number"==typeof r.streamFinishReason?r.streamFinishReason:void 0,a=this.resolveContentText(t),c=a;return{customType:"string"==typeof r.streamType?r.streamType:void 0,seq:s,status:this.mapStreamStatus(n,i),errorType:i,finishReason:o,deltaText:a,fullText:c}}mapStreamStatus(e,t){return t>0?nt.ERROR:e===Vt?nt.START:e===Kt?nt.START_COMPLETED:e===Ht?nt.COMPLETED:e===Wt?nt.FULL:nt.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),s=this.parseMetaPayload(t);return r&&s?{...s,...r}:r??s??e??t}resolvePeerRead(e,t,r){if("singleChat"!==t||"SEND"!==r)return;const s=this.parseMetaPayload(e);return"boolean"==typeof s?.isRead?s.isRead:void 0}resolveGroupReadCount(e,t){if("groupChat"!==t)return;const r=this.parseMetaPayload(e),s=r?.group_read_ack;return"number"==typeof s&&Number.isInteger(s)&&s>=0?s:void 0}resolveModifiedInfo(e){const t=this.parseMetaPayload(e),r=t?.edit_msg;if(!fu(r))return;const s="string"==typeof r.operator?r.operator:"",n=this.toFiniteNumber(r.count),i=this.toFiniteNumber(r.edit_time);return s&&void 0!==n&&void 0!==i?{operatorId:s,operationCount:n,operationTime:i}:void 0}resolveChatThreadMessageContext(e){const t=this.parseMetaPayload(e),r=t?.thread;if(!fu(r)||0===Object.keys(r).length)return;const s=this.readString(r.msg_parent_id??r.messageId),n=this.readString(r.muc_parent_id??r.parentId);if(!s||!n)return;const i=this.readString(r.thread_name??r.chatThreadName);return{messageId:s,parentId:n,...i?{chatThreadName:i}:{}}}resolveChatThreadOverview(e){const t=this.parseMetaPayload(e),r=t?.thread_overview??t?.threadOverview;if(!fu(r)||0===Object.keys(r).length)return;const s=this.readString(r.id??r.thread_id??r.chatThreadId),n=this.readString(r.muc_parent_id??r.parentId);if(!s||!n)return;const i=this.readString(r.name),o=this.resolveChatThreadOverviewLastMessage(r.last_message??r.lastMessage,s);return{chatThreadId:s,parentId:n,...i?{name:i}:{},...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(!fu(e)||0===Object.keys(e).length)return null;const r=this.readString(e.msgId??e.msg_id??e.id);if(!r)return null;const s=this.toFiniteNumber(e.timestamp)??0,n=this.resolveThreadLastMessagePayload(e),i=this.readString(n?.from)??this.readString(e.from)??"",o=this.readString(n?.to)??this.readString(e.to)??t,a=Array.isArray(n?.bodies)?n.bodies:[],c=a.length>=2?this.composeThreadBodies(a):null;if(a.length>=2&&!c)return null;const d=fu(a[0])?a[0]:null,u=this.readString(d?.type)??this.readString(e.type),l=c?.type??this.mapThreadMessageType(u),h=c?.body??this.normalizeThreadLastMessageBody(l,d,e),p=t,m=i===this.userId?"SEND":"RECEIVE";return{msgServerId:r,msgLocalId:"",from:i,to:o,sender:{userId:i},conversationId:p,conversationType:"groupChat",type:l,sendStatus:"sent",ext:fu(n?.ext)?n.ext:{},timestamp:s,body:h,direct:m}}resolveThreadLastMessagePayload(e){const t=e.payload;if(fu(t))return t;if("string"==typeof t){const e=this.parseMetaPayload(t);if(e)return e}return null}composeThreadBodies(e){return hu(e.map(e=>{if(!fu(e))return null;if(du(e))return{type:"combine",body:this.normalizeThreadLastMessageBody("combine",e,e)};const t=(e=>e?iu[e]??null:null)(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(e,t,r){if(!t){return{content:this.readString(r.msg??r.content??r.text)??""}}switch(e){case"text":default:return{content:this.readString(t.msg??t.content??t.text)??""};case"image":{const e=this.readString(t.url)??"",r=Cs(e,{deriveVariants:!this.useCustomAttachmentUpload});return{localUrl:"",filename:this.readString(t.filename)??"image",filetype:this.readString(t.filetype)??"application/octet-stream",width:this.toFiniteNumber(t.width)??0,height:this.toFiniteNumber(t.height)??0,isGif:!0===t.isGif,isOriginalImage:!1,originalImageUrl:r.originalImageUrl,bigImageUrl:r.bigImageUrl,thumbnailUrl:this.readString(t.thumb)??r.thumbnailUrl,secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)}}case"voice":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"voice",filetype:this.readString(t.filetype)??"application/octet-stream",duration:this.toFiniteNumber(t.duration??t.length)??0,secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"video":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"video",filetype:this.readString(t.filetype)??"application/octet-stream",duration:this.toFiniteNumber(t.duration??t.length)??0,width:this.toFiniteNumber(t.width),height:this.toFiniteNumber(t.height),thumbnailUrl:this.readString(t.thumb),secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"file":return{url:this.readString(t.url)??"",filename:this.readString(t.filename)??"file",filetype:this.readString(t.filetype)??"application/octet-stream",secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength)};case"location":return{latitude:this.toFiniteNumber(t.lat??t.latitude)??0,longitude:this.toFiniteNumber(t.lng??t.longitude)??0,address:this.readString(t.addr??t.address),buildingName:this.readString(t.buildingName)};case"cmd":return{action:this.readString(t.action)??""};case"custom":return{event:this.readString(t.event??t.customEvent)??"",params:fu(t.params??t.customExts)?t.params??t.customExts:{}};case"combine":return{title:this.readString(t.title)??"",summary:this.readString(t.summary)??"",filename:this.readString(t.filename)??"combine",filetype:"application/octet-stream",url:this.readString(t.url),secret:this.readString(t.secret),fileLength:this.toFiniteNumber(t.file_length??t.fileLength),combineLevel:this.toFiniteNumber(t.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(Ws(t));return fu(e)?e:null}catch{return null}}if(fu(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return fu(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(fu).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}}const Iu=(e,t)=>{for(const r of[e,t])if(r&&"object"==typeof r&&"name"in r&&"string"==typeof r.name&&r.name.length>0)return r.name;return""},bu=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,_u="X-Request-Id",Tu=new Set(["mute"]),Cu={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext",mute:"muteAllMembers"},Su=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Eu=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},wu=(e,t)=>{const r=e?.map(e=>Su(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},Au=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=Eu(t);if(!s)return;const n=s.muteExpire??s.mute_expire??s.expire??s.expired??s.expireAt??s.expiredAt,i=Number(n);return Number.isFinite(i)&&i>0?i:void 0},Ru=e=>{const t=Eu(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=Cu[s];if(!e)continue;let t=n;if(Tu.has(s))t=!0===n||"true"===n;else if("max_users"===s){const e=Number(n);t=Number.isFinite(e)?e:void 0}void 0!==t&&(r[e]=t)}return Object.keys(r).length>0?r:void 0},Nu=e=>{const t=Eu(e);if(!t)return{attributes:{},keyList:[]};const r=t.result&&"object"==typeof t.result&&!Array.isArray(t.result)?t.result:{},s=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},n=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[];return{attributes:Object.fromEntries(n.map(e=>[e,s[e]]).filter(e=>"string"==typeof e[1])),keyList:n,from:Su(t.operator)??Su(t.username)}},Ou=(e,t)=>({eventName:e,payload:t}),Mu=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},r=Su(e.from?.name),s=(n=e.to,Su(n?.[0]?.name));var n;switch(e.operation){case 1:return Ou(qe,t);case 10:return Ou(Ve,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:s??r});case 17:return Ou($e,{...t,memberIds:wu(e.members,r),ext:e.ext??e.eventExt});case 18:return Ou(je,{...t,memberIds:wu(e.members,r)});case 20:return Ou(Ye,{...t,oldOwnerId:r,newOwnerId:s});case 21:return Ou(Qe,{...t,adminId:s??r});case 22:return Ou(Ze,{...t,adminId:s??r});case 23:{const r=(e=>{const t=Eu(e),r=t?.user_mute_time;if(!r||"object"!=typeof r||Array.isArray(r))return null;const s={};for(const[n,i]of Object.entries(r)){const e=Number(i);n&&Number.isFinite(e)&&(s[n]=e)}return Object.keys(s).length>0?s:null})(e.ext??e.eventExt),n=r?Object.keys(r):wu(e.members,s),i=46388736e5;return Ou(Ke,{...t,userIds:n,muteMembers:r??Object.fromEntries(n.map(e=>[e,i])),muteExpire:Au(e.reason,e.eventExt)??i})}case 24:return Ou(ze,{...t,userIds:wu(e.members,s)});case 25:return Ou(Xe,{...t,announcement:e.reason??""});case 26:return Ou(Xe,{...t,announcement:""});case 29:return Ou(He,{...t,userIds:wu(e.members,s)});case 30:return Ou(We,{...t,userIds:wu(e.members,s)});case 31:return Ou(Je,{...t,isMuted:!0});case 32:return Ou(Je,{...t,isMuted:!1});case 14:return Ou(et,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:Ru(e.eventExt)});case 43:{const s=Nu(e.eventExt);return Ou(rt,{...t,attributes:s.attributes,from:s.from??r})}case 44:{const s=Nu(e.eventExt);return Ou(st,{...t,keyList:s.keyList,from:s.from??r})}default:return null}},Uu=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Lu=(e,t)=>{if(!e)return t;try{return JSON.parse(e)}catch{return t}},ku=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Du=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Pu=e=>({userId:e}),xu=(e,t,r)=>{const s={userId:r};for(const n of ku){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},Fu=async(e,t)=>{const r=(e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,Du(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,t)}for(const o of r)s.has(o)||s.set(o,Pu(o));return s},Bu=e=>Uu(e)?e:null,Gu=e=>{if("string"==typeof e)return e},qu=e=>{const t=Gu(e)?.trim();return t||void 0},$u=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isFinite(t)?t:void 0}},ju=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},Vu=e=>{const t=Bu(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},Ku=e=>{const t=Bu(e);return t?Bu(t.data)?t.data:t:null},zu=(e,t)=>{const r=Bu(e),s=r&&Bu(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return $u(n[0])},Hu=(e,t)=>{const r=(e=>{const t=Bu(e);return t?$u(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},Wu=e=>qu(e.groupId)??qu(e.groupid)??qu(e.id)??"",Ju=e=>Gu(e.name)??Gu(e.groupname)??Gu(e.groupName)??"",Qu=e=>{const t=Vu(e),r=Bu(t[0])??Ku(e)??{},s=(e=>{const t=Bu(e);if(!t)return null;const r=Wu(t);return r?{groupId:r,name:Ju(t),description:Gu(t.description),memberCount:$u(t.memberCount)??$u(t.affiliations_count),public:ju(t.public),joinApprovalRequired:ju(t.joinApprovalRequired)??ju(t.approval)??ju(t.membersonly)??ju(t.members_only),allowInvites:ju(t.allowInvites)??ju(t.allowinvites)??ju(t.allow_user_invites),maxMembers:$u(t.maxMembers)??$u(t.maxusers),role:qu(t.role)??qu(t.permission),disabled:ju(t.disabled)}:null})(r)??{groupId:Wu(r),name:Ju(r)},n=qu(r.owner)??qu(r.admin)??qu(r.member),i=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>Bu(e)).filter(e=>null!==e).map(e=>$u(e.joined_time)).find(e=>void 0!==e);return{...s,owner:n?Pu(n):void 0,inviteNeedConfirm:ju(r.inviteNeedConfirm)??ju(r.invite_need_confirm),muteAllMembers:ju(r.mute),ext:Gu(r.ext)??Gu(r.custom),createdAt:$u(r.createdAt)??$u(r.created),joinedAt:i,avatarUrl:Gu(r.avatar),messageBlocked:ju(r.messageBlocked)??ju(r.isMessageBlocked)??ju(r.shieldgroup)}},Zu=e=>Pu(e),Yu=e=>Vu(e).map(e=>qu(e)).filter(e=>Boolean(e)).map(e=>Zu(e)),Xu=e=>{const t=Bu(e);if(!t)return null;const r=qu(t.fileId)??qu(t.file_id);if(!r)return null;const s=Gu(t.fileName)??Gu(t.file_name)??r,n=qu(t.fileOwner)??qu(t.file_owner);return{fileId:r,fileName:s,fileOwner:n?Zu(n):void 0,fileSize:$u(t.fileSize)??$u(t.file_size),createdAt:$u(t.createdAt)??$u(t.created)}},el=new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),tl={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},rl=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},sl=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},nl=(e,t)=>{const r=e?.map(e=>rl(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},il=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=sl(t);if(!s)return;const n=s.muteExpire??s.mute_expire??s.expire??s.expired??s.expireAt??s.expiredAt,i=Number(n);return Number.isFinite(i)&&i>0?i:void 0},ol=e=>{const t=sl(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=tl[s];if(!e)continue;let t=n;if(el.has(s))t=!0===n||"true"===n;else if("max_users"===s){const e=Number(n);t=Number.isFinite(e)?e:void 0}void 0!==t&&(r[e]=t)}return Object.keys(r).length>0?r:void 0},al=(e,t)=>{const r=sl(t)??sl(e);return Xu(r??void 0)??void 0},cl=(e,t)=>{const r=sl(t)??sl(e);return rl(r?.fileId)??rl(r?.file_id)??rl(e)??""},dl=(e,t)=>({eventName:e,payload:t}),ul=e=>{const t={groupId:e.groupId,groupName:e.groupName},r=rl(e.from?.name),s=(n=e.to,rl(n?.[0]?.name));var n;switch(e.operation){case 4:return dl(X,{...t,applicantId:r,reason:e.reason});case 5:return dl(ee,{...t,accepterId:r});case 6:return dl(te,{...t,declinerId:r,applicantId:s,reason:e.reason});case 7:return dl(Y,{...t,inviterId:r,reason:e.reason});case 8:return dl(re,{...t,inviteeId:r,reason:e.reason});case 9:return dl(se,{...t,inviteeId:r,reason:e.reason});case 10:return dl(ne,t);case 1:return dl(ie,t);case 19:return dl(oe,{...t,inviterId:r,reason:e.reason});case 23:{const r=(e=>{const t=sl(e),r=t?.user_mute_time;if(!r||"object"!=typeof r||Array.isArray(r))return null;const s={};for(const[n,i]of Object.entries(r)){const e=rl(n),t=Number(i);e&&Number.isFinite(t)&&t>0&&(s[e]=t)}return Object.keys(s).length>0?s:null})(e.ext),n=r?Object.keys(r):nl(e.members,s);return dl(ae,{...t,userIds:n,muteExpire:n.map(e=>r?.[e]).find(e=>void 0!==e)??il(e.reason,e.eventExt)})}case 24:return dl(ce,{...t,userIds:nl(e.members,s)});case 29:return dl(de,{...t,userIds:nl(e.members,s)});case 30:return dl(ue,{...t,userIds:nl(e.members,s)});case 31:return dl(le,{...t,isMuted:!0});case 32:return dl(le,{...t,isMuted:!1});case 21:return dl(he,{...t,administratorId:s??r});case 22:return dl(pe,{...t,administratorId:s??r});case 20:return dl(me,{...t,oldOwnerId:r,newOwnerId:s});case 17:{const s=nl(e.members,r);return dl(ge,{...t,memberIds:s})}case 18:{const s=nl(e.members,r);return dl(fe,{...t,memberIds:s})}case 25:return dl(ye,{...t,announcement:e.reason??""});case 26:return dl(ye,{...t,announcement:""});case 27:return dl(ve,{...t,sharedFile:al(e.reason,e.eventExt)});case 28:return dl(Ie,{...t,fileId:cl(e.reason,e.eventExt)});case 14:return dl(be,{...t,shouldFetchGroupDetail:!0,groupPatch:ol(e.eventExt)});case 41:return dl(_e,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return dl(_e,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const s=(e=>{const t=sl(e);if(!t)return{attribute:{}};const r=t.properties&&"object"==typeof t.properties&&!Array.isArray(t.properties)?t.properties:{},s=Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]));return{userId:rl(t.username),attribute:s}})(e.eventExt);return dl(Te,{...t,userId:s.userId,attribute:s.attribute,from:r,source:e.source??"direct"})}default:return null}},ll=new WeakMap,hl=(e,t)=>{ll.set(e,t)},pl=e=>ll.get(e)??null,ml=(e,t)=>{const r=pl(e);r&&hl(t,r)},gl=new WeakMap,fl=e=>gl.get(e),yl=new WeakMap,vl=e=>yl.get(e),Il=(e,t)=>{const r=yl.get(e);r&&yl.set(t,r)},bl="singleChat",_l="groupChat",Tl=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Cl=e=>{if("number"==typeof e)return Number.isFinite(e)?e:void 0;if("string"==typeof e&&e.trim().length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}},Sl=e=>{if(!Array.isArray(e))return;const t=e.map(e=>Tl(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},El=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),wl=(...e)=>{for(const t of e){const e=Tl(t);if(e)return e}},Al=(e,t)=>Boolean(e&&t&&e===t),Rl=(e,t,r)=>Boolean(e&&e===r.userId&&t&&r.clientResource&&t!==r.clientResource),Nl=(e,t,r)=>{const s=Sl(e);if(s&&s.length>0)return s;const n=(t??[]).map(e=>Tl(e.name)).filter(e=>"string"==typeof e);if(n.length>0)return n;const i=Tl(r?.name);return i?[i]:[]},Ol=e=>{const t=Cl(e);if(void 0!==t)return t;if("string"==typeof e){const t=e.match(/(\d+)/);if(t){const e=Number(t[1]);return Number.isFinite(e)?e:void 0}}},Ml=(e,t)=>{const r=wl(e.to?.[0]?.clientResource);if(1!==e.to?.length||Tl(e.to[0]?.name)!==t.userId||!Rl(t.userId,r,t))return null;const s=(n=e.from,Tl(n?.name)??"");var n;if(!s)return Ks("Discarded MultiDevice contact event without target user",{operation:e.operation}),null;const i=(e=>{switch(e){case 3:return"CONTACT_REMOVE";case 4:case 8:return"CONTACT_ACCEPT";case 5:case 9:return"CONTACT_DECLINE";case 6:return"CONTACT_BAN";case 7:return"CONTACT_ALLOW";default:return Ks("Discarded unknown MultiDevice contact operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===i?null:{category:"contact",operation:i,targetUserId:s,rosterVersion:e.rosterVersion,ext:e.ext,deviceId:r,timestamp:e.timestamp,raw:e.raw}},Ul=(e,t)=>{if(!e.groupId)return Ks("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const r=wl(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Rl(Tl(e.from?.name),r,t))return null;const s=(e=>{switch(e){case 0:return"GROUP_CREATE";case 1:return"GROUP_DESTROY";case 2:return"GROUP_JOIN";case 3:return"GROUP_LEAVE";case 4:return"GROUP_APPLY";case 5:return"GROUP_APPLY_ACCEPT";case 6:return"GROUP_APPLY_DECLINE";case 7:return"GROUP_INVITE";case 8:return"GROUP_INVITE_ACCEPT";case 9:return"GROUP_INVITE_DECLINE";case 10:return"GROUP_KICK";case 12:return"GROUP_BAN";case 13:return"GROUP_ALLOW";case 15:return"GROUP_BLOCK";case 16:return"GROUP_UNBLOCK";case 20:return"GROUP_ASSIGN_OWNER";case 21:return"GROUP_ADD_ADMIN";case 22:return"GROUP_REMOVE_ADMIN";case 23:return"GROUP_ADD_MUTE";case 24:return"GROUP_REMOVE_MUTE";case 29:return"GROUP_ADD_USER_WHITE_LIST";case 30:return"GROUP_REMOVE_USER_WHITE_LIST";case 31:return"GROUP_ALL_BAN";case 32:return"GROUP_REMOVE_ALL_BAN";case 45:return"GROUP_MEMBER_METADATA_CHANGED";case 14:return"GROUP_UPDATED";default:return Ks("Discarded unknown MultiDevice group operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===s)return null;const n=Nl(e.members,e.to,e.from);return{category:"group",operation:s,groupId:e.groupId,userIds:n.length>0?n:void 0,operatorId:Tl(e.from?.name),groupName:e.groupName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},Ll=(e,t)=>{if(!e.threadId)return Ks("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const r=wl(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Rl(Tl(e.from?.name),r,t))return null;const s=(e=>{switch(e){case 33:return"THREAD_CREATE";case 35:return"THREAD_JOIN";case 38:return"THREAD_UPDATE";case 36:return"THREAD_LEAVE";case 34:return"THREAD_DESTROY";case 37:return"THREAD_KICK";default:return Ks("Discarded unknown MultiDevice thread operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===s)return null;const n=Nl(e.members,e.to,e.from);return{category:"thread",operation:s,threadId:e.threadId,parentId:e.parentId,userIds:n.length>0?n:void 0,operatorId:Tl(e.from?.name),threadName:e.threadName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},kl=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const r=wl(e.res,e.raw?.resource,e.raw?.clientResource);if(Al(r,t.clientResource))return Vs("Discarded same-device MultiDevice conversation echo",{operation:e.operation,conversationId:e.id}),null;const s="chat"===(n=e.type)||"singleChat"===n?bl:_l;var n;const i=Tl(e.id)??(s===bl?Tl(e.from):void 0);if(!i)return Ks("Discarded MultiDevice conversation event without conversationId",{operation:e.operation}),null;const o=(e=>{switch(e){case"del":return"CONVERSATION_DELETED";case"top":return"CONVERSATION_PINNED";case"not_top":return"CONVERSATION_UNPINNED";case"mark":case"mark_delete":return"CONVERSATION_MARK";case"setSilentModeForConversation":case"removeSilentModeForConversation":return"CONVERSATION_MUTE_INFO_CHANGED";default:return Ks("Discarded unknown MultiDevice conversation operation",{operation:e}),"UNKNOWN"}})(e.operation);return"UNKNOWN"===o?null:{category:"conversation",operation:o,conversationId:i,conversationType:s,mark:"mark"===e.operation||"mark_delete"===e.operation?Ol(e.ext):void 0,operatorId:Tl(e.from),deviceId:r,timestamp:Cl(e.ts),raw:e.raw}},Dl=(e,t)=>{const r=wl(e.resource,e.raw?.resource,e.raw?.clientResource);if(Al(r,t.clientResource))return Vs("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const s=Tl(e.to);if(!s)return Ks("Discarded MultiDevice roaming delete event without conversationId",{}),null;const n=Tl(e.lastMsgId),i=Sl(e.msgIdList)??(n?[n]:void 0),o=Cl(e.deleteTime);if(!i&&void 0===o)return Ks("Discarded MultiDevice roaming delete event without messageIds or beforeTimestamp",{conversationId:s}),null;const a=(e=>e&&"deleteRoaming"!==e&&"MESSAGE_REMOVED"!==e?(Ks("Discarded unknown MultiDevice message-removed operation",{operation:e}),"UNKNOWN"):"MESSAGE_REMOVED")(e.messageRoamingType);return"UNKNOWN"===a?null:{category:"messageRemoved",operation:a,conversationId:s,conversationType:"groupchat"===e.chatType||"groupChat"===e.chatType?_l:bl,messageIds:i,beforeTimestamp:o,deviceId:r,raw:e.raw}},Pl=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}},xl=2147483647,Fl=e=>{const t=Number(e);if(!Number.isFinite(t)||t<=0)return;const r=Math.floor(t);return r<=0||r>xl?void 0:r},Bl=e=>{if("number"!=typeof e||!Number.isFinite(e)||e<=0)return;const t=e>xl?Math.floor(e/1e3):Math.floor(e);return Fl(t)};var Gl=4096,ql=65547,$l=15,jl=2113929216,Vl=65536,Kl=65536,zl=10485760,Hl={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},Wl={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function Jl(e){if(!(e>0))return Kl;if(e<=Kl)return Kl;if(e>1073741823)return e;for(var t=Kl;t<e;)t*=2;return t}var Ql={byU16:0,byU32:1},Zl=0,Yl=1,Xl=2,eh=0,th=1;function rh(e,t){return e[t]|e[t+1]<<8}function sh(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function nh(e,t,r){e[t]=255&r,e[t+1]=r>>>8&255}var ih="fast";function oh(e){return 2654435761*(e>>>0)>>>20&4095}function ah(e){return 2654435761*(e>>>0)>>>19&8191}function ch(e,t,r){if("fast"===ih){var s=sh(e,t);return r===Ql.byU16?ah(s):oh(s)}throw new Error("Unsupported hash strategy: "+ih)}function dh(e,t,r,s,n){r[t]=e-n}function uh(e,t,r,s,n){dh(t,ch(e,t,s),r,0,n)}function lh(e,t,r,s){return t[e]+s}function hh(e,t,r,s,n){return lh(ch(e,t,s),r,0,n)}function ph(e,t,r,s){for(var n=t;t<s-3;){if(sh(e,t)!==sh(e,r)){for(;t<s&&e[t]===e[r];)t++,r++;return t-n}t+=4,r+=4}for(;t<s&&e[t]===e[r];)t++,r++;return t-n}function mh(e,t,r,s,n,i,o,a,c,d){var u,l,h,p=e.hashTable,m=s,g=m-e.dictSize,f=e.dictionary,y=e.dictionaryStart,v=y+e.dictSize,I=e.dictSize>0?v-s:0,b=s,_=s+n,T=_-12,C=_-5,S=0,E=i>0?i:r.length,w=0;if(n>jl)return 0;switch(c){case Zl:default:u=s,l=s;break;case Yl:u=s-e.currentOffset,l=s-e.dictSize;break;case Xl:u=s-e.currentOffset,l=s}if(a===Ql.byU16&&n>=ql)return 0;if(n<13)return yh(t,r,b,_,S,E,o);uh(t,m,p,a,u),h=ch(t,++m,a);e:for(;;){var A,R,N=m,O=1,M=64;do{var U=h;if(m=N,N+=O,O=M++>>>6,N>T)return yh(t,r,b,_,S,E,o);A=lh(U,p,0,u),c===Xl&&(A<s?(w=I,l=y):(w=0,l=s)),h=ch(t,N,a),dh(m,U,p,0,u)}while(d===th&&A<g||a!==Ql.byU16&&A+65535<m||!gh(t,f,m,A,w,c,s));for(;m>b&&A+w>l;){var L=A+w-1;if(t[m-1]!==(c===Xl&&A<s?f[L-y+e.dictionaryStart]:t[L]))break;m--,A--}var k=m-b;if(R=S++,o&&S+k+8+Math.floor(k/255)>E)return 0;if(k>=$l){var D=k-$l;for(r[R]=240;D>=255;)r[S++]=255,D-=255;r[S++]=D}else r[R]=k<<4;if(k>=16&&r.set&&t.subarray)r.set(t.subarray(b,b+k),S),S+=k;else for(var P=0;P<k;P++)r[S++]=t[b+P];t:for(;;){var x;if(nh(r,S,m-A),S+=2,c===Xl&&A<s){var F=m+(v-(A+w));if(F>C&&(F=C),(m+=4+(x=fh(t,f,m+4,A+w+4-y+e.dictionaryStart,F,v-y)))===F&&F<C){var B=ph(t,m,s,C);x+=B,m+=B}}else m+=4+(x=ph(t,m+4,A+4,C));if(o&&S+6+(x>>>8)>E)return 0;if(x>=15){for(r[R]+=15,x-=15;x>=510;)r[S++]=255,r[S++]=255,x-=510;x>=255&&(x-=255,r[S++]=255),r[S++]=x}else r[R]+=x;if(b=m,m>T)break e;if(uh(t,m-2,p,a,u),A=hh(t,m,p,a,u),c===Xl&&(A<s?(w=I,l=y):(w=0,l=s)),uh(t,m,p,a,u),!((d!==th||A>=g)&&A+65535>=m&&gh(t,f,m,A,w,c,s)))break t;r[R=S++]=0}h=ch(t,++m,a)}return yh(t,r,b,_,S,E,o)}function gh(e,t,r,s,n,i,o){var a,c=sh(e,r);i===Xl&&s+n<o?a=sh(t,s+n):a=sh(e,s+n);return c===a}function fh(e,t,r,s,n,i,o){for(var a=r;s<i&&r<n&&t[s]===e[r];)s++,r++;return r-a}function yh(e,t,r,s,n,i,o){var a=s-r;if(o&&n+a+1+Math.floor((a+255-$l)/255)>i)return 0;if(a>=$l){for(t[n++]=240,a-=$l;a>=255;)t[n++]=255,a-=255;t[n++]=a}else t[n++]=a<<4;var c=r,d=s,u=d-c;if(u>=16&&t.set&&e.subarray)t.set(e.subarray(c,d),n),n+=u;else for(var l=c;l<d;l++)t[n++]=e[l];return n}function vh(e,t,r,s){var n,i=0;if(s&&t.ip>=r)return-1;do{if(i+=n=e[t.ip++],t.ip>r)return-1;if(i>2147483647)return-1}while(255===n);return i}function Ih(e,t,r,s,n,i,o,a,c,d,u,l,h){if(null==e)return-1;if(i<0)return-1;var p=r,m=r+s,g=n,f=n+i,y=u-h,v=l+h,I=h<65536;if(0===i)return 1===s&&0===e[p]?0:-1;if(0===s)return-1;for(;;){var b,_,T,C;if(p>=m)return-(p-r)-1;if((_=(b=e[p++])>>>4)===$l){var S=vh(e,A={ip:p},m-$l,!0);if(p=A.ip,-1===S)return-(p-r)-1;if(g+(_+=S)<g)return-(p-r)-1;if(p+_<p)return-(p-r)-1}if(T=g+_,o&&(T>f-12||p+_>m-8)||!o&&T>f-8){if(!o&&T!==f)return-(p-r)-1;if(o&&(p+_!==m||T>f))return-(p-r)-1;if(_>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+_),g);else for(var E=0;E<_;E++)t[g+E]=e[p+E];p+=_,g+=_;break}if(_>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+_),g);else for(E=0;E<_;E++)t[g+E]=e[p+E];if(g=T,(p+=_)+2>m)return-(p-r)-1;var w=rh(e,p);if(p+=2,C=T-w,I&&C+h<u)return-(p-r)-1;if(0===w)return-(p-r)-1;if(15===(_=15&b)){var A;S=vh(e,A={ip:p},m-5+1,!1);if(p=A.ip,-1===S)return-(p-r)-1;if(g+(_+=S)<g)return-(p-r)-1}if(_+=4,d===Xl&&C<u){if(g+_>f-5)return-(p-r)-1;if(_<=u-C){var R=v-(u-C);for(E=0;E<_;E++)t[g+E]=t[R+E];g+=_}else{var N=u-C;for(R=v-N,E=0;E<N;E++)t[g+E]=t[R+E];var O=_-N;if(O>(g+=N)-u)for(var M=u,U=g+O;g<U;)t[g++]=t[M++];else{for(E=0;E<O;E++)t[g+E]=t[u+E];g+=O}}}else{if(C<y)return-(p-r)-1;if(T=g+_,g-C<8)for(t[g]=t[C],t[g+1]=t[C+1],t[g+2]=t[C+2],t[g+3]=t[C+3],g+=4,C+=4;g<T;)t[g++]=t[C++];else for(;g<T;)t[g++]=t[C++]}}return o?g-n:p-r}function bh(){return{hashTable:new Uint32Array(Gl),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function _h(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function Th(e,t,r,s,n,i,o,a){s=s||0;var c=e.dictionaryStart+e.dictSize,d=s;if(e.initCheck)return 0;e.dictSize>0&&d>c&&(d=c),function(e){if(e.currentOffset>2147483648){for(var t=e.currentOffset-65536,r=e.dictionaryStart+e.dictSize,s=0;s<e.hashTable.length;s++)e.hashTable[s]<t?e.hashTable[s]=0:e.hashTable[s]-=t;e.currentOffset=65536,e.dictSize>65536&&(e.dictSize=65536),e.dictionaryStart=r-e.dictSize}}(e);var u,l=s+n;e.dictionary&&l>e.dictionaryStart&&l<c&&(e.dictSize=c-l,e.dictSize>65536&&(e.dictSize=65536),e.dictSize<4&&(e.dictSize=0),e.dictionaryStart=c-e.dictSize);var h=e.dictSize<65536&&e.dictSize<e.currentOffset?th:eh;return e.dictionary&&c===s?(u=mh(e,t,r,s,n,o||0,a||!1,Ql.byU32,Yl,h),e.dictSize+=n,e.currentOffset+=n,u):(u=mh(e,t,r,s,n,o||0,a||!1,Ql.byU32,Xl,h),e.dictionary=t,e.dictionaryStart=s,e.dictSize=n,e.currentOffset+=n,u)}function Ch(e,t,r,s){var n=e.dictionaryStart+e.dictSize;s>65536&&(s=65536),s>e.dictSize&&(s=e.dictSize);var i=n-s;if(t.set&&e.dictionary.subarray)t.set(e.dictionary.subarray(i,i+s),r);else for(var o=0;o<s;o++)t[r+o]=e.dictionary[i+o];return e.dictionary=t,e.dictionaryStart=r,e.dictSize=s,s}function Sh(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function Eh(e,t,r,s){return e.prefixSize=s,e.prefixEnd=r+s,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function wh(e,t,r,s,n,i,o){var a;if(e.prefixEnd===i){if((a=Ih(t,r,s,n,i,o,!0,0,0,Xl,e.prefixEnd-e.prefixSize,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize+=a,e.prefixEnd+=a}else{if(e.extDictSize=e.prefixSize,e.extDictStart=e.prefixEnd-e.extDictSize,(a=Ih(t,r,s,n,i,o,!0,0,0,Xl,i,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=i+a}return a}function Ah(e){var t=(e=e||{}).minWorkArea||Kl,r=e.maxWorkArea||zl,s=e.shrinkThreshold||t;t<Kl&&(t=Kl),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Vl+t,this.maxBufferSize=Vl+r,this.shrinkThreshold=Vl+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Hl.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=bh()}function Rh(e){var t=(e=e||{}).minWorkArea||Kl,r=e.maxWorkArea||zl,s=e.shrinkThreshold||t;t<Kl&&(t=Kl),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Vl+t,this.maxBufferSize=Vl+r,this.shrinkThreshold=Vl+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Hl.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}Ah.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Vl?this.offset:Vl,n=this.offset>Vl?this.offset-Vl:0;t.set(this.ringBuffer.subarray(n,n+s),0),Ch(this.stream,t,0,s),r=s}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},Ah.prototype.compress=function(e,t){var r=e.length;if(r<=0)return Wl.PARAM_ERROR;if(r>this.maxBufferSize-Vl)return Wl.PARAM_ERROR;if(r>this.ringBufferSize-Vl){var s=Jl(r),n=Vl+s;if(n>this.maxBufferSize&&(n=this.maxBufferSize),!this._resizeBuffer(n))return Wl.BUFFER_RESIZE_FAILED}this.offset+r>this.ringBufferSize&&(Ch(this.stream,this.ringBuffer,0,Vl),this.offset=Vl);var i=this.offset;this.ringBuffer.set(e,i);var o=Th(this.stream,this.ringBuffer,t,i,r,0,t.length,!0);return o<=0?Wl.COMPRESS_FAILED:(this.offset+=r,this._tryAutoShrink(),o)},Ah.prototype.reset=function(){this.offset=0,_h(this.stream)},Ah.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Ah.prototype._tryAutoShrink=function(){this.shrinkMode!==Hl.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Hl.AUTO_IMMEDIATE||this.shrinkMode===Hl.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Ah.prototype.getWorkArea=function(){return this.ringBufferSize-Vl},Ah.prototype.getRingBufferSize=function(){return this.ringBufferSize},Ah.prototype.getBaseBufferSize=function(){return this.minBufferSize},Ah.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Ah.prototype.getCurrentOffset=function(){return this.offset},Ah.prototype.getShrinkMode=function(){return this.shrinkMode},Ah.prototype.setShrinkMode=function(e){this.shrinkMode=e},Ah.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Ah.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Vl,r=this.maxBufferSize-Vl;if(e<t||e>r)return Wl.PARAM_ERROR;this.shrinkThreshold=Vl+e},Rh.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Vl?this.offset:Vl,n=this.offset>Vl?this.offset-Vl:0;t.set(this.ringBuffer.subarray(n,n+s),0),r=s,Eh(this.streamDecode,0,0,s)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},Rh.prototype.decompress=function(e,t,r){var s=e.length;if(s<=0||r<=0)return Wl.PARAM_ERROR;if(r>this.maxBufferSize-Vl)return Wl.PARAM_ERROR;if(r>this.ringBufferSize-Vl){var n=Jl(r),i=Vl+n;if(i>this.maxBufferSize&&(i=this.maxBufferSize),!this._resizeBuffer(i))return Wl.BUFFER_RESIZE_FAILED}if(this.offset+r>this.ringBufferSize){var o=this.offset-Vl;o>0&&this.ringBuffer.set(this.ringBuffer.subarray(o,o+Vl),0),Eh(this.streamDecode,this.ringBuffer,0,Vl),this.offset=Vl}var a=wh(this.streamDecode,e,this.ringBuffer,0,s,this.offset,r);return a<=0?Wl.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},Rh.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},Rh.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Rh.prototype._tryAutoShrink=function(){this.shrinkMode!==Hl.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Hl.AUTO_IMMEDIATE||this.shrinkMode===Hl.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Rh.prototype.getWorkArea=function(){return this.ringBufferSize-Vl},Rh.prototype.getRingBufferSize=function(){return this.ringBufferSize},Rh.prototype.getBaseBufferSize=function(){return this.minBufferSize},Rh.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Rh.prototype.getCurrentOffset=function(){return this.offset},Rh.prototype.getShrinkMode=function(){return this.shrinkMode},Rh.prototype.setShrinkMode=function(e){this.shrinkMode=e},Rh.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Rh.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Vl,r=this.maxBufferSize-Vl;if(e<t||e>r)return Wl.PARAM_ERROR;this.shrinkThreshold=Vl+e};const Nh={LZ4_MAX_INPUT_SIZE:jl,BLOCK_MAX_SIZE:65536,DICT_SIZE:Vl,DEFAULT_WORK_AREA:Kl,DEFAULT_MAX_WORK:zl,SHRINK_MODE:Hl,LZ4_ERROR:Wl,alignToPowerOf2:Jl,calcDefaultBufferSize:function(){return 131072},calcDefaultMaxBufferSize:function(){return 10551296},setHashStrategy:function(e){if("fast"!==e&&"compatible"!==e)throw new Error("Invalid hash strategy: "+e+'. Use "fast" or "compatible".');ih=e},getHashStrategy:function(){return ih},compress:function(e,t,r,s,n){if(null==e)return 0;if(null==t)return 0;if(r=r||0,s=void 0===s?e.length:s,n=n||0,r<0||n<0)return 0;if(s<0)return 0;if(r+s>e.length)return 0;if(s>jl)return 0;if(0===s)return t.length>n?(t[n]=0,1):0;var i=s<ql?Ql.byU16:Ql.byU32;return mh({hashTable:new Uint32Array(i===Ql.byU16?8192:Gl),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,0,!1,i,Zl,eh)},compressLimited:function(e,t,r,s,n,i){if(null==e)return 0;if(null==t)return 0;if(r=r||0,s=void 0===s?e.length:s,n=n||0,r<0||n<0)return 0;if(s<0||i<0)return 0;if(r+s>e.length)return 0;if(s>jl)return 0;if(i<1)return 0;if(0===s)return t[n]=0,1;var o=s<ql?Ql.byU16:Ql.byU32;return mh({hashTable:new Uint32Array(o===Ql.byU16?8192:Gl),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,i,!0,o,Zl,eh)},compressBound:function(e){return e<0||e>jl?0:e+Math.floor(e/255)+16},decompressSafe:function(e,t,r,s,n,i){return null==e||null==t?-1:(n=n||0,(r=r||0)<0||n<0||s<0||i<0||r+s>e.length||n+i>t.length?-1:Ih(e,t,r,s,n,i,!0,0,0,Zl,n,null,0))},decompressFast:function(e,t,r,s,n){return Ih(e,t,r=r||0,0,s=s||0,n,!1,0,0,Yl,s-65536,0,65536)},createStream:bh,resetStream:_h,loadDict:function(e,t,r,s){if(e.initCheck&&_h(e),s<4)return e.dictionary=null,e.dictSize=0,0;s>65536&&(r=r+s-65536,s=65536);var n=r-e.currentOffset;e.dictionary=t,e.dictionaryStart=r,e.dictSize=s,e.currentOffset+=s;for(var i=r,o=r+s;i<=o-4;)uh(t,i,e.hashTable,Ql.byU32,n),i+=3;return s},compressContinue:Th,saveDict:Ch,createStreamDecode:Sh,setStreamDecode:Eh,decompressSafeContinue:wh,RingBufferEncoder:Ah,RingBufferDecoder:Rh,_hashU16:ah,_hashU32:oh,_TABLE_TYPE:Ql},Oh=268435455,Mh=new Uint32Array(256);let Uh=!1;function Lh(e){!function(){if(!Uh){for(let e=0;e<256;e+=1){let t=e;for(let e=0;e<8;e+=1)t=1&t?3988292384^t>>>1:t>>>1;Mh[e]=t>>>0}Uh=!0}}();let t=4294967295;for(let r=0;r<e.length;r+=1){const s=e[r]??0;t=t>>>8^(Mh[255&(t^255&s)]??0)}return(4294967295^t)>>>0}var kh=(e=>(e[e.NONE=-1]="NONE",e[e.UPLINK_ONLY=0]="UPLINK_ONLY",e[e.DOWNLINK_ONLY=1]="DOWNLINK_ONLY",e[e.BIDIRECTIONAL=2]="BIDIRECTIONAL",e))(kh||{});const Dh=268435455;class Ph{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:Nh.DEFAULT_WORK_AREA,maxWorkArea:Nh.DEFAULT_MAX_WORK,shrinkMode:Nh.SHRINK_MODE.MANUAL};this.encoder=new Nh.RingBufferEncoder(e),this.decoder=new Nh.RingBufferDecoder(e)}compress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length>Dh)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const r=Nh.compressBound(t.length),s=new Uint8Array(r),n=this.encoder.compress(t,s);if(n<0)throw new Error(`LZ4 compression failed with error code: ${n}`);const i=s.subarray(0,n),o=function(e){if(e<0)throw new Error("encodeLength: Length must be non-negative");if(e>Oh)throw new Error("encodeLength: Length exceeds maximum: 268435455");if(0===e)return new Uint8Array([0]);const t=[];let r=e;for(;r>0;){let e=127&r;r>>>=7,r>0&&(e|=128),t.push(e)}return new Uint8Array(t)}(t.length),a=Lh(t),c=new Uint8Array(o.length+4+n);let d=0;c.set(o,d),d+=o.length;return new DataView(c.buffer).setUint32(d,a,!1),d+=4,c.set(i,d),c}decompress(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!t||0===t.length)return new Uint8Array(0);if(t.length<5)throw new Error("Compressed data is too short: must contain at least length and CRC32");const r={offset:0},s=function(e,t){if(t.offset>=e.length)throw new Error("decodeLength: No data to decode: offset beyond data length");let r=0,s=0;for(;t.offset<e.length;){const n=e[t.offset]??0;if(t.offset+=1,r|=(127&n)<<s,!(128&n))return r>>>0;if(s+=7,s>=28)throw new Error("decodeLength: Invalid length encoding: exceeds 4 bytes")}throw new Error("decodeLength: Incomplete length encoding: missing terminator byte")}(t,r);if(s>Dh)throw new Error(`Original size exceeds maximum allowed: ${s}`);if(t.length<r.offset+4)throw new Error("Compressed data is too short: missing CRC32 checksum");const n=new DataView(t.buffer,t.byteOffset+r.offset,4).getUint32(0,!1);r.offset+=4;const i=t.subarray(r.offset),o=new Uint8Array(s),a=this.decoder.decompress(i,o,s);if(a<0||a!==s)throw new Error(`LZ4 decompression failed: expected ${s}, got ${a}`);const c=Lh(o);if(c!==n)throw new Error(`CRC32 checksum mismatch: expected ${n}, got ${c}`);return o}reset(){this.encoder.reset(),this.decoder.reset()}}const xh=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Fh=(e,t)=>Da(e,t).finish();class Bh{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=Yd({useFixedDeviceId:e.useFixedDeviceId??!0,deviceId:e.deviceId??"webim",customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform}),r=`${Date.now()}:`;return{appKey:e.appKey,userId:e.userId,token:e.token,domain:e.domain??"easemob.com",version:e.version??"4.11.0",uiKitVersion:e.uiKitVersion,osType:void 0!==e.customOSPlatform?5:e.osType??16,deviceId:t.deviceId,deviceName:t.deviceName,deviceUuid:t.deviceUuid,clientResource:t.deviceId,customOSPlatform:e.customOSPlatform,loginExtensionInfo:e.loginExtensionInfo,encryptType:[sr],compressType:[nr],sessionId:r,serviceId:e.serviceId}})(e),this.useReplacedMessageContents=e.useReplacedMessageContents??!1,this.payloadDecoder=new vu(this.context.userId,e.useCustomAttachmentUpload??!1)}updateToken(e){this.context.token=e}updateResource(e){e&&(this.context.clientResource=e)}getContext(){return{...this.context}}encodeProvision(){const e=Wd(),t=e.lookupType("easemob.pb.Provision"),r=e.lookupType("easemob.pb.MSync"),s={osType:this.context.osType,version:this.context.uiKitVersion??this.context.version,compressType:[nr],encryptType:[sr],protocolCompressType:this.getRequestedCompressTypes(),deviceUuid:this.context.deviceUuid,deviceName:this.context.deviceName,resource:this.context.deviceId,actionVersion:"v6.0",authToken:`{"token":"$t$${this.context.token}"}`,sessionId:this.context.sessionId,...this.context.serviceId?{serviceId:this.context.serviceId}:{},...void 0!==this.context.customOSPlatform?{osCustomValue:this.context.customOSPlatform}:{},...this.context.loginExtensionInfo?{reason:this.context.loginExtensionInfo}:{}},n=Fh(t,s),i={version:0,guid:Xd({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),command:St,deviceId:0,encryptType:[sr],payload:n,traceId:bu()};return Fh(r,i)}encodeHeartbeat(){const e=Wd(),t=e.lookupType("easemob.pb.CommUnreadUL"),r=e.lookupType("easemob.pb.MSync"),s=Fh(t,{}),n={version:0,encryptType:[sr],command:Tt,payload:s,traceId:bu()};return Fh(r,n)}encodeStatisticRebuild(){const e=Wd(),t=e.lookupType("easemob.pb.StatisticsBody"),r=e.lookupType("easemob.pb.Meta"),s=e.lookupType("easemob.pb.CommSyncUL"),n=e.lookupType("easemob.pb.MSync"),i=Fh(t,{operation:0}),o=r.decode(new Uint8Array);o.id=Date.now(),o.ns=Jt,o.payload=i;const a=s.decode(new Uint8Array);a.meta=o;const c=Fh(s,a);return Fh(n,{version:0,encryptType:[sr],command:_t,payload:c,traceId:bu()})}decodeProvision(e){const t=Wd().lookupType("easemob.pb.Provision").decode(e),r=t.status??{},s="number"==typeof r.errorCode?r.errorCode:ar,n="string"==typeof r.reason?r.reason:void 0,i="string"==typeof t.resource?t.resource:void 0,o="string"==typeof t.authToken?t.authToken:void 0,a=Array.isArray(t.protocolCompressType)?t.protocolCompressType:void 0,c="number"==typeof t.protocolCompressDirection?t.protocolCompressDirection:void 0;return this.configureCompression(a,c),{ok:s===or,statusCode:s,reason:n,resource:i,authToken:o,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=Wd().lookupType("easemob.pb.Logout").decode(e),r=t.status&&"object"==typeof t.status?t.status:void 0;return{sessionId:"string"==typeof t.sessionId?t.sessionId:void 0,reason:"string"==typeof t.reason?t.reason:void 0,statusCode:"number"==typeof r?.errorCode?r.errorCode:void 0}}decodeSyncStatisticOperations(e){const t=Wd().lookupType("easemob.pb.CommSyncDL").decode(e),r=Array.isArray(t.metas)?t.metas:[],s=[];for(const n of r){const e=this.decodeStatisticMeta(n);e&&s.push(e)}return s}decodeMsync(e){const t=Wd().lookupType("easemob.pb.MSync").decode(e);return{command:"number"==typeof t.command?t.command:-1,payload:this.normalizeBinaryPayload(t.payload)}}normalizeBinaryPayload(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)?Uint8Array.from(e.filter(e=>"number"==typeof e)):new Uint8Array}decodeSync(e){const t=Wd(),r=t.lookupType("easemob.pb.CommSyncDL"),s=t.lookupType("easemob.pb.MessageBody"),n=r.decode(e);Vs("decodeSync commSyncDl",{hasMetas:Array.isArray(n.metas)});const i=Array.isArray(n.metas)?n.metas:[],o=this.decodeAck(n);o?.ok&&(o.chatRoomInfo=this.decodeChatRoomJoinInfo(i));const a=tu(n.metaId),c=tu(n.nextKey),d=n.queue??void 0,u="boolean"==typeof n.isLast?n.isLast:void 0,l=[],h=[];if(a&&"0"!==a){const e=this.useReplacedMessageContents?this.decodeReplacedMessage(i,s):void 0;for(const t of i){const e=this.decodeNotifyMeta(t);e.length>0&&h.push(...e)}return{ack:o,messages:l,notifies:h.length>0?h:void 0,metaId:a,queue:d,nextKey:c,isLast:u,replacedMessage:e}}for(const p of i){const e=this.decodeChatMeta(p,s);e&&l.push(e);const t=this.decodeChatActionMeta(p,s);t&&h.push(t);const r=this.decodeNotifyMeta(p);r.length>0&&h.push(...r)}return{ack:o,messages:l,notifies:h.length>0?h:void 0,metaId:a,queue:d,nextKey:c,isLast:u}}decodeReplacedMessage(e,t){for(const r of e){const e=this.decodeChatMeta(r,t);if(e)return e}}decodeChatMeta(e,t){if(!e||"object"!=typeof e)return null;const r=e,s=r.payload;let n=null;if(s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!n)return null;if(("number"==typeof r.ns?r.ns:void 0)!==Qt)return null;try{const e=t.decode(n);if(!e||"object"!=typeof e)return null;const s=e;return this.decodeMessage(r,s)}catch{return null}}decodeChatActionMeta(e,t){if(!e||"object"!=typeof e)return null;const r=e,s=r.payload;let n=null;if(s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),!n)return null;if(("number"==typeof r.ns?r.ns:void 0)!==Qt)return null;try{const e=t.decode(n);if(!e||"object"!=typeof e)return null;const s=e,i="number"==typeof s.type?s.type:wt;if(i!==Ot&&i!==Ut&&i!==Lt&&i!==kt&&i!==Mt)return null;const o=this.readJid(r.to),a=Number(tu(r.timestamp))||Date.now(),c=this.resolveActionConversationType(o.domain,s.meta,s),{senderId:d,receiverId:u}=this.resolveIncomingMessageParties(r,s,c),l=this.resolveActionConversationId(d,u,c);if(i===Lt)return!0===s.clearAllUnreadMessageCount?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"ALL_CONVERSATIONS_UNREAD_MESSAGE_COUNT_CLEARED",timestamp:a}}:l?{type:"multiDevice",eventName:"onMultiDeviceConversation",data:{category:"conversation",operation:"CONVERSATION_UNREAD_MESSAGE_COUNT_CLEARED",conversationId:l,conversationType:"groupChat"===c?"groupChat":"singleChat",timestamp:a}}:null;if(i===Ot){Vs("Received READ_ACK MessageBody",s);const e=(Array.isArray(s.ackMessageIds)?s.ackMessageIds:[]).map(e=>tu(e)).filter(e=>Boolean(e)),t=tu(s.ackMessageId);if(0===e.length&&t&&e.push(t),0===e.length||!l)return null;const r=su(Array.isArray(s.ext)?s.ext.filter(xh):void 0),n=xh(r.group_ack_count)?r.group_ack_count:{},i=e.flatMap(e=>{const t=n[e];return"number"==typeof t&&Number.isInteger(t)&&t>=0?[{messageId:e,count:t}]:[]});return{type:"message_receipts",data:{messageIds:e,conversationId:l,conversationType:"groupChat"===c?"groupChat":"singleChat",timestamp:a,..."groupChat"===c?{receiptDetails:i}:{}}}}if(i===Mt){const e=tu(s.ackMessageId);return e&&l?{type:"message_delivered",data:{messageId:e,from:d,to:u,conversationId:l,conversationType:"singleChat"}}:null}if(i===Ut){const e=tu(s.ackMessageId);return e&&l?{type:"message_recalled",data:{messageId:e,conversationId:l,conversationType:c,timestamp:a}}:null}const h=tu(s.editMessageId),p=(Array.isArray(s.contents)?s.contents.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)):[])[0],m=p?this.decodeContent(p,s.meta):null;if(!h||!l||!m)return null;const g=this.payloadDecoder.resolveModifiedInfo(s.meta);return{type:"message_updated",data:{messageId:h,conversationId:l,conversationType:c,timestamp:a,message:{type:m.type,body:m.body,ext:su(s.ext),...g?{modifiedInfo:g}:{}}}}}catch{return null}}decodeNotifyMeta(e){if(!e||"object"!=typeof e)return[];const t=e,r="number"==typeof t.ns?t.ns:void 0;if(r!==Xt&&r!==Yt&&r!==Zt&&r!==Jt)return[];const s=t.payload;let n=null;return s instanceof Uint8Array?n=s:s instanceof ArrayBuffer?n=new Uint8Array(s):ArrayBuffer.isView(s)&&(n=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),n?r===Yt?this.decodeRosterMeta(t,n):r===Zt?this.decodeMucMeta(t,n):r===Jt?this.decodeStatisticGroupReceiptNotifies(t,n):this.decodeNotifyPayload(n):[]}decodeStatisticGroupReceiptNotifies(e,t){try{const r=Wd(),s=r.lookupType("easemob.pb.StatisticsBody").decode(t);if("string"!=typeof s.location||0===s.location.length)return[];const n=JSON.parse(s.location);if(!xh(n)||!Array.isArray(n.group_ack))return[];const i=this.readMetaTimestamp(e)??Date.now(),o=new Map;for(const e of n.group_ack){if(!xh(e))continue;const t="string"==typeof e.groupId&&e.groupId.length>0?e.groupId:"";for(const[r,s]of Object.entries(e)){if("groupId"===r)continue;const e="number"==typeof s?s:"string"==typeof s&&s.trim().length>0?Number(s):Number.NaN;!r||!Number.isInteger(e)||e<0||o.set(r,{conversationId:t,count:e})}}return Vs("Decoded MSync statistic group read receipts",{receiptDetails:Array.from(o,([e,{conversationId:t,count:r}])=>({messageId:e,conversationId:t,count:r}))}),Array.from(o,([e,{conversationId:t,count:r}])=>({type:"message_receipts",data:{messageIds:[e],conversationId:t,conversationType:"groupChat",timestamp:i,receiptDetails:[{messageId:e,count:r}]}}))}catch{return[]}}decodeStatisticMeta(e){if(!e||"object"!=typeof e)return null;const t=e;if(t.ns!==Jt)return null;const r=t.payload;let s=null;if(r instanceof Uint8Array?s=r:r instanceof ArrayBuffer?s=new Uint8Array(r):ArrayBuffer.isView(r)&&(s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),!s)return null;try{const e=Wd(),t=e.lookupType("easemob.pb.StatisticsBody").decode(s);return{operation:"number"==typeof t.operation?t.operation:-1,reason:"string"==typeof t.reason?t.reason:void 0}}catch{return null}}decodeRosterMeta(e,t){try{const r=Wd(),s=r.lookupType("easemob.pb.RosterBody").decode(t),n="number"==typeof s.operation?s.operation:-1,i=this.readRosterJid(s.from),o=this.readRosterJidList(s.to),a="string"==typeof s.reason?s.reason:"",c="string"==typeof s.rosterVer&&s.rosterVer.trim().length>0?s.rosterVer:void 0,d=i.name??"",u=o[0]?.name??"";if(!d&&!u)return[];const l=Ml({operation:n,from:i,to:o,rosterVersion:c,ext:a,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(l)return[this.createMultiDeviceNotify(l)];const h=this.mapRosterOperationToEvent(n,{from:d,to:u,message:a,rosterVersion:c});return h?[{type:"contact",eventName:h.eventName,data:h.payload}]:[]}catch{return[]}}readRosterJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0}}readRosterJidList(e){return Array.isArray(e)&&0!==e.length?e.map(e=>this.readRosterJid(e)):[]}readJid(e){if(!e||"object"!=typeof e)return{};const t=e;return{name:"string"==typeof t.name?t.name:void 0,clientResource:"string"==typeof t.clientResource?t.clientResource:void 0,domain:"string"==typeof t.domain?t.domain:void 0}}decodeMucMeta(e,t){try{const r=Wd(),s=r.lookupType("easemob.pb.MUCBody").decode(t),n="number"==typeof s.operation?s.operation:-1,i=!0===s.isChatroom,o=!0===s.isThread,a=this.readJid(s.from),c=Array.isArray(s.to)?s.to.map(e=>this.readJid(e)):[],d=s.eventInfo&&"object"==typeof s.eventInfo?s.eventInfo:void 0,u=Array.isArray(s.members)?s.members.filter(e=>"string"==typeof e):[],l=a.name===this.context.userId&&a.clientResource&&a.clientResource!==this.context.clientResource?"multiDevice":"direct";if(o){const t=Ll({operation:n,threadId:this.readJid(s.mucId).name??"",threadName:"string"==typeof s.mucName?s.mucName:void 0,parentId:this.readJid(s.mucParentId).name??void 0,from:a,to:c,members:u,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)];const r=37===n&&c.some(e=>e.name===this.context.userId),i=this.readJid(s.mucId).name??"",o=this.readJid(s.mucParentId).name??"";return r&&i&&o?[{type:"thread",eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:{id:i,name:"string"==typeof s.mucName?s.mucName:void 0,muc_parent_id:o,timestamp:this.readMetaTimestamp(e),from:a.name,userIds:[this.context.userId],operation:"kick"}}}]:[]}if(!i){const t=Ul({operation:n,groupId:this.readJid(s.mucId).name??"",groupName:"string"==typeof s.mucName?s.mucName:void 0,from:a,to:c,reason:"string"==typeof s.reason?s.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,members:u,timestamp:this.readMetaTimestamp(e),raw:s},this.msyncCodecContext());if(t)return[this.createMultiDeviceNotify(t)]}const h=i?Mu({operation:n,chatRoomId:this.readJid(s.mucId).name??"",chatRoomName:"string"==typeof s.mucName?s.mucName:void 0,from:a,to:c,reason:"string"==typeof s.reason?s.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof s.ext?s.ext:void 0,members:u}):ul({operation:n,groupId:this.readJid(s.mucId).name??"",groupName:"string"==typeof s.mucName?s.mucName:void 0,from:a,to:c,reason:"string"==typeof s.reason?s.reason:void 0,eventExt:"string"==typeof d?.ext?d.ext:void 0,ext:"string"==typeof s.ext?s.ext:void 0,members:u,source:l});return h?[{type:i?"chatroom":"group",eventName:i?"onChatRoomNotify":"onGroupNotify",data:h}]:[]}catch{return[]}}mapRosterOperationToEvent(e,t){const r={from:t.from,to:t.to,message:t.message,userInfo:{userId:t.from||t.to}};switch(((e,t)=>{t&&gl.set(e,t)})(r,t.rosterVersion),e){case 2:return{eventName:"onContactInvited",payload:r};case 3:return{eventName:"onContactDeleted",payload:r};case 4:return{eventName:"onContactAdded",payload:r};case 5:case 9:return{eventName:"onContactRefuse",payload:r};case 8:return{eventName:"onContactAgreed",payload:r};default:return null}}decodeNotifyPayload(e){try{let t="";for(let i=0;i<e.length;i+=1){const r=e[i];if(void 0===r)return[];t+=`%${r.toString(16)}`}const r=decodeURIComponent(t),s=JSON.parse(r);Vs("Decoded MSync notify payload",{payload:s});const n="string"==typeof s.type?s.type:"";if(!n)return[];if("thread"===n){return[{type:n,eventName:"onChatThreadChange",data:{eventName:"onChatThreadChange",payload:xh(s.data)?s.data:s}}]}if("conv"===n){const e=xh(s.data)?s.data:s,t=[],r="string"==typeof e.op?e.op:"";if("pin"===r||"pin_delete"===r)return[{type:n,eventName:"onPinnedMessageChanged",data:e}];const i=kl({operation:r,id:"string"==typeof e.id?e.id:"",type:"string"==typeof e.type?e.type:void 0,from:"string"==typeof e.from?e.from:void 0,res:"string"==typeof e.res?e.res:void 0,ts:e.ts,ext:"string"==typeof e.ext?e.ext:void 0,raw:e},this.msyncCodecContext());return i&&t.push(this.createMultiDeviceNotify(i)),t}if("roaming_delete"===n){const e=xh(s.data)?s.data:s,t=Dl({chatType:"string"==typeof e.chatType?e.chatType:void 0,to:"string"==typeof e.to?e.to:void 0,resource:"string"==typeof e.resource?e.resource:void 0,msgIdList:Array.isArray(e.msgIdList)?e.msgIdList.filter(e=>"string"==typeof e):void 0,deleteTime:e.deleteTime,lastMsgId:"string"==typeof e.lastMsgId?e.lastMsgId:void 0,messageRoamingType:"string"==typeof e.messageRoamingType?e.messageRoamingType:void 0,raw:e},this.msyncCodecContext());return t?[this.createMultiDeviceNotify(t)]:[]}if("user_notification_mute"===n){return((e,t)=>{if(!Array.isArray(e)||0===e.length)return[];const r=[];for(const s of e){if(!El(s))continue;const e=wl(s.operator_resource,s.resource,s.clientResource);if(Al(e,t.clientResource))continue;const n=Tl(s.group)??Tl(s.user);if(!n||!El(s.data))continue;const i=Tl(s.group)?_l:bl,o=s.data;r.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:n,conversationType:i,remindType:Tl(o.type),silentMode:o,deviceId:e,raw:s})}return r})(xh(s.data)&&Array.isArray(s.data.values)?s.data.values:Array.isArray(s.values)?s.values:[],this.msyncCodecContext()).map(e=>this.createMultiDeviceNotify(e))}return[{type:n,data:s.data??s}]}catch{return[]}}readMetaTimestamp(e){const t=e.timestamp,r=Number(tu(t));if(Number.isFinite(r)&&r>0)return r}msyncCodecContext(){return{userId:this.context.userId,clientResource:this.context.clientResource}}createMultiDeviceNotify(e){return{type:"multiDevice",eventName:Pl(e.category),data:e}}decodeNotice(e){const t=Wd().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=Wd().lookupType("easemob.pb.CommUnreadDL").decode(e);return{queues:(Array.isArray(t.unread)?t.unread:[]).map(e=>e&&"object"==typeof e?e:null).map(e=>e?.queue&&"object"==typeof e.queue?e.queue:null).filter(e=>Boolean(e))}}encodeBackQueue(e){const t=Wd(),r=t.lookupType("easemob.pb.CommSyncUL"),s=t.lookupType("easemob.pb.MSync"),n=Fh(r,{queue:e}),i={version:0,encryptType:[sr],command:_t,payload:n,traceId:bu()};return Fh(s,i)}encodeLastSession(e,t){const r=Wd(),s=r.lookupType("easemob.pb.CommSyncUL"),n=r.lookupType("easemob.pb.MSync"),i=Fh(s,{queue:e,key:t}),o={version:0,encryptType:[sr],command:_t,payload:i,traceId:bu()};return Fh(n,o)}encodeChatMessage(e,t){const r=Wd(),s=r.lookupType("easemob.pb.CommSyncUL"),n=r.lookupType("easemob.pb.MSync"),i=this.buildChatMeta(e,t),o=Fh(s,{meta:i}),a={version:0,encryptType:[sr],command:_t,payload:o,traceId:bu()};return Fh(n,a)}encodeCombineMessageMeta(e){const t=Wd().lookupType("easemob.pb.Meta"),r=eu(e.msgServerId||e.msgLocalId),s=this.buildChatMeta(e,r,!0);return Fh(t,s)}buildChatMeta(e,t,r=!1){const s=Wd().lookupType("easemob.pb.MessageBody"),n=this.buildContents(e),i=this.resolveMessageProfileVersionFields(e),o=this.buildMessageMeta(e),a=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),c=r?e.from||e.sender.userId:this.context.userId,d=r&&e.to||a.name,u={type:this.resolveChatType(e),from:{name:c},to:{name:d},contents:n,ext:ru(e.ext??{}),...o?{meta:o}:{},...i,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},l=Fh(s,u),h="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",p=this.resolveDirectedUsers(e),m=this.resolveMetaExt(e);return{id:t,to:Xd({appKey:this.context.appKey,name:d,domain:h,clientResource:r?void 0:a.clientResource}),...r?{timestamp:e.timestamp}:{},ns:Qt,payload:l,routetype:this.resolveRouteType(e),directedUsers:p,ext:m,...void 0!==e.webhookEnv?{env:e.webhookEnv}:{}}}encodeActionMessage(e,t){const r=Wd(),s=r.lookupType("easemob.pb.MessageBody"),n=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),o=r.lookupEnum("easemob.pb.MessageBody.EditScope"),a=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),c=e.body&&e.messageType?[this.buildContent({msgServerId:e.messageId??"",msgLocalId:t,from:this.context.userId,to:e.conversationId,sender:{userId:this.context.userId},conversationId:e.conversationId,conversationType:e.conversationType,type:e.messageType,sendStatus:"sending",ext:e.ext??{},timestamp:Date.now(),body:e.body})]:[],d={type:this.resolveActionMessageType(e),from:{name:this.context.userId},to:{name:a.name},contents:c,ext:ru(e.ext??{})};if("recall"!==e.kind&&"deliveryAck"!==e.kind||(d.ackMessageId=e.messageId),"sendMessageReadReceipts"===e.kind&&(d.ackMessageIds=e.messageIds,"groupChat"===e.conversationType&&(d.msgConfig={allowGroupAck:!0})),"clearConversationUnreadMessageCount"===e.kind&&(d.sendToPeer=e.sendToPeer??!1),"clearAllConversationUnreadMessageCount"===e.kind&&(d.sendToPeer=e.sendToPeer??!1,d.clearAllUnreadMessageCount=e.clearAllUnreadMessageCount??!0),"update"===e.kind){d.editMessageId=e.messageId,d.editScope=e.ext&&Object.keys(e.ext).length>0?o.values.BODY_AND_EXT:o.values.BODY;const t=this.buildMessageMetaFromBody(e.messageType,e.body);t&&(d.meta=t)}const u=Fh(s,d);if("clearAllConversationUnreadMessageCount"===e.kind){const e=s.decode(u),r=s.fields.clearAllUnreadMessageCount;Vs("Clear-all unread MessageBody wire encoded",{operation:"msync.action.clear-all-unread.wire",protocolId:t,messageType:d.type,fieldId:r?.id,requestedValue:d.clearAllUnreadMessageCount,decodedHasField:Object.prototype.hasOwnProperty.call(e,"clearAllUnreadMessageCount"),decodedValue:e.clearAllUnreadMessageCount,messageBodyBytes:u.byteLength,wireTailHex:Array.from(u.slice(-16),e=>e.toString(16).padStart(2,"0")).join(" ")})}const l={id:t,to:Xd({appKey:this.context.appKey,name:a.name,domain:"singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",clientResource:a.clientResource}),ns:Qt,payload:u,routetype:er,directedUsers:[],ext:[]},h=Fh(n,{meta:l}),p={version:0,encryptType:[sr],command:_t,payload:h,traceId:bu()};return Fh(i,p)}encodeChatRoomOperation(e,t){const r=Wd(),s=r.lookupType("easemob.pb.MUCBody"),n=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),o={mucId:Xd({appKey:this.context.appKey,name:e.chatRoomId,domain:"conference.easemob.com"}),operation:"join"===e.operation?2:3,from:{name:this.context.userId},isChatroom:!0};"join"===e.operation&&(void 0!==e.ext&&(o.ext=e.ext),void 0!==e.leaveOtherRooms&&(o.leaveOtherRooms=e.leaveOtherRooms));const a=Fh(s,o),c={id:t,from:Xd({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:Zt,payload:a},d=Fh(n,{meta:c}),u={version:0,encryptType:[sr],command:_t,payload:d,traceId:bu()};return Fh(i,u)}decodeServerMessageMeta(e){const t=Wd(),r=t.lookupType("easemob.pb.Meta"),s=t.lookupType("easemob.pb.MessageBody");try{const t=r.decode(e);return this.decodeChatMeta(t,s)}catch{return null}}async normalizeIncoming(e){if(e instanceof Uint8Array)return e;if(t=e,"[object ArrayBuffer]"===Object.prototype.toString.call(t))return new Uint8Array(e);var t;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if((e=>"undefined"!=typeof Blob&&e instanceof Blob||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(e)){const t=await e.arrayBuffer();return new Uint8Array(t)}return"string"==typeof e?Hs(e):e&&"object"==typeof e&&"data"in e?this.normalizeIncoming(e.data):new Uint8Array}decompressIncoming(e){if(!this.compressor||!this.compressor.enableDownlinkCompression)return e;try{return this.compressor.decompress(e)}catch{return this.compressionFailureCount+=1,null}}prepareOutgoing(e){if(!this.compressor||!this.compressor.enableUplinkCompression)return e;try{return this.compressor.compress(e)}catch{throw this.compressionFailureCount+=1,new Error("compress outgoing message failed")}}resetCompressionNegotiation(){this.compressor?.reset(),this.disableCompression()}toProtocolId(e){return eu(e)}decodeChatRoomJoinInfo(e){const t=Wd().lookupType("easemob.pb.MUCBody");for(const s of e){if(!xh(s)||s.ns!==Zt)continue;const e=s.payload,n=e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0;if(n)try{const e=t.decode(n);if(!xh(e)||!xh(e.status))continue;const r=e.status.chatroomInfo;if("string"!=typeof r||""===r)continue;const s=JSON.parse(r);if(!xh(s))continue;const i=s[this.context.userId];if(!xh(i))continue;const o=i;return{..."boolean"==typeof o.is_all_mute?{isAllMembersMuted:o.is_all_mute}:{},..."number"==typeof o.create_timestamp?{createTimestamp:o.create_timestamp}:{},..."boolean"==typeof o.is_in_white_list?{isInAllowlist:o.is_in_white_list}:{},..."number"==typeof o.member_count?{memberCount:o.member_count}:{},muteExpireTimestamp:"number"==typeof o.mute_duration&&0!==o.mute_duration?o.mute_duration:-1}}catch(r){zs("Failed to decode chat room info from ACK",r)}}}decodeAck(e){const t=tu(e.metaId);if(!t||"0"===t)return;const r=e.status??{},s="number"==typeof r.errorCode?r.errorCode:ar,n="string"==typeof r.reason?r.reason:void 0;return{protocolId:t,serverId:tu(e.serverId),ok:s===or,statusCode:s,reason:n}}decodeMessage(e,t){const r="number"==typeof t.type?t.type:At;if(!this.isPublicMessageType(r))return null;const s=Array.isArray(t.contents)?t.contents.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)):[];if(0===s.length)return null;const n=this.resolveConversationType(r),{senderUserId:i,senderId:o,receiverId:a}=this.resolveIncomingMessageParties(e,t,n),c=o===this.context.userId?"SEND":"RECEIVE",d="singleChat"===n?"SEND"===c?a:o:a,u=this.payloadDecoder.decodeMetadata(t,n,c,e.meta),l=u.stream&&s.length>=2?lu(s,"stream content is not composed into a multi_body message"):s,h=this.payloadDecoder.resolveMessageMetaPayload(t.meta,e.meta),p=pu(l,e=>this.decodeContent(e,h));if(!p)return null;const m=su(t.ext),g=su(e.ext),f=Number(tu(e.timestamp))||Date.now(),y=tu(e.id),v=this.resolveBroadcast(g),I=this.resolvePriority(g),b=this.resolveProfileVersionTime(t.userInfoUpdateTime),_=this.resolveProfileVersionTime(t.namecardUpdateTime);let T={...{msgServerId:y,msgLocalId:"",from:o,to:a,sender:{userId:i},conversationId:d,conversationType:n,sendStatus:"sent",ext:m,timestamp:f,direct:c,isOnline:this.resolveMessageIsOnline(r,g)},type:p.type,body:p.body};hl(T,{userInfoUpdateTime:b,namecardUpdateTime:_});const C=u.stream;if(C&&"multi_body"!==p.type&&"multi_body"!==T.type){const e={...T,type:"text",body:{content:C.fullText},stream:C};ml(T,e),T=e}return void 0!==v&&(T.isBroadcast=v),void 0!==I&&(T.priority=I),Object.assign(T,u),T}resolveMessageProfileVersionFields(e){const t=pl(e),r={};return"number"==typeof t?.userInfoUpdateTime&&(r.userInfoUpdateTime=t.userInfoUpdateTime),"groupChat"===e.conversationType&&"number"==typeof t?.namecardUpdateTime&&(r.namecardUpdateTime=t.namecardUpdateTime),r}buildMessageMeta(e){const t={};if("text"===e.type){const r=this.buildTranslationsMeta(e.body);r&&Object.assign(t,r)}return e.isChatThread&&(t.thread={}),Object.keys(t).length>0?JSON.stringify(t):""}buildMessageMetaFromBody(e,t){if("text"!==e||!t||Array.isArray(t)||!("translations"in t))return"";const r=this.buildTranslationsMeta(t);return r?JSON.stringify(r):""}buildTranslationsMeta(e){if(Array.isArray(e)||!("translations"in e))return null;const t=(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})))(e.translations);return t.length>0?{translations:t}:null}resolveProfileVersionTime(e){return Fl(tu(e))}isPublicMessageType(e){return e===At||e===Rt||e===Nt}resolveMessageIsOnline(e,t){if(e===Nt)return!0;const r=t.is_online;return"boolean"==typeof r?r:"number"==typeof r?0!==r:"string"!=typeof r||"0"!==r}buildContents(e){if("multi_body"!==e.type)return[this.buildContent(e)];const t=e.body;if(!Array.isArray(t)||t.length<2)throw new Error("multi_body message requires at least 2 bodies");return Vs("MultiBody message encoded as contents",{operation:"message.multibody.encode",msgLocalId:e.msgLocalId,segmentCount:t.length,segmentTypes:t.map(e=>e.type)}),t.map(t=>this.buildContent({...e,type:t.type,body:t}))}buildContent(e){if("multi_body"===e.type)throw new Error("multi_body message must be encoded as multiple contents");if("text"===e.type){const t=e.body;return{type:Dt,text:t.content}}if("cmd"===e.type){const t=e.body;return{type:qt,action:t.action}}if("custom"===e.type){const t=e.body;return{type:$t,customEvent:t.event,customExts:ru(t.params??{})}}if("location"===e.type){const t=e.body;return{type:Ft,latitude:t.latitude,longitude:t.longitude,address:t.address,buildingName:t.buildingName}}if("image"===e.type){const r=e.body,s=r.isGif||r.isOriginalImage?"original":"large";return{type:Pt,displayName:r.filename,remotePath:r.originalImageUrl??"",imageType:(t=s,t===ps?1:2),secretKey:r.secret,fileLength:r.fileLength,size:{width:r.width,height:r.height},subType:r.isGif?1:void 0,thumbnailRemotePath:r.thumbnailUrl,thumbnailDisplayName:r.filename}}var t;if("video"===e.type){const t=e.body;return{type:xt,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,duration:t.duration,size:t.width&&t.height?{width:t.width,height:t.height}:void 0,thumbnailRemotePath:t.thumbnailUrl,thumbnailSecretKey:t.secret,thumbnailDisplayName:t.filename}}if("voice"===e.type){const t=e.body;return{type:Bt,displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,duration:t.duration,thumbnailDisplayName:t.filename}}if("combine"===e.type){const t=e.body;return{type:Dt,subType:0,text:vl(e)??"版本过低",displayName:t.filename,remotePath:t.url,secretKey:t.secret,fileLength:t.fileLength,title:t.title,summary:t.summary,combineLevel:t.combineLevel}}const r=e.body;return{type:Gt,displayName:r.filename,remotePath:r.url,secretKey:r.secret,fileLength:r.fileLength,thumbnailDisplayName:r.filename}}decodeContent(e,t){return this.payloadDecoder.decodeContent(e,t)}resolveChatType(e){switch(e.conversationType){case"groupChat":return Rt;case"chatRoom":return Nt;default:return At}}resolveActionConversationType(e,t,r){const s=this.resolveConversationTypeFromMeta(t);if(s)return s;const n=r?.msgConfig&&"object"==typeof r.msgConfig?r.msgConfig:null;return!0===n?.allowGroupAck||"conference.easemob.com"===e?"groupChat":"singleChat"}resolveConversationTypeFromMeta(e){if("string"!=typeof e||0===e.length)return null;try{const t=JSON.parse(e),r=t.edit_msg&&"object"==typeof t.edit_msg?t.edit_msg:void 0,s=("string"==typeof t.chat_type?t.chat_type:void 0)??("string"==typeof t.chatType?t.chatType:void 0)??("string"==typeof t.type?t.type:void 0)??("string"==typeof r?.chat_type?r.chat_type:void 0);if("chat:user"===s||"singleChat"===s)return"singleChat";if("chat:group"===s||"groupChat"===s)return"groupChat";if("chat:room"===s||"chatRoom"===s)return"chatRoom"}catch{}return null}resolveActionConversationId(e,t,r){return"singleChat"===r?e===this.context.userId?t:e:t}resolveOutboundMessageTarget(e,t){if("singleChat"!==t)return{name:e};const r=`${this.context.userId}/`;if(!e.startsWith(r))return{name:e};const s=e.slice(r.length);return s?{name:this.context.userId,clientResource:s}:{name:e}}resolveIncomingMessageParties(e,t,r){const s=this.readJid(e.from),n=this.readJid(e.to),i=Iu(t.from,e.from),o=Iu(t.to,e.to);if(!("singleChat"===r&&i===this.context.userId&&o===this.context.userId))return{senderUserId:i,senderId:i,receiverId:o};return{senderUserId:i,senderId:s.clientResource&&s.clientResource!==this.context.clientResource?`${i}/${s.clientResource}`:i,receiverId:n.clientResource?`${o}/${n.clientResource}`:o}}resolveActionMessageType(e){switch(e.kind){case"clearConversationUnreadMessageCount":case"clearAllConversationUnreadMessageCount":return Lt;case"sendMessageReadReceipts":return Ot;case"deliveryAck":return Mt;case"recall":return Ut;case"update":return kt;default:return At}}resolveConversationType(e){return e===Rt?"groupChat":e===Nt?"chatRoom":"singleChat"}resolveDirectedUsers(e){return"singleChat"===e.conversationType?[]:Array.isArray(e.receiverList)?e.receiverList:[]}resolveDeliverOnlineOnly(e){if("boolean"==typeof e.deliverOnlineOnly)return e.deliverOnlineOnly;if("cmd"===e.type){const t=e.body;return Boolean(t.deliverOnlineOnly)}return!1}resolveMetaExt(e){return"chatRoom"!==e.conversationType?[]:e.priority?ru({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?rr:this.resolveDeliverOnlineOnly(e)?tr:er}resolveBroadcast(e){if(!Object.prototype.hasOwnProperty.call(e,"is_broadcast"))return;const t=e.is_broadcast;return"boolean"==typeof t?t:"number"==typeof t?0!==t:"string"==typeof t?"1"===t||"true"===t.toLowerCase():Boolean(t)}resolvePriority(e){if(!Object.prototype.hasOwnProperty.call(e,"chatroom_msg_tag"))return;const t=Number(e.chatroom_msg_tag);return 0===t?"high":2===t?"low":"normal"}mapPriorityToTag(e){return"high"===e?0:"low"===e?2:1}getRequestedCompressTypes(){return this.compressionFailureCount>=this.maxCompressionFailures?[]:[ir]}configureCompression(e,t){if(!e||!e.includes(ir))return void this.disableCompression();this.compressor||(this.compressor=new Ph);const r=this.resolveCompressionMode(t);this.compressor.mode=r,this.compressor.enableUplinkCompression=r===kh.UPLINK_ONLY||r===kh.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=r===kh.DOWNLINK_ONLY||r===kh.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?kh.UPLINK_ONLY:1===e?kh.DOWNLINK_ONLY:2===e?kh.BIDIRECTIONAL:kh.NONE}disableCompression(){this.compressor&&(this.compressor.mode=kh.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}const Gh=1e3,qh="direct";class $h{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 r=0;r<this.events.length;r+=1){const s=this.events[r];s&&s.appKey===e&&(this.events[r]={appKey:t,wire:{...s.wire,body:{...s.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 r=0;r<this.events.length&&t.length<this.batchSize;){const s=this.events[r];s?.appKey===e.appKey?(t.push(s.wire),this.events.splice(r,1)):r+=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 jh{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 r=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});(r.status<200||r.status>=300)&&this.onFailure?.({reason:"non-success-response",status:r.status})}catch(r){this.onFailure?.({reason:"transport-error",message:r instanceof Error?r.message:String(r)})}else this.onFailure?.({reason:"request-adapter-unavailable",eventCount:t.length})}}const Vh={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},Kh=()=>{const e=fn(),t=e.crypto?.randomUUID;return("function"==typeof t?t.call(e.crypto):void 0)??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class zh{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??Kh;const t=new jh({requestAdapter:e.requestAdapter,debug:e.debug,now:this.now,onFailure:t=>{e.onDiagnostic?.("DataReport transport failed",t)}}),r=e.send??((e,r)=>t.send(e,r));this.queue=new $h({send:r,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:Vh[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 r=`opr_${this.randomId()}`,s=this.now();let n=!1,i=!1,o=`req_${this.randomId()}`,a=0,c="";const d=()=>!n&&!i&&this.session?.sessionId===t,u=(t,s,n,i,o)=>{d()&&(a=o.success?0:o.code,c=o.success?"":o.description??"",this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:r,requestid:s,operationName:e.operationName,operationType:e.operationType,requestName:t.requestName??e.operationName,subrequestid:String(n),requestMethod:t.method??"",requestUrl:t.url??"",requestElapse:Math.max(0,this.now()-i),code:o.code,codeDesc:o.description??"",isLastApi:0,isSuccess:o.success?1:0,accessChannel:this.session?.accessChannel??qh,msgId:e.msgId,messageType:e.messageType,resultCount:o.resultCount}))},l=(e,t,r,s)=>{const n=this.now();let i=!1;return{retry:()=>(s.next+=1,l(e,t,s.next,s)),finish:s=>{i||(i=!0,u(e,t,r,n,s))}}};return{startRequest:(e={})=>(o=`req_${this.randomId()}`,l(e,o,1,{next:1})),finish:t=>{d()&&(n=!0,this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:r,requestid:o,operationName:e.operationName,operationType:e.operationType,requestName:"",subrequestid:"0",requestMethod:"",requestUrl:"",requestElapse:Math.max(0,this.now()-s),code:t.success?0:t.code??a,codeDesc:t.success?"":t.description??c,isLastApi:1,isSuccess:t.success?1:0,accessChannel:this.session?.accessChannel??qh,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 r=this.session;if(!r||"disabled"===this.currentState)return;const s={lts:this.now(),net:this.networkType,appkey:r.appKey,sdkServiceId:r.serviceId,sdkProduct:0,uikitVersion:r.uikitVersion??"",...t},n={eventId:e,body:Object.fromEntries(Object.entries(s).filter(([,e])=>void 0!==e))};this.queue.enqueue({appKey:r.appKey,wire:n})}createNoopOperation(){const e={retry:()=>e,finish:()=>{}};return{startRequest:()=>e,finish:()=>{},discard:()=>{}}}}let Hh;const Wh=e=>{Hh?.updateSession(e)},Jh=e=>{Hh?.applyDnsSwitch(e)},Qh=e=>{Hh?.updateNetworkType(e)},Zh=e=>{if("disabled"!==Hh?.state)return Hh?.startOperation(e)},Yh=()=>{Hh?.reset(),Hh=void 0},Xh=e=>new ht("Connection attempt cancelled",{code:ot.CONNECTION_CANCELLED,details:{stage:e,cancelled:!0,retryable:!0}}),ep=e=>e instanceof ht&&e.code===ot.CONNECTION_CANCELLED&&!0===e.details?.cancelled;class tp{constructor(e,r){this.serverUrlIndex=0,this.websocket=null,this.provisionTimeoutId=null,this.reconnectAttempts=0,this.messageReceiver=null,this.provisionPromise=null,this.provisionResolve=null,this.provisionReject=null,this.queues=[],this.currentQueueId=null,this.currentQueue=null,this.nextKey=null,this.offlineMessageSyncing=!1,this.offlineMessageSyncLifecycleDispatched=!1,this.offlineMessageSyncLifecycleActive=!1,this.offlineMessageQueueNames=new Set,this.offlineMessageQueueReports=new Map,this.offlineMessageQueueCounts=new Map,this.offlineMessageTotalCount=0,this.reconnectTimerId=null,this.reconnectDelayReject=null,this.reconnectTask=null,this.pendingReconnectReason=null,this.reconnectInProgress=!1,this.reconnectPaused=!1,this.terminalDisconnectError=null,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.hasEverConnected=!1,this.isOnline=!0,this.internalHandlerId="__internal:connection-manager",this.suppressNextCloseEvent=!1,this.socketDisposers=[],this.inboundMessageQueue=Promise.resolve(),this.socketGeneration=0,this.connectionAttemptGeneration=0,this.activeConnectionAttemptCancel=null,this.activeLoginDeadline=null,this.tokenLifecycle=null,this.tokenWillExpireTimerId=null,this.tokenExpiredTimerId=null,this.config={heartBeatWait:3e4,autoReconnectNumMax:10,connectTimeout:1e4,...e},this.eventHub=r,this.msyncCodec=new Bh({appKey:e.appKey,useCustomAttachmentUpload:e.useCustomAttachmentUpload,userId:e.userId,token:e.token,useReplacedMessageContents:e.useReplacedMessageContents,useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,serviceId:e.serviceId}),this.serverUrls=this.normalizeServerUrls(e),this.config.serverUrl=this.serverUrls[0]??this.config.serverUrl,this.connection={status:t,serverUrl:this.config.serverUrl,userId:e.userId,token:e.token,reconnectAttempts:0},this.connectionRetry=new qd({maxAttempts:this.config.autoReconnectNumMax,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2}),this.heartbeatManager=new Kd({interval:this.config.heartBeatWait,timeout:6e4}),this.connectionEventNormalizer=new Js,this.socketAdapter=this.resolveSocketAdapter(e),this.isOnline="undefined"==typeof navigator||navigator.onLine,this.eventHub.addEventHandler(this.internalHandlerId,{[m]:e=>{this.handleSendTimeout(e)}})}getConnectionStatus(){return this.connection.status}getWebSocket(){return this.websocket}getMsyncCodec(){return this.msyncCodec}getClientResource(){return this.msyncCodec.getContext().clientResource}setMessageReceiver(e){this.messageReceiver=e}renewToken(e,t){const r=Date.now();if(t<=r)throw new ht("Token is expired",{code:ot.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});return this.config.token=e,this.connection.token=e,this.msyncCodec.updateToken(e),this.setupTokenLifecycle(e,t,r),Ks("Connection token renewed",{userId:this.config.userId,expireAt:t}),{token:e,expireAt:t}}handleOnline(){if(Ks("Network online event received",this.getReconnectDiagnostic()),this.isOnline=!0,this.terminalDisconnectError)return void Ks("Network online recovery skipped",{guard:"terminal-disconnect",...this.getReconnectDiagnostic()});const e=this.offlineRecoverPending?C:T;this.offlineRecoverPending=!1,this.resumeReconnect(e)}handleOffline(){Ks("Network offline event received",this.getReconnectDiagnostic()),this.isOnline=!1,this.offlineRecoverPending=!0,this.reconnectPaused=!0,this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.stopHeartbeat(),this.closeWebSocket(N,!0),Ks("Network offline state applied",this.getReconnectDiagnostic())}async handleForeground(){if(this.terminalDisconnectError)return void Ks("Foreground recovery skipped",{guard:"terminal-disconnect",...this.getReconnectDiagnostic()});if(!this.isLoggedIn)return;if(!this.isOnline)return;if(this.reconnectInProgress)return void Ks("Foreground recovery skipped",{guard:"reconnect-in-progress",...this.getReconnectDiagnostic()});const e=this.websocket;try{if(!(await this.checkHeartbeatOnce())){if(this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(S,!0,!0),this.resumeReconnect(S)}}catch(t){if(Ks("Foreground heartbeat check failed",t),this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(S,!0,!0),this.resumeReconnect(S)}}resumeReconnect(e){if(this.terminalDisconnectError)Ks("Reconnect recovery skipped",{guard:"terminal-disconnect",reason:e,...this.getReconnectDiagnostic()});else if(this.isLoggedIn)return this.reconnectTask||this.reconnectInProgress?(this.pendingReconnectReason=e,void Ks("Reconnect recovery queued",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()})):void(this.connection.status===s&&this.websocket||(this.reconnectPaused=!1,this.resetReconnectState(),Ks("Reconnect recovery requested",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e)))}handleSendTimeout(e){this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||e.reason===E&&Ks("Message send timeout received without reconnect",e))}resetReconnectState(){this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connectionRetry.reset()}getReconnectDiagnostic(){return{status:this.connection.status,isOnline:this.isOnline,isLoggedIn:this.isLoggedIn,isLoginPhase:this.isLoginPhase,reconnectInProgress:this.reconnectInProgress,reconnectPaused:this.reconnectPaused,terminalDisconnectCode:this.terminalDisconnectError?.code,offlineRecoverPending:this.offlineRecoverPending,reconnectAttempts:this.reconnectAttempts,hasWebSocket:null!==this.websocket,hasReconnectTimer:null!==this.reconnectTimerId,hasReconnectTask:null!==this.reconnectTask,hasActiveConnectionAttempt:null!==this.activeConnectionAttemptCancel}}normalizeServerUrls(e){const t=(e.serverUrls??[]).filter(e=>"string"==typeof e&&e.length>0);return t.length>0?[...t]:[e.serverUrl]}pickNextServerUrl(){if(0===this.serverUrls.length)return this.config.serverUrl;const e=this.serverUrlIndex%this.serverUrls.length,t=this.serverUrls[e]??this.config.serverUrl;return this.serverUrlIndex=(e+1)%this.serverUrls.length,this.config.serverUrl=t,this.connection.serverUrl=t,t}resolveEffectiveMaxAttempts(){return this.isLoginPhase&&0===this.config.autoReconnectNumMax?1:this.config.autoReconnectNumMax}isNonRetryableError(e){if(!(e instanceof ht))return!1;const t=e.details;if(!t||"object"!=typeof t)return!1;return!1===t.retryable}isServerNormalClosePayload(e){if(e.length>64)return!1;let t;try{t=JSON.parse(Ws(e))}catch{return!1}return!(!Array.isArray(t)||t.length<2)&&(3e3===t[0]&&"normal closed"===t[1])}clearReconnectTimer(){const e=this.reconnectDelayReject;this.reconnectDelayReject=null,this.reconnectTimerId&&(clearTimeout(this.reconnectTimerId),this.reconnectTimerId=null),e?.(Xh("retry-delay"))}resolveLoginStageTimeout(e){return this.isLoginPhase&&this.activeLoginDeadline?this.activeLoginDeadline.clamp(e):e}isLoginDeadlineExpired(){return Boolean(this.isLoginPhase&&this.activeLoginDeadline&&this.activeLoginDeadline.remainingMs()<=0)}requireLoginTimeoutError(){const e=this.activeLoginDeadline;return e?(e.expire(),e.createTimeoutError()):new ht("Login timeout",{code:ot.CONNECTION_LOGIN_TIMEOUT,details:{stage:"login",retryable:!0}})}async waitForReconnectDelay(){const e=this.connectionRetry.getRetryDelay(),t=this.resolveLoginStageTimeout(e);if(t<=0)throw this.requireLoginTimeoutError();Ks("Reconnect retry scheduled",{delayMs:Math.round(t),...this.getReconnectDiagnostic()}),this.clearReconnectTimer(),await new Promise((e,r)=>{this.reconnectDelayReject=e=>{this.reconnectDelayReject=null,r(e)},this.reconnectTimerId=setTimeout(()=>{this.reconnectTimerId=null,this.reconnectDelayReject=null,e()},t)})}buildConnectionEventPayload(e,t){const r=this.connection.error instanceof ht?this.connection.error:void 0;return{state:e,reason:t,attempt:this.reconnectAttempts,maxAttempts:this.resolveEffectiveMaxAttempts(),isLoginPhase:this.isLoginPhase,isOnline:this.isOnline,errorCode:r?.code,errorMessage:r?.message,timestamp:Date.now()}}dispatchConnectionEvent(e,r){if(e===t&&!this.hasEverConnected)return;if(e===i&&!this.isLoggedIn)return;if(this.isLoginPhase&&(e===t||e===i))return;const s=this.buildConnectionEventPayload(e,r),n=this.connectionEventNormalizer.normalize(e,s);n&&this.eventHub.dispatch(n.eventName,n.payload)}updateStatus(e,t,r,n=!1){const i=this.connection.status!==e;(i||n)&&(i&&(this.connection.status=e,this.connection.lastConnectedAt=e===s?Date.now():void 0),r&&this.dispatchConnectionEvent(e,t),Vs("Connection status updated",{status:e,reason:t,attempt:this.reconnectAttempts,forceEmit:n}))}clampTimerDelay(e){return e<=0?0:Math.min(e,2**31-1)}clearTokenTimers(){this.tokenWillExpireTimerId&&(clearTimeout(this.tokenWillExpireTimerId),this.tokenWillExpireTimerId=null),this.tokenExpiredTimerId&&(clearTimeout(this.tokenExpiredTimerId),this.tokenExpiredTimerId=null)}setupTokenLifecycle(e,t,r=Date.now()){this.clearTokenTimers();const s=Math.max(t-r,0),n=r+Math.floor(.8*s);this.tokenLifecycle={token:e,issuedAt:r,expireAt:t,willExpireAt:n,willExpireEmitted:!1,expiredEmitted:!1},this.tokenWillExpireTimerId=setTimeout(()=>{this.emitTokenWillExpire()},this.clampTimerDelay(n-Date.now())),this.tokenExpiredTimerId=setTimeout(()=>{this.handleTokenExpiredDisconnect("timer")},this.clampTimerDelay(t-Date.now()))}setupTokenLifecycleFromProvision(e){if(e&&!this.tokenWillExpireTimerId&&!this.tokenExpiredTimerId)try{const t=JSON.parse(e);if(!t||"object"!=typeof t)return void Ks("Provision auth token has invalid payload");const r=Number(t.expires_in);if(!Number.isFinite(r))return void Ks("Provision auth token has invalid expires_in");this.setupTokenLifecycle(this.connection.token??this.config.token,r)}catch(t){Ks("Failed to parse provision auth token expiration",t)}}emitTokenWillExpire(){this.tokenLifecycle&&!this.tokenLifecycle.willExpireEmitted&&(this.tokenLifecycle.willExpireEmitted=!0,Ks("Token will expire"),this.eventHub.dispatch(u,void 0))}emitTokenExpired(){this.tokenLifecycle||(this.tokenLifecycle={token:this.connection.token??"",issuedAt:Date.now(),expireAt:Date.now(),willExpireAt:Date.now(),willExpireEmitted:!0,expiredEmitted:!1});const e=this.tokenLifecycle;e.expiredEmitted||(e.expiredEmitted=!0,Ks("Token expired"),this.eventHub.dispatch(l,void 0))}isTokenExpiredConnectionError(e){return e instanceof ht&&e.code===ot.AUTH_TOKEN_EXPIRED}handleTokenExpiredDisconnect(e){Ks("Connection closing because token expired",{source:e}),this.connection.error=new ht("Token expired",{code:ot.AUTH_TOKEN_EXPIRED,details:{stage:"token",source:e,retryable:!1}}),this.emitTokenExpired(),this.clearTokenTimers(),this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.closeWebSocket(O,!0,!0),this.updateStatus(t,O,!0)}startHeartbeat(e){this.heartbeatManager.start(e,()=>{this.triggerReconnect(S)},()=>{this.sendHeartbeatPing()})}stopHeartbeat(){this.heartbeatManager.stop()}async checkHeartbeatOnce(){return!!this.websocket&&this.heartbeatManager.probeOnce(this.websocket,6e4)}sendHeartbeatPing(){const e=this.msyncCodec.encodeHeartbeat();this.sendMsyncPayload(e)}async connect(e){if(!this.reconnectInProgress)if(this.connection.status!==s&&this.connection.status!==r){this.isLoginPhase=!0,this.activeLoginDeadline=e??null,this.terminalDisconnectError=null,this.reconnectPaused=!1,this.resetReconnectState(),this.connectionEventNormalizer.reset();try{await this.connectWithRetry(b,!0),this.isLoggedIn=!0}catch(n){throw this.isLoggedIn=!1,n instanceof ht&&n.code===ot.CONNECTION_LOGIN_TIMEOUT&&"login"===n.details?.stage&&(this.cancelActiveConnectionAttempt(),this.closeWebSocket(A,!1,!1),this.updateStatus(t,A,!1)),n}finally{this.isLoginPhase=!1,this.activeLoginDeadline=null}}else Ks("Connection already established or connecting")}async connectWithRetry(e,o){if(Ks("Reconnect flow requested",{reason:e,throwOnFailure:o,...this.getReconnectDiagnostic()}),this.reconnectInProgress)return void Ks("Reconnect flow skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()});if(this.connection.status===s&&this.websocket)return;if(this.reconnectPaused)return void Ks("Reconnect flow skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()});if(!this.isLoginPhase&&0===this.config.autoReconnectNumMax)return;if(!this.isOnline&&!this.isLoginPhase)return;this.reconnectInProgress=!0;let a=null,c=null,d=null;const u=this.resolveEffectiveMaxAttempts();this.connectionRetry.reset(),Ks("Reconnect flow started",{reason:e,throwOnFailure:o,maxAttempts:u,...this.getReconnectDiagnostic()});try{for(;this.connectionRetry.getAttemptCount()<u;){if(this.isLoginDeadlineExpired())throw this.requireLoginTimeoutError();if(!this.isLoginPhase&&(this.reconnectPaused||!this.isOnline||!this.isLoggedIn)){d=Xh("ws");break}this.connectionRetry.recordAttempt(),this.reconnectAttempts=this.connectionRetry.getAttemptCount(),this.connection.reconnectAttempts=this.reconnectAttempts;const t=this.isLoginPhase?r:n;Ks("Reconnect attempt started",{attempt:this.reconnectAttempts,maxAttempts:u,reason:e,nextStatus:t,...this.getReconnectDiagnostic()}),this.updateStatus(t,e,!0,!0),this.prepareForConnectAttempt();try{return await this.connectOnce(),void this.handleConnectSuccess(e)}catch(l){if(a=l,this.isLoginDeadlineExpired())throw this.requireLoginTimeoutError();if(ep(l)){d=l,Ks("Reconnect attempt cancelled",{attempt:this.reconnectAttempts,reason:e,...this.getReconnectDiagnostic()});break}if(Ks("Connection attempt failed",{attempt:this.reconnectAttempts,reason:e,error:a}),!this.isLoginPhase&&this.isTokenExpiredConnectionError(a))return void this.handleTokenExpiredDisconnect("server");if(this.isNonRetryableError(a)){c=a;break}}if(this.connectionRetry.getAttemptCount()>=u)break;if(this.reconnectPaused||!this.isOnline&&!this.isLoginPhase){Ks("Reconnect retry loop interrupted",{reason:e,attempt:this.reconnectAttempts,maxAttempts:u,...this.getReconnectDiagnostic()});break}try{await this.waitForReconnectDelay()}catch(l){if(!ep(l))throw l;d=l,Ks("Reconnect retry delay cancelled",{reason:e,attempt:this.reconnectAttempts,...this.getReconnectDiagnostic()});break}}if(d){if(o)throw d;return}if(c){if(this.connection.error=c,o)throw this.updateStatus(t,A,!1),c;return this.reconnectPaused=!0,void this.updateStatus(t,A,!0)}if(o)throw this.updateStatus(t,A,!1),a??new ht("Connection failed",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.reconnectPaused=!0,Ks("Reconnect attempts exhausted",{reason:e,attempt:this.reconnectAttempts,maxAttempts:u,lastError:a,...this.getReconnectDiagnostic()}),this.updateStatus(i,R,!0)}finally{this.reconnectInProgress=!1,Ks("Reconnect flow finished",{reason:e,...this.getReconnectDiagnostic()})}}async connectOnce(){await this.createWebSocketConnection()}prepareForConnectAttempt(){this.cancelActiveConnectionAttempt(),this.clearReconnectTimer(),this.stopHeartbeat(),this.resetProvisionHandlers(),this.resetSyncState(),this.websocket&&this.closeWebSocket(_,!1,!1),this.msyncCodec.resetCompressionNegotiation()}handleConnectSuccess(e){this.updateStatus(s,e,!0),this.hasEverConnected=!0,this.connection.error=void 0,this.resetReconnectState(),this.offlineRecoverPending=!1,this.reconnectPaused=!1,this.sendPostProvisionInitialSync(),this.websocket&&this.startHeartbeat(this.websocket),Ks("Connection established successfully")}sendPostProvisionInitialSync(){this.sendMsyncPayload(this.msyncCodec.encodeHeartbeat()),this.sendMsyncPayload(this.msyncCodec.encodeStatisticRebuild())}triggerReconnect(e){if(Ks("Reconnect trigger received",{reason:e,...this.getReconnectDiagnostic()}),this.terminalDisconnectError)return Ks("Reconnect trigger skipped",{guard:"terminal-disconnect",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(!this.isLoggedIn)return Ks("Reconnect trigger skipped",{guard:"not-logged-in",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(this.reconnectTask)return Ks("Reconnect task reused",{reason:e,...this.getReconnectDiagnostic()}),this.reconnectTask;if(this.reconnectInProgress)return Ks("Reconnect trigger skipped",{guard:"reconnect-in-progress-without-task",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();if(this.reconnectPaused)return Ks("Reconnect trigger skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()}),Promise.resolve();this.connection.status===s&&this.websocket&&this.closeWebSocket(e,!0,!0);const t=this.connectWithRetry(e,!1).finally(()=>(this.reconnectTask===t&&(this.reconnectTask=null),this.startPendingReconnectIfNeeded()??void 0));return this.reconnectTask=t,t}recoverConnectionForSend(){return this.connection.status===s&&this.websocket?Promise.resolve():this.terminalDisconnectError||!this.isLoggedIn||!this.isOnline||this.isLoginPhase||0===this.config.autoReconnectNumMax?(Ks("Send connection recovery skipped",{guard:"connection-not-recoverable",...this.getReconnectDiagnostic()}),Promise.resolve()):this.reconnectTask?(Ks("Send connection recovery reused",this.getReconnectDiagnostic()),this.reconnectTask):(this.reconnectPaused=!1,this.resetReconnectState(),Ks("Send connection recovery requested",this.getReconnectDiagnostic()),this.triggerReconnect(_))}startPendingReconnectIfNeeded(){const e=this.pendingReconnectReason;return this.pendingReconnectReason=null,!e||null!==this.terminalDisconnectError||!this.isLoggedIn||!this.isOnline||this.connection.status===s&&this.websocket?null:(this.reconnectPaused=!1,this.resetReconnectState(),Ks("Queued reconnect recovery started",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e))}handleDisconnection(e){Ks("Connection disconnection handled",{reason:e,...this.getReconnectDiagnostic()}),this.stopHeartbeat(),this.updateStatus(t,e,!0),e!==O&&this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||this.triggerReconnect(e))}closeWebSocket(e,r,s=!0){this.websocket?(this.suppressNextCloseEvent=!0,this.websocket.close(),this.websocket=null,this.stopHeartbeat(),s&&this.updateStatus(t,e,r)):s&&this.updateStatus(t,e,r)}createWebSocketConnection(){const e=this.resolveLoginStageTimeout(this.config.connectTimeout);return e<=0?Promise.reject(this.requireLoginTimeoutError()):new Promise((t,r)=>{const s=++this.connectionAttemptGeneration,n=this.pickNextServerUrl();Vs("WebSocket connecting",{url:n}),this.clearSocketListeners();let i=!1,o=!1,a=null;const c=()=>{this.connectionAttemptGeneration===s&&(this.activeConnectionAttemptCancel=null)},d=e=>{i||(i=!0,a&&(clearTimeout(a),a=null),c(),r(e))};this.activeConnectionAttemptCancel=()=>{const e=Xh(o?"provision":"ws");this.rejectPendingProvision(e),d(e)},a=setTimeout(()=>{Ks("WebSocket connection attempt timed out",{url:n,connectTimeout:e,...this.getReconnectDiagnostic()}),d(this.isLoginDeadlineExpired()?this.requireLoginTimeoutError():new ht("Connection timeout",{code:ot.CONNECTION_TIMEOUT,details:{stage:"ws"}}))},e),this.socketAdapter.connect({url:n,timeoutMs:e}).then(e=>{if(i||s!==this.connectionAttemptGeneration||this.reconnectPaused)return Ks("WebSocket connection result discarded",{url:n,cancelled:i||s!==this.connectionAttemptGeneration,reconnectPaused:this.reconnectPaused,...this.getReconnectDiagnostic()}),e.close(),void d(Xh("ws"));a&&(clearTimeout(a),a=null),this.websocket=e,this.socketGeneration+=1,this.inboundMessageQueue=Promise.resolve(),this.attachSocketListeners(e,this.socketGeneration),o=!0,this.startProvision().then(()=>{if(this.resetProvisionHandlers(),i||s!==this.connectionAttemptGeneration||this.reconnectPaused)return Ks("Provision result discarded",{url:n,cancelled:i||s!==this.connectionAttemptGeneration,reconnectPaused:this.reconnectPaused,...this.getReconnectDiagnostic()}),this.closeWebSocket(A,!1,!1),void d(Xh("provision"));i||(i=!0,a&&(clearTimeout(a),a=null),c(),t())}).catch(e=>{this.resetProvisionHandlers(),this.closeWebSocket(A,!1,!1),d(e instanceof Error?e:new Error(String(e)))})}).catch(e=>{if(i)return;const t=e instanceof ht?e:new ht("Failed to create WebSocket",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:e instanceof Error?e.message:String(e)}});this.handleConnectionError(t,A),d(t)})}).catch(e=>{if(e instanceof ht)throw e;const t=new ht("Failed to create WebSocket",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws",cause:e instanceof Error?e.message:String(e)}});throw this.handleConnectionError(t,A),t})}cancelActiveConnectionAttempt(){this.activeConnectionAttemptCancel?.()}handleWebSocketClose(e){this.suppressNextCloseEvent?this.suppressNextCloseEvent=!1:(Ks("WebSocket closed",{code:e.code,reason:e.reason}),this.provisionReject&&this.rejectProvisionAfterQueuedMessages(),this.websocket=null,this.clearSocketListeners(),this.stopHeartbeat(),this.handleDisconnection(w))}async rejectProvisionAfterQueuedMessages(){try{await this.inboundMessageQueue}catch{}this.provisionReject&&(this.provisionReject(new ht("Provision interrupted",{code:ot.CONNECTION_PROVISION_CLOSED,details:{stage:"provision"}})),this.resetProvisionHandlers())}handleConnectionError(e,t){zs("Connection error:",e),this.connection.error=e,this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null);const r=e instanceof ht?e:new ht(e.message,{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",retryable:!0}});if(this.rejectPendingProvision(r)||this.resetProvisionHandlers(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.handleDisconnection(t)}handleTerminalConnectionError(e,r){if(Ks("Terminal connection error received",{code:e.code,message:e.message,details:e.details}),this.connection.error=e,this.terminalDisconnectError=e,this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.pendingReconnectReason=null,this.isLoggedIn=!1,this.cancelActiveConnectionAttempt(),this.resetProvisionHandlers(),this.clearReconnectTimer(),this.websocket){this.suppressNextCloseEvent=!0;const e=this.websocket;this.clearSocketListeners(),e.close(),this.websocket=null}this.stopHeartbeat(),this.updateStatus(t,r,!0,!0)}async handleWebSocketMessage(e,t){try{if(t!==this.socketGeneration)return;Vs("WebSocket message received",{dataType:typeof e});const s=await this.msyncCodec.normalizeIncoming(e);if(t!==this.socketGeneration)return;if(Vs("handleWebSocketMessage data",{length:s.length}),!s.length)return;const n=this.msyncCodec.decompressIncoming(s);if(!n){const e=null!==this.provisionReject;return zs("Failed to decompress mSync payload, closing connection",{stage:e?"provision":"connected"}),void(e?(this.rejectPendingProvision(new ht("Failed to decompress Provision payload",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision",cause:"decompression-failed",retryable:!0}})),this.closeWebSocket(A,!1,!1)):this.websocket?.close())}if(this.isServerNormalClosePayload(n))return void Vs("Ignore server normal close payload",{length:n.length});let i=null;try{i=this.msyncCodec.decodeMsync(n)}catch(r){const e=r instanceof Error?r:new Error("Failed to decode mSync payload");if(e instanceof RangeError)return void Ks("Discard invalid mSync payload",{length:n.length,message:e.message,prefixHex:Array.from(n.subarray(0,16),e=>e.toString(16).padStart(2,"0")).join(""),suffixHex:Array.from(n.subarray(Math.max(0,n.length-16)),e=>e.toString(16).padStart(2,"0")).join("")});throw Ks("Invalid mSync payload signature",{length:n.length,prefixHex:Array.from(n.subarray(0,8),e=>e.toString(16).padStart(2,"0")).join("")}),e}switch(this.heartbeatManager.markAlive(),Vs("handleWebSocketMessage decoded",{command:i.command}),i.command){case St:this.handleProvisionMessage(i.payload);break;case Et:this.handleLogoutMessage(i.payload);break;case Ct:this.handleNoticeMessage(i.payload);break;case Tt:this.handleUnreadMessage(i.payload);break;case _t:this.handleSyncMessage(i.payload)}}catch(r){const e=r instanceof Error?r:new Error("Failed to handle mSync payload");zs("Failed to handle mSync payload",e),this.handleConnectionError(e,A)}}startProvision(){const e=this.resolveLoginStageTimeout(1e4);if(e<=0)return Promise.reject(this.requireLoginTimeoutError());this.provisionPromise=new Promise((e,t)=>{this.provisionResolve=e,this.provisionReject=t}),this.provisionTimeoutId&&clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=setTimeout(()=>{this.rejectPendingProvision(this.isLoginDeadlineExpired()?this.requireLoginTimeoutError():new ht("Provision timeout",{code:ot.CONNECTION_PROVISION_TIMEOUT,details:{stage:"provision",retryable:!0}}))},e);try{const e=this.msyncCodec.encodeProvision();Vs("startProvision provision",{length:e.length}),this.sendMsyncPayload(e)}catch{this.provisionReject?.(new ht("Provision send failed",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"provision"}})),this.resetProvisionHandlers()}return this.provisionPromise}handleProvisionMessage(e){const t=this.msyncCodec.decodeProvision(e);if(this.isLoginPhase&&this.activeLoginDeadline?.markProvisionReceived(),this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t.ok)this.msyncCodec.updateResource(t.resource),this.setupTokenLifecycleFromProvision(t.authToken),this.provisionResolve?.();else{Ks("Provision rejected",{statusCode:t.statusCode,reason:t.reason});const e=Wr(t.statusCode,t.reason),r=e.code===ot.UNKNOWN?ot.CONNECTION_PROVISION_REJECTED:e.code;this.provisionReject?.(new ht("Provision rejected",{code:r,details:{stage:"provision",reason:t.reason,statusCode:t.statusCode,retryable:e.retryable}}))}}handleNoticeMessage(e){const{queue:t}=this.msyncCodec.decodeNotice(e),r=t?this.getQueueId(t):null,s=!!t&&this.isSelfQueue(t),n=!!t&&this.isQueueInList(t);t&&r&&(s||n||(this.queues.push(t),1===this.queues.length&&this.sendBackqueue(t)))}handleUnreadMessage(e){const{queues:t}=this.msyncCodec.decodeUnread(e),r=t.filter(e=>this.getQueueId(e));if(r.length){r.length!==t.length&&Ks("Unread queues without usable identity were ignored",{ignoredCount:t.length-r.length}),this.startOfflineMessageSync(r);for(const e of r)this.isQueueInList(e)||this.queues.push(e);if(this.queues.length>0&&!this.currentQueue){const e=this.queues[0];e&&this.sendBackqueue(e)}}}handleSyncMessage(e){const t=this.resolveStatisticDisconnectError(this.msyncCodec.decodeSyncStatisticOperations(e));if(t)return void this.handleTerminalConnectionError(t,A);if(!this.messageReceiver)return;const r=this.messageReceiver.handleSyncPayload(e);if(Vs("handleSyncMessage result",{result:r}),!r)return;(void 0!==r.queue||void 0!==r.nextKey||void 0!==r.isLast)&&this.handleSyncQueueState(r)}handleSyncQueueState(e){Vs("[QueueSync] handleSyncQueueState",{isLast:e.isLast,nextKey:e.nextKey,queueName:e.queue?this.getQueueName(e.queue):null,queueId:e.queue?this.getQueueId(e.queue):null,queuesLength:this.queues.length});const t=this.resolveSyncQueueState(e);if(!t)return e.queue&&e.isLast?(this.queues=this.queues.filter(e=>null!==this.getQueueId(e)),void this.sendNextQueue()):e.queue&&e.nextKey?void this.sendLastSession(e.queue,e.nextKey):void 0;const{queue:r,queueId:s}=t;if(this.offlineMessageSyncing&&this.offlineMessageQueueNames.has(s)){const t=this.offlineMessageQueueCounts.get(s)??0;this.offlineMessageQueueCounts.set(s,t+e.messages.length),this.offlineMessageTotalCount+=e.messages.length}const n=e.nextKey;if(e.isLast)return this.finishOfflineMessageQueue(s),this.removeQueueEntry(r),this.nextKey=null,this.currentQueueId=null,this.currentQueue=null,void this.sendNextQueue();if(n){if(n!==this.nextKey||!this.isSameQueue(r,this.currentQueue))return this.nextKey=n,this.currentQueueId=s,this.currentQueue=r,void this.sendLastSession(r,n);this.removeQueueEntry(r),this.sendNextQueue()}}resolveSyncQueueState(e){const t=e.queue&&"object"==typeof e.queue?e.queue:void 0,r=t?this.getQueueName(t):null,s=t?this.getQueueId(t):null,n=void 0!==t&&null!==s&&(0===this.queues.length||this.queues.some(e=>this.isSameQueue(e,t)));if(t&&s&&n)return{queue:t,queueId:s};const i=this.currentQueue&&this.queues.some(e=>this.isSameQueue(e,this.currentQueue))?this.currentQueue:void 0,o=this.currentQueueId?this.queues.find(e=>this.getQueueId(e)===this.currentQueueId):void 0,a=i??o??this.queues[0],c=a?this.getQueueName(a):null,d=a?this.getQueueId(a):null;return a&&d?(Ks("Sync queue response did not match a tracked queue, fallback to local queue",{responseQueueName:r,responseQueueId:s,fallbackQueueName:c,fallbackQueueId:d,currentQueueId:this.currentQueueId,firstQueueName:this.getQueueName(this.queues[0]??{}),firstQueueId:this.getQueueId(this.queues[0]??{}),isLast:e.isLast,hasNextKey:Boolean(e.nextKey)}),{queue:a,queueId:d}):null}handleLogoutMessage(e){const t=this.msyncCodec.decodeLogout(e);Ks("Logout message received",t)}resolveStatisticDisconnectError(e){for(const t of e)switch(t.operation){case 1:return new ht("User has been removed",{code:ot.USER_REMOVED,details:{stage:"statistics",operation:t.operation,retryable:!1}});case 2:return new ht("The user is already logged on another device",{code:ot.USER_LOGIN_ANOTHER_DEVICE,details:{stage:"statistics",operation:t.operation,retryable:!1,...t.reason?{loginInfoCustomExt:t.reason}:{}}});case 3:return new ht("The user was kicked by changing password",{code:ot.USER_KICKED_BY_CHANGE_PASSWORD,details:{stage:"statistics",operation:t.operation,retryable:!1}});case 4:return new ht("The user was kicked by other device",{code:ot.USER_KICKED_BY_OTHER_DEVICE,details:{stage:"statistics",operation:t.operation,retryable:!1}})}return null}resetProvisionHandlers(){this.provisionResolve=null,this.provisionReject=null,this.provisionPromise=null}rejectPendingProvision(e){const t=this.provisionReject;return!!t&&(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t(e),this.resetProvisionHandlers(),!0)}disconnect(){return this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),this.clearReconnectTimer(),this.cancelActiveConnectionAttempt(),this.clearTokenTimers(),this.tokenLifecycle=null,this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.terminalDisconnectError=null,this.offlineRecoverPending=!1,this.closeWebSocket(w,!0,!0),this.updateStatus(t,w,!0),this.resetSyncState(),this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connection.error=void 0,this.hasEverConnected=!1,this.connectionEventNormalizer.reset(),Ks("Connection disconnected"),Promise.resolve()}destroy(){this.disconnect(),this.eventHub.removeEventHandler(this.internalHandlerId)}resolveSocketAdapter(e){return Bd(e.socketAdapter)}attachSocketListeners(e,t){this.clearSocketListeners(),this.socketDisposers=[e.onMessage(r=>{this.websocket===e&&(this.inboundMessageQueue=this.inboundMessageQueue.catch(()=>{}).then(()=>this.handleWebSocketMessage(r,t)))}),e.onError(()=>{if(this.websocket!==e)return;Ks("WebSocket error",{stage:"ws"});const t=new ht("WebSocket connection error",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{stage:"ws"}});this.handleConnectionError(t,A)}),e.onClose(t=>{this.websocket===e&&this.handleWebSocketClose(t)})]}clearSocketListeners(){for(const e of this.socketDisposers)e();this.socketDisposers=[]}sendMsyncPayload(e){if(this.websocket&&this.websocket.readyState===hn)try{const t=this.msyncCodec.prepareOutgoing(e);Vs("WebSocket send payload",{length:t.length}),Promise.resolve(this.websocket.send(t)).catch(e=>{zs("Failed to send mSync payload",e),this.websocket?.close()})}catch(t){zs("Failed to send mSync payload",t),this.websocket?.close()}}sendBackqueue(e){this.currentQueue=e,this.currentQueueId=this.getQueueId(e),this.nextKey=null;const t=this.msyncCodec.encodeBackQueue(e);Vs("sendBackqueue payload",{length:t.length}),this.sendMsyncPayload(t)}sendLastSession(e,t){Vs("sendLastSession queue",{queueName:this.getQueueName(e),nextKey:t});const r=this.msyncCodec.encodeLastSession(e,t);this.sendMsyncPayload(r)}sendNextQueue(){Vs("sendNextQueue queues",{size:this.queues.length});const e=this.queues[0];e&&this.sendBackqueue(e)}removeQueueEntry(e){const t=this.queues.findIndex(t=>this.isSameQueue(t,e));t>=0&&this.queues.splice(t,1)}startOfflineMessageSync(e){const t=new Set;for(const r of e){const e=this.getQueueId(r);e&&t.add(e)}if(0!==t.size){for(const e of t)this.offlineMessageQueueNames.add(e);if(!this.offlineMessageSyncing){this.offlineMessageSyncing=!0,this.offlineMessageSyncLifecycleActive=!this.offlineMessageSyncLifecycleDispatched,this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleDispatched=!0),this.offlineMessageTotalCount=0,this.offlineMessageQueueCounts.clear(),this.offlineMessageQueueReports.clear(),this.offlineMessageReport=Zh({operationName:"MSYNC_SYNCOFFLINEMESSAGE",operationType:"MESSAGE"});for(const e of t){this.offlineMessageQueueCounts.set(e,0);const t=this.offlineMessageReport?.startRequest({requestName:"MSYNC_SYNCOFFLINEMESSAGE",method:"WS",url:e});t&&this.offlineMessageQueueReports.set(e,t)}this.offlineMessageSyncLifecycleActive&&this.eventHub.dispatch(h,void 0)}}}finishOfflineMessageQueue(e){if(!this.offlineMessageSyncing)return;const t=this.offlineMessageQueueCounts.get(e)??0;this.offlineMessageQueueReports.get(e)?.finish({code:200,success:!0,resultCount:t}),this.offlineMessageQueueReports.delete(e),this.offlineMessageQueueNames.delete(e),this.offlineMessageQueueNames.size>0||(this.offlineMessageSyncing=!1,this.offlineMessageReport?.finish({code:0,success:!0,resultCount:this.offlineMessageTotalCount}),this.offlineMessageReport=void 0,this.offlineMessageQueueReports.clear(),this.offlineMessageQueueCounts.clear(),this.offlineMessageSyncLifecycleActive&&(this.offlineMessageSyncLifecycleActive=!1,this.eventHub.dispatch(p,void 0)))}isQueueInList(e){return this.queues.some(t=>this.isSameQueue(t,e))}isSelfQueue(e){const t=this.getQueueName(e),r=this.getQueueResource(e),s=this.msyncCodec.getContext();return t===s.userId&&r===s.clientResource}getQueueName(e){return"string"==typeof e.name&&e.name.trim().length>0?e.name:null}getQueueResource(e){return this.getQueueField(e,"clientResource")}getQueueId(e){const t=this.getQueueName(e);if(t)return`name:${t}`;const r=this.getQueueField(e,"domain"),s=this.getQueueResource(e);if(r)return`domain:${r}|resource:${s??""}`;if(s)return`resource:${s}`;const n=this.getQueueField(e,"appKey");return n?`appKey:${n}`:null}getQueueField(e,t){const r=e[t];return"string"==typeof r&&r.trim().length>0?r:null}isSameQueue(e,t){if(!e||!t)return!1;const r=this.getQueueId(e),s=this.getQueueId(t);return null!==r&&r===s}resetSyncState(){this.queues=[],this.currentQueueId=null,this.currentQueue=null,this.nextKey=null,this.offlineMessageSyncing=!1,this.offlineMessageSyncLifecycleDispatched=!1,this.offlineMessageSyncLifecycleActive=!1,this.offlineMessageQueueNames.clear(),this.offlineMessageReport?.discard(),this.offlineMessageReport=void 0,this.offlineMessageQueueReports.clear(),this.offlineMessageQueueCounts.clear(),this.offlineMessageTotalCount=0}}const rp=new class{constructor(){this.store=new Map}set(e,t){e&&this.store.set(e,t)}get(e){if(e)return this.store.get(e)}consume(e){const t=this.get(e);return t&&this.store.delete(e),t}delete(e){e&&this.store.delete(e)}clear(){this.store.clear()}},sp=e=>{if((e=>"undefined"!=typeof File&&e instanceof File)(e)){if("undefined"==typeof URL||"function"!=typeof URL.createObjectURL)return;return URL.createObjectURL(e)}return(e=>"object"==typeof e&&null!==e&&"path"in e&&"string"==typeof e.path)(e)?e.path:(e=>"object"==typeof e&&null!==e&&"uri"in e&&"string"==typeof e.uri)(e)?e.uri:void 0},np=()=>{const e=fn().crypto;return e&&"function"==typeof e.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},ip=new Uint8Array([99,109]),op=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ap=e=>Array.isArray(e)&&e.every(op),cp=e=>"string"==typeof e?e:void 0,dp=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,up=e=>{const t=new Uint8Array(4);return t[0]=e>>>24&255,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=255&e,t},lp=(e,t)=>{const r=e[t],s=e[t+1],n=e[t+2],i=e[t+3];if("number"!=typeof r||"number"!=typeof s||"number"!=typeof n||"number"!=typeof i)throw new ft("Combine payload length header is invalid",{code:ot.COMBINE_PARSE_FAILED});return r<<24|s<<16|n<<8|i},hp=e=>{let t=0;for(let r=2;r<e.length;r+=1)r%2==1&&(t^=e[r]??0);return t},pp=(e,t)=>{const r=Wd().lookupType(e).decode(t);if(!op(r))throw new Error(`${e} decoded result is invalid`);return r},mp=e=>op(e)&&"string"==typeof e.name?e.name:"",gp=(e,t,r)=>{const s=ap(e.contents)?e.contents:[];if(0===s.length)throw new Error("MessageBody contents is empty");const n=s.map(e=>(e=>{const t=dp(e.type)??Dt,r=Boolean(cp(e.remotePath))||Boolean(cp(e.title))||Boolean(cp(e.summary))||(dp(e.combineLevel)??0)>0,s=t===Dt&&0===e.subType&&r;if(t===jt||s){const t=dp(e.combineLevel)??0;return{type:"combine",body:{title:cp(e.title)??"",summary:cp(e.summary)??"",filename:cp(e.displayName)??"combine",filetype:"application/octet-stream",url:cp(e.remotePath),secret:cp(e.secretKey),fileLength:dp(e.fileLength),combineLevel:t},combineLevel:t}}if(t===Dt)return{type:"text",body:{content:cp(e.text)??""}};if(t===qt)return{type:"cmd",body:{action:cp(e.action)??""}};if(t===$t){const t=su(ap(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:cp(e.customEvent)??"",params:t}}}if(t===Ft)return{type:"location",body:{latitude:dp(e.latitude)??0,longitude:dp(e.longitude)??0,address:cp(e.address),buildingName:cp(e.buildingName)}};if(t===Pt){const t=op(e.size)?e.size:{},r=cp(e.remotePath)??"",s=Cs(r),n=cp(e.thumbnailRemotePath),i=Es(e.imageType)===ps;return{type:"image",body:{localUrl:"",filename:cp(e.displayName)??"image",filetype:"application/octet-stream",width:dp(t.width)??0,height:dp(t.height)??0,isGif:1===e.subType,isOriginalImage:i,originalImageUrl:s.originalImageUrl,bigImageUrl:s.bigImageUrl,secret:cp(e.secretKey),fileLength:dp(e.fileLength),thumbnailUrl:n??s.thumbnailUrl}}}if(t===xt){const t=op(e.size)?e.size:{};return{type:"video",body:{url:cp(e.remotePath)??"",filename:cp(e.displayName)??"video",filetype:"application/octet-stream",duration:dp(e.duration)??0,width:dp(t.width),height:dp(t.height),secret:cp(e.secretKey),fileLength:dp(e.fileLength),thumbnailUrl:cp(e.thumbnailRemotePath)}}}if(t===Bt)return{type:"voice",body:{url:cp(e.remotePath)??"",filename:cp(e.displayName)??"voice",filetype:"application/octet-stream",duration:dp(e.duration)??0,secret:cp(e.secretKey),fileLength:dp(e.fileLength)}};if(t===Gt)return{type:"file",body:{url:cp(e.remotePath)??"",filename:cp(e.displayName)??"file",filetype:"application/octet-stream",secret:cp(e.secretKey),fileLength:dp(e.fileLength)}};return null})(e)),i=hu(n);if(!i)throw new Error("MessageBody content type is unsupported");const o=mp(e.from)||mp(r?.from)||`unknown-${t}`,a=mp(e.to)||mp(r?.to)||`unknown-${t}`,c=(d=e.type)===Rt?"groupChat":d===Nt?"chatRoom":"singleChat";var d;const u=a||o,l=Number(tu(r?.timestamp))||Date.now(),h=su(ap(e.ext)?e.ext:void 0),p="text"===i.type?zd(e.meta):void 0,m={msgServerId:tu(r?.id),msgLocalId:"",type:i.type,sender:{userId:o},conversationId:u,conversationType:c,timestamp:l,body:Array.isArray(i.body)?i.body:{...i.body,...p?{translations:p}:{}},ext:h},g=1===n.length?n[0]?.combineLevel:void 0;return"number"==typeof g&&op(m.body)&&(m.body.combineLevel=g),m},fp=(e,t)=>{const r=[];try{const n=pp("easemob.pb.Meta",e),i=(s=n.payload)instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):ArrayBuffer.isView(s)?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):void 0;if(i&&i.length>0){const e=pp("easemob.pb.MessageBody",i);return gp(e,t,n)}r.push("Meta payload is empty")}catch(n){r.push(n instanceof Error?n.message:String(n))}var s;try{const r=pp("easemob.pb.MessageBody",e);return gp(r,t)}catch(n){r.push(n instanceof Error?n.message:String(n))}try{const r=pp("easemob.pb.MessageBody.Content",e);return gp({type:At,from:{name:`unknown-${t}`},to:{name:`unknown-${t}`},contents:[r],ext:[]},t)}catch(n){r.push(n instanceof Error?n.message:String(n))}throw new Error(r.join("; "))},yp=(e,t)=>{const r=Ws(e);try{const e=JSON.parse(r);if(!op(e))throw new ft("Combine payload item is invalid",{code:ot.COMBINE_PARSE_FAILED,details:{index:t}});return e}catch(s){if(s instanceof ft)throw s;try{return fp(e,t)}catch(n){throw new ft("Combine payload item parse failed",{code:ot.COMBINE_PARSE_FAILED,details:{index:t,cause:s instanceof Error?s.message:String(s),protobufCause:n instanceof Error?n.message:String(n)}})}}},vp=e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e];if(void 0===t)throw new gt("Combine payload base64 encode failed",{code:ot.COMBINE_ENCODE_FAILED});return t},Ip=(e,t)=>{const r=e[t];if(void 0===r)throw new gt("Combine payload byte is missing",{code:ot.COMBINE_ENCODE_FAILED});return r},bp=e=>{let t="";for(let r=0;r<e.length;r+=3){const s=Ip(e,r),n=r+1<e.length,i=r+2<e.length,o=s<<16|(n?Ip(e,r+1):0)<<8|(i?Ip(e,r+2):0);t+=vp(o>>18&63),t+=vp(o>>12&63),t+=n?vp(o>>6&63):"=",t+=i?vp(63&o):"="}return t},_p=e=>{const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t},Tp=(e,t)=>new gt("Failed to write the combine message file",{code:ot.COMBINE_UPLOAD_FAILED,details:{filePath:e,cause:t}}),Cp=(e,t)=>new gt("Failed to remove the combine message file",{code:ot.COMBINE_UPLOAD_FAILED,details:{filePath:e,cause:t}}),Sp=(e,t)=>{const r=e.getFileSystemManager?.(),s=r?.writeFile;if(!r||!s)throw new gt("Mini program file system is missing",{code:ot.COMBINE_UPLOAD_FAILED});const n=`${(e=>{const t=e.env?.USER_DATA_PATH;if("string"!=typeof t||0===t.length)throw new gt("Mini program user data path is missing",{code:ot.COMBINE_UPLOAD_FAILED});return t.replace(/\/+$/,"")})(e)}/combine-${(e=>{const t=e.replace(/[^A-Za-z0-9._-]/g,"_");if(0===t.length)throw new gt("Combine payload file id is missing",{code:ot.COMBINE_ENCODE_FAILED});return t})(t.fileId)}`,i=_p(t.payload);return new Promise((e,o)=>{try{s.call(r,{filePath:n,data:bp(new Uint8Array(i)),encoding:"base64",success:()=>{e({path:n,name:t.filename,type:t.filetype,size:t.payload.byteLength})},fail:e=>{o(Tp(n,e))}})}catch(a){o(Tp(n,a))}})},Ep=async e=>{const t=Mn(e.runtime);return Un(t.hostPlatform)?Sp(t.global,e):Promise.resolve((e=>{if("undefined"==typeof File)throw new gt("Combine payload file is not supported on this runtime",{code:ot.COMBINE_ENCODE_FAILED});return new File([_p(e.payload)],e.filename,{type:e.filetype})})(e))},wp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ap=(e,t,r)=>{throw new mt(e,{code:r,details:{fields:[{path:t,message:e,rule:"invalid_format"}]}})},Rp=e=>{if("combine"!==e.type)return 0;const t=e.combineLevel;return"number"==typeof t?t:wp(e.body)&&"number"==typeof e.body.combineLevel?e.body.combineLevel:0},Np=(e,t)=>{if(e.sender.userId||Ap(`messageList[${t}] sender.userId is required`,`messageList[${t}].sender.userId`,ot.COMBINE_INVALID_INPUT),e.conversationId&&["singleChat","groupChat","chatRoom"].includes(e.conversationType)||Ap(`messageList[${t}] conversation is invalid`,`messageList[${t}].conversationId`,ot.COMBINE_INVALID_INPUT),(!Number.isInteger(e.timestamp)||e.timestamp<=0)&&Ap(`messageList[${t}] timestamp must be positive integer`,`messageList[${t}].timestamp`,ot.COMBINE_INVALID_INPUT),"multi_body"===e.type){const s=e.body;r=s,!Array.isArray(r)||s.length<2?Ap(`messageList[${t}] body must contain at least 2 segments`,`messageList[${t}].body`,ot.COMBINE_INVALID_INPUT):s.forEach((e,r)=>{wp(e)&&"string"==typeof e.type&&au(e.type)||Ap(`messageList[${t}].body[${r}] is not allowed in a multi_body message`,`messageList[${t}].body[${r}]`,ot.COMBINE_INVALID_INPUT)})}else wp(e.body)||Ap(`messageList[${t}] body must be object`,`messageList[${t}].body`,ot.COMBINE_INVALID_INPUT);var r;if("combine"===e.type){const r=Rp(e);(!Number.isInteger(r)||r<0)&&Ap(`messageList[${t}] combineLevel is invalid`,`messageList[${t}].combineLevel`,ot.COMBINE_INVALID_INPUT),r>10&&Ap(`messageList[${t}] combineLevel exceeds limit`,`messageList[${t}].combineLevel`,ot.COMBINE_LEVEL_EXCEEDED)}},Op=(e,t=300)=>{(!Number.isInteger(e)||e<=0)&&Ap("messageList must not be empty","messageList",ot.COMBINE_INVALID_INPUT),(!Number.isInteger(t)||t<=0||t>300)&&Ap("max items is invalid","maxItems",ot.COMBINE_INVALID_INPUT),e>t&&Ap(`messageList max length is ${t}`,"messageList",ot.COMBINE_ITEM_LIMIT_EXCEEDED)},Mp=e=>{Op(e.length);for(let t=0;t<e.length;t+=1){const r=e[t];void 0!==r?Np(r,t):Ap(`messageList[${t}] is required`,`messageList[${t}]`,ot.COMBINE_INVALID_INPUT)}},Up=e=>{let t=0;for(const r of e){if("combine"!==r.type)continue;const e=Rp(r);e>t&&(t=e)}return t+1},Lp=e=>{(!Number.isInteger(e)||e<=0)&&Ap("combineLevel must be positive integer","combineLevel",ot.COMBINE_INVALID_INPUT),e>10&&Ap("combineLevel must be <= 10","combineLevel",ot.COMBINE_LEVEL_EXCEEDED)},kp=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class Dp{constructor(e,t,r,s){this.websocket=null,this.pendingMessages=new Map,this.ackTimeout=15e3,this.attachmentUploader=null,this.messageReportCount=0,this.chatRoomReportCount=0,this.messageReportSaturated=!1,this.chatRoomReportSaturated=!1,this.websocket=t,this.eventHub=r,this.msyncCodec=e,this.attachmentUploader=s??null}updateAuthToken(e){this.attachmentUploader?.updateAuthToken(e)}async sendMessage(e,t){const r=this.msyncCodec.toProtocolId(e.msgLocalId);if(it(e))throw new gt("Stream message send is not supported",{code:ot.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:e.msgLocalId,retryable:!1}});if(!this.websocket||this.websocket.readyState!==hn){const t=this.msyncCodec.toProtocolId(e.msgLocalId);throw new gt("WebSocket is not connected",{code:ot.MESSAGE_NOT_CONNECTED,details:{msgLocalId:e.msgLocalId,protocolId:t,retryable:!0}})}let s={...e,sendStatus:"sending"};ml(e,s),Vs("Message send queued",{msgLocalId:e.msgLocalId,protocolId:r,type:e.type,conversationType:e.conversationType,conversationId:e.conversationId});try{const e="combine"===s.type?await this.prepareCombineMessage(s):s,r=this.attachmentUploader?await this.attachmentUploader.prepareMessage(e,t):e;if(this.attachmentUploader&&"combine"===s.type)try{await(async(e,t)=>{if(void 0===e||!(e=>"path"in e&&"string"==typeof e.path&&e.path.length>0)(e))return;const r=Mn(t);if(!Un(r.hostPlatform))return;const s=r.global,n=s.getFileSystemManager?.(),i=n?.unlink;if(!n||!i)throw new gt("Mini program file system is missing",{code:ot.COMBINE_UPLOAD_FAILED,details:{filePath:e.path}});const o=e.path;await new Promise((e,t)=>{try{i.call(n,{filePath:o,success:()=>{e()},fail:e=>{t(Cp(o,e))}})}catch(r){t(Cp(o,r))}})})(rp.get(s.msgLocalId))}catch(n){Ks("Failed to remove combine payload file after upload",{msgLocalId:s.msgLocalId,cause:n})}const i={...r,sendStatus:"sending"};ml(s,i),s=i,t?.onSending?.(i);const o=await this.doSendMessage(i);return t?.onSuccess?.(o),o}catch(n){const e={...s,sendStatus:"failed"};throw ml(s,e),t?.onFailed?.(e,n instanceof Error?n:new Error(String(n))),n}}async sendAction(e,t){const r=this.msyncCodec.toProtocolId(`${e.kind}:${e.messageId??e.conversationId}:${Date.now()}`);"clearAllConversationUnreadMessageCount"===e.kind&&Vs("Clear-all unread action encode started",{operation:"message.action.clear-all-unread.encode",protocolId:r,conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:e.sendToPeer,clearAllUnreadMessageCount:e.clearAllUnreadMessageCount});const s=this.msyncCodec.encodeActionMessage(e,r);"clearAllConversationUnreadMessageCount"===e.kind&&Vs("Clear-all unread action encoded",{operation:"message.action.clear-all-unread.encoded",protocolId:r,payloadBytes:s.byteLength});const n="recall"===e.kind?"MSYNC_RECALLMESSAGE":"update"===e.kind?"MSYNC_MODIFYMESSAGE":`MSYNC_${e.kind.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()}`;return this.sendProtocolPayload(r,s,t,this.createPendingDataReport({category:"message",operationName:n,operationType:"MESSAGE",requestName:n,msgId:e.messageId,messageType:kp(e.conversationType)}))}async sendChatRoomOperation(e,t){const r=this.msyncCodec.toProtocolId(`chatroom:${e.operation}:${e.chatRoomId}:${Date.now()}`),s=this.msyncCodec.encodeChatRoomOperation(e,r),n="join"===e.operation?"CHATROOM_JOINCAHTROOM":"CHATROOM_LEAVECAHTROOM";return this.sendProtocolPayload(r,s,t,this.createPendingDataReport({category:"chatroom",operationName:n,operationType:"CHATROOM",requestName:n,msgId:e.chatRoomId}))}async doSendMessage(e){const t=this.createPendingDataReport({category:"message",operationName:"MSYNC_SENDMESSAGE",operationType:"SENDMESSAGE",requestName:"MSYNC_SENDMESSAGE",msgId:e.msgLocalId,messageType:kp(e.conversationType)});return new Promise((r,s)=>{const n=this.msyncCodec.toProtocolId(e.msgLocalId),i=setTimeout(()=>{this.pendingMessages.delete(n),this.finishPendingDataReport(t,{code:ot.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),s(new gt("Message ACK timeout",{code:ot.MESSAGE_ACK_TIMEOUT,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(n,{kind:"message",message:e,protocolId:n,timeoutId:i,resolve:e=>{clearTimeout(i),r(e)},reject:e=>{clearTimeout(i),s(e)},report:t});try{if(!this.websocket||this.websocket.readyState!==hn)throw new gt("WebSocket is not connected",{code:ot.MESSAGE_NOT_CONNECTED,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}});const r=this.msyncCodec.encodeChatMessage(e,n),o=this.msyncCodec.prepareOutgoing(r);Promise.resolve(this.websocket.send(o)).catch(r=>{const o=r instanceof Error?r.message:String(r);this.pendingMessages.delete(n),clearTimeout(i),this.finishPendingDataReport(t,{code:-1,success:!1,description:o}),Ks("Message send socket failure",{msgLocalId:e.msgLocalId,protocolId:n,websocketReadyState:this.websocket?.readyState??null,cause:o}),s(new gt(`WebSocket send failed: ${o}`,{code:ot.MESSAGE_NOT_CONNECTED,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0,cause:o}}))}),Vs("Message sent",{msgLocalId:e.msgLocalId,protocolId:n})}catch(o){if(this.pendingMessages.delete(n),clearTimeout(i),this.finishPendingDataReport(t,{code:o instanceof gt?o.code:ot.MESSAGE_ENCODE_FAILED,success:!1,description:o instanceof Error?o.message:String(o)}),o instanceof gt)throw o;throw new gt("Message encode failed",{code:ot.MESSAGE_ENCODE_FAILED,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0}})}})}async sendProtocolPayload(e,t,r,s){return new Promise((n,i)=>{const o=setTimeout(()=>{this.pendingMessages.delete(e),this.finishPendingDataReport(s,{code:ot.MESSAGE_ACK_TIMEOUT,success:!1,description:"Message ACK timeout"}),i(new gt("Message ACK timeout",{code:ot.MESSAGE_ACK_TIMEOUT,details:{protocolId:e,retryable:!0}}))},this.ackTimeout);this.pendingMessages.set(e,{kind:"action",protocolId:e,timeoutId:o,createAckError:r,resolve:n,reject:i,report:s});try{if(!this.websocket||this.websocket.readyState!==hn)throw new gt("WebSocket is not connected",{code:ot.MESSAGE_NOT_CONNECTED,details:{protocolId:e,retryable:!0}});const r=this.msyncCodec.prepareOutgoing(t);Promise.resolve(this.websocket.send(r)).catch(t=>{const r=t instanceof Error?t.message:String(t);this.pendingMessages.delete(e),clearTimeout(o),this.finishPendingDataReport(s,{code:-1,success:!1,description:r}),i(new gt(`WebSocket action send failed: ${r}`,{code:ot.MESSAGE_NOT_CONNECTED,details:{protocolId:e,retryable:!0,cause:r}}))})}catch(a){if(this.pendingMessages.delete(e),clearTimeout(o),this.finishPendingDataReport(s,{code:a instanceof gt?a.code:ot.MESSAGE_ENCODE_FAILED,success:!1,description:a instanceof Error?a.message:String(a)}),a instanceof gt)throw a;i(new gt("Message encode failed",{code:ot.MESSAGE_ENCODE_FAILED,details:{protocolId:e,retryable:!1}}))}})}async prepareCombineMessage(e){const t=e.body,r=t.messageList??[];Mp(r);const s=Up(r);Lp(s);const n=((e,t)=>{try{const r=e.map((e,r)=>{const s=t(e,r);if(0===s.length)throw new gt("Combine payload item encode failed",{code:ot.COMBINE_ENCODE_FAILED,details:{index:r}});return s}),s=ip.length+r.reduce((e,t)=>e+4+t.length,0)+1,n=new Uint8Array(s);let i=0;n.set(ip,i),i+=ip.length;for(const e of r){const t=up(e.length);n.set(t,i),i+=t.length,n.set(e,i),i+=e.length}const o=hp(n.subarray(0,n.length-1));return n[n.length-1]=o,n}catch(r){if(r instanceof gt)throw r;throw new gt("Combine payload encode failed",{code:ot.COMBINE_ENCODE_FAILED,details:{cause:r instanceof Error?r.message:String(r)}})}})(r,e=>this.msyncCodec.encodeCombineMessageMeta(e)),i=t.filename||"combine",o=t.filetype||"application/octet-stream",a=await Ep({payload:n,filename:i,filetype:o,fileId:e.msgLocalId}),c=sp(a);if(!c&&!this.attachmentUploader)throw new gt("Combine payload local url generation failed",{code:ot.COMBINE_ENCODE_FAILED});rp.set(e.msgLocalId,a);const d={...e,body:{...t,combineLevel:s,fileLength:n.byteLength,filename:i,filetype:o,url:c??t.url}};return ml(e,d),Il(e,d),d}handleAck(e,t,r,s){const n=this.pendingMessages.get(e);if(!n)return void Vs("Received ACK without a tracked pending message",{protocolId:e});if("action"===n.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:200,success:!0}),void n.resolve({protocolId:e,serverId:t??"",statusCode:0,chatRoomInfo:s});const i=n.message,o={...i,...this.resolveReplacedMessage(i,r),sendStatus:"sent",msgServerId:t||r?.msgServerId||i.msgServerId};if(ml(i,o),this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:200,success:!0}),"multi_body"===i.type){const e=i.body;Array.isArray(e)&&e.forEach((e,t)=>{rp.delete(cu(i.msgLocalId,t))})}else"image"!==o.type&&"video"!==o.type&&"voice"!==o.type&&"file"!==o.type&&"combine"!==o.type||rp.delete(o.msgLocalId);Vs("Message ACK matched",{protocolId:e,msgLocalId:o.msgLocalId,msgServerId:o.msgServerId??null,type:o.type,conversationType:o.conversationType,conversationId:o.conversationId}),this.eventHub.dispatch(I,o),n.resolve(o)}resolveReplacedMessage(e,t){return t?{type:t.type,body:t.body,ext:t.ext,timestamp:t.timestamp||e.timestamp}:{}}handleSendError(e,t){const r=this.pendingMessages.get(e);if(!r)return;if("action"===r.kind)return this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t instanceof gt?t.code:-1,success:!1,description:t.message}),void r.reject(t);const s={...r.message,sendStatus:"failed"};ml(r.message,s),this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t instanceof gt?t.code:-1,success:!1,description:t.message}),Ks("Message send failed after ACK/error",{protocolId:e,msgLocalId:s.msgLocalId,type:s.type,conversationType:s.conversationType,conversationId:s.conversationId,error:t.message}),r.reject(t)}handleAckFailure(e,t,r,s){const n=this.pendingMessages.get(e);if(n)return"action"===n.kind?(this.pendingMessages.delete(e),this.finishPendingDataReport(n.report,{code:t,success:!1,description:r??s.message}),void n.reject(n.createAckError?.(t,r)??s)):void this.handleSendError(e,s)}setWebSocket(e){this.websocket=e}destroy(){for(const[e,t]of this.pendingMessages)clearTimeout(t.timeoutId),this.finishPendingDataReport(t.report,{code:-1,success:!1,description:"Message sender destroyed"}),t.reject(new gt("Message sender destroyed",{code:ot.MESSAGE_SENDER_DESTROYED,details:"message"===t.kind?{msgLocalId:t.message.msgLocalId,protocolId:e,retryable:!1}:{protocolId:e,retryable:!1}}));this.pendingMessages.clear()}createPendingDataReport(e){if(("message"===e.category?this.messageReportCount:this.chatRoomReportCount)>=Gh){return void(("message"===e.category?this.messageReportSaturated:this.chatRoomReportSaturated)||(Ks("DataReport correlation limit reached",{category:e.category}),"message"===e.category?this.messageReportSaturated=!0:this.chatRoomReportSaturated=!0))}const t=Zh({operationName:e.operationName,operationType:e.operationType,msgId:e.msgId,messageType:e.messageType});if(t)return"message"===e.category?this.messageReportCount+=1:this.chatRoomReportCount+=1,{category:e.category,operation:t,request:t.startRequest({requestName:e.requestName,method:"WS",url:""}),released:!1}}finishPendingDataReport(e,t){e&&!e.released&&(e.released=!0,e.request.finish(t),e.operation.finish(t),"message"===e.category?(this.messageReportCount=Math.max(0,this.messageReportCount-1),this.messageReportCount<Gh&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<Gh&&(this.chatRoomReportSaturated=!1)))}}class Pp{constructor(e){this.sessions=new Map,this.ttlMs=e?.ttlMs??3e5,this.maxSessions=e?.maxSessions??100}getOrCreate(e){this.evictStale();const t=this.sessions.get(e);if(t)return t.lastActivityTs=Date.now(),t;this.sessions.size>=this.maxSessions&&this.evictOldest();const r={msgId:e,startSeq:null,lastDispatchedSeq:-1,fullText:"",completed:!1,chunksBySeq:new Map,lastActivityTs:Date.now()};return this.sessions.set(e,r),r}get(e){return this.sessions.get(e)}addChunk(e,t){const r=this.getOrCreate(e),s=t.stream.seq;return r.chunksBySeq.has(s)?{duplicate:!0,session:r}:(r.chunksBySeq.set(s,t),r.lastActivityTs=Date.now(),t.stream.status!==nt.START&&t.stream.status!==nt.START_COMPLETED||null!==r.startSeq||(r.startSeq=s),{duplicate:!1,session:r})}getSequentialChunks(e){const t=this.sessions.get(e);if(!t||t.completed||null===t.startSeq)return[];let r=t.lastDispatchedSeq<t.startSeq?t.startSeq:t.lastDispatchedSeq+1;const s=[];for(;t.chunksBySeq.has(r);){const e=t.chunksBySeq.get(r);if(!e)break;s.push(e),r+=1}return s}markDispatched(e,t,r){const s=this.sessions.get(e);if(!s)return;const n=t.stream.seq;s.lastDispatchedSeq=Math.max(s.lastDispatchedSeq,n),s.fullText=r,s.chunksBySeq.delete(n)}markCompleted(e,t,r){const s=this.getOrCreate(e);s.completed=!0,s.completedReason=t,s.fullText=r}clear(e){this.sessions.delete(e)}clearAll(){this.sessions.clear()}evictStale(){const e=Date.now();for(const[t,r]of this.sessions)e-r.lastActivityTs>this.ttlMs&&this.sessions.delete(t)}evictOldest(){let e=null,t=1/0;for(const[r,s]of this.sessions)s.lastActivityTs<t&&(t=s.lastActivityTs,e=r);e&&this.sessions.delete(e)}}class xp{constructor(e,t){this.completedIds=new Set,this.eventHub=e,this.cache=t??new Pp}handle(e){const t=this.resolveMessageId(e);if(!t)return void Ks("stream message id missing, skip dispatch");if(this.completedIds.has(t))return void Vs("stream message already completed, ignore",{msgId:t});if(e.stream.status===nt.FULL)return void this.handleFullChunk(t,e);const r=this.cache.get(t);if(r?.completed)return void Vs("stream session completed, ignore chunk",{msgId:t,seq:e.stream.seq});const{duplicate:s}=this.cache.addChunk(t,e);s?Vs("stream duplicate chunk ignored",{msgId:t,seq:e.stream.seq}):e.stream.errorType>0?this.dispatchServerError(t,e):this.dispatchSequentialChunks(t)}destroy(){this.cache.clearAll(),this.completedIds.clear()}dispatchSequentialChunks(e){const t=this.cache.getSequentialChunks(e);if(0!==t.length)for(const r of t){const t=this.cache.get(e);if(!t)return;const s=t.fullText,n=r.stream.deltaText,i=`${s}${n}`,o=r.stream.errorType>0?nt.ERROR:r.stream.status,a=this.buildDispatchMessage(r,{status:o,fullText:i,deltaText:n});if(this.eventHub.dispatch(U,a),this.cache.markDispatched(e,r,i),o===nt.START_COMPLETED||o===nt.COMPLETED||o===nt.ERROR){const t=o===nt.ERROR?"timeout_error":"normal";return this.cache.markCompleted(e,t,i),this.cache.clear(e),void this.markCompleted(e)}}else Vs("stream chunks pending for missing seq",{msgId:e})}handleFullChunk(e,t){const r=this.cache.get(e),s=r?.fullText??"",n=this.resolveFullText(t,s),i=this.resolveDeltaText(s,n,t.stream.deltaText),o=!r||-1===r.lastDispatchedSeq&&0===r.chunksBySeq.size,a=t.stream.errorType>0?nt.ERROR:o?nt.START_COMPLETED:nt.COMPLETED,c=this.buildDispatchMessage(t,{status:a,fullText:n,deltaText:i});this.eventHub.dispatch(U,c);const d=a===nt.ERROR?"timeout_error":"fallback_full";this.cache.markCompleted(e,d,n),this.cache.clear(e),this.markCompleted(e)}dispatchServerError(e,t){const r=this.cache.get(e),s=r?.fullText??"",n=this.resolveFullText(t,s),i=this.resolveDeltaText(s,n,t.stream.deltaText),o=this.buildDispatchMessage(t,{status:nt.ERROR,fullText:n,deltaText:i});this.eventHub.dispatch(U,o),this.cache.markCompleted(e,"timeout_error",n),this.cache.clear(e),this.markCompleted(e)}buildDispatchMessage(e,t){return{...e,body:{...e.body,content:t.fullText},stream:{...e.stream,status:t.status,fullText:t.fullText,deltaText:t.deltaText}}}resolveMessageId(e){return e.msgServerId&&e.msgServerId.length>0?e.msgServerId:e.msgLocalId}resolveFullText(e,t){const r=e.stream.fullText;if(r&&r.length>=t.length)return r;const s=e.body.content;return s&&s.length>=t.length?s:`${t}${e.stream.deltaText}`}resolveDeltaText(e,t,r){return t.startsWith(e)?t.slice(e.length):r}markCompleted(e){if(this.completedIds.add(e),this.completedIds.size<=2048)return;const t=this.completedIds.values().next().value;t&&this.completedIds.delete(t)}}class Fp{constructor(e=100){this.seenIds=new Set,this.orderedIds=[],this.limit=Math.max(1,Math.floor(e))}checkAndRecord(e){if(!e)return!1;if(this.seenIds.has(e))return!0;for(this.seenIds.add(e),this.orderedIds.push(e);this.orderedIds.length>this.limit;){const e=this.orderedIds.shift();e&&this.seenIds.delete(e)}return!1}clear(){this.seenIds.clear(),this.orderedIds.length=0}size(){return this.seenIds.size}}const Bp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class Gp{constructor(e,t,r){this.eventHub=r,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new xp(r),this.messageContexts=new Map,this.recentMessageIds=new Fp(100),this.enableDeliveryReceipt=!1}setDeliveryAckEnabled(e){this.enableDeliveryReceipt=e}rememberSentMessageContext(e){"sent"===e.sendStatus&&(this.rememberMessageContext(e),this.recentMessageIds.checkAndRecord(this.resolveMessageContextId(e)))}handleSyncPayload(e){try{Vs("handleSyncPayload payload",{length:e.length});const t=this.msyncCodec.decodeSync(e);Vs("handleSyncPayload result",{ack:Boolean(t.ack),messageCount:t.messages.length});const{ack:r,messages:s}=t;t.notifies&&t.notifies.length>0&&this.handleNotifies(t.notifies),r&&(Vs("Decoded sync ACK",{ok:r.ok,protocolId:r.protocolId,serverId:r.serverId??null,statusCode:r.statusCode??null,reason:r.reason??null,hasReplacedMessage:Boolean(t.replacedMessage)}),this.handleAck(r,t.replacedMessage));for(const e of s)this.dispatchMessage(e);return t}catch(t){zs("Failed to decode sync payload",t)}return null}handleAck(e,t){if(e.ok)return Vs("ACK accepted",{protocolId:e.protocolId,serverId:e.serverId??null,hasReplacedMessage:Boolean(t)}),void(e.chatRoomInfo?this.messageSender.handleAck(e.protocolId,e.serverId,t,e.chatRoomInfo):this.messageSender.handleAck(e.protocolId,e.serverId,t));Ks("ACK rejected",{protocolId:e.protocolId,statusCode:e.statusCode,reason:e.reason,hasReplacedMessage:Boolean(t)});const r=((e,t)=>{const r=Wr(e,t),s=r.code===ot.UNKNOWN?ot.MESSAGE_SEND_FAILED:r.code;return{code:s,message:Jr[s]??(t?`Message send failed: ${t}`:"Message send failed for an unknown reason"),retryable:r.retryable}})(e.statusCode,e.reason),s=new gt(r.message,{code:r.code,details:{protocolId:e.protocolId,serverCode:e.statusCode,reason:e.reason,retryable:!1}});this.messageSender.handleAckFailure(e.protocolId,e.statusCode,e.reason,s)}dispatchMessage(e){if(it(e))return void this.streamMessageHandler.handle(e);this.rememberMessageContext(e),this.sendDeliveryAckIfNeeded(e);const t=this.resolveMessageContextId(e);this.recentMessageIds.checkAndRecord(t)?Vs("Duplicate message ignored",{messageId:t}):(this.eventHub.dispatch(M,e),Vs("Message received",{msgServerId:e.msgServerId}))}sendDeliveryAckIfNeeded(e){if(!this.enableDeliveryReceipt)return;if("singleChat"!==e.conversationType)return;const t=this.msyncCodec.getContext().userId;t&&e.from!==t&&this.messageSender.sendAction({kind:"deliveryAck",conversationId:e.from,conversationType:"singleChat",messageId:e.msgServerId??e.msgLocalId}).catch(e=>{Ks("Failed to send delivery ack",e)})}handleNotifies(e){const t=[];for(const r of e)if("presence"===r.type)this.handlePresenceNotify(r);else if("contact"===r.type)this.handleContactNotify(r);else if("group"===r.type)this.handleGroupNotify(r);else if("thread"===r.type)this.handleChatThreadNotify(r);else if("chatroom"===r.type)this.handleChatRoomNotify(r);else if("reaction"===r.type)this.handleReactionNotify(r);else if("conv"===r.type)this.handleConversationNotify(r);else if("multiDevice"===r.type)this.handleMultiDeviceNotify(r);else if("message_receipts"===r.type){const e=this.toMessageReceiptPayload(r);e&&t.push(e)}else"message_recalled"===r.type?this.handleMessageRecalledNotify(r):"message_updated"===r.type?this.handleMessageUpdatedNotify(r):"message_delivered"===r.type?this.handleMessageDeliveredNotify(r):this.handleUserInfoNotify(r);t.length>0&&this.eventHub.dispatch(k,t)}handleUserInfoNotify(e){const t="subscribe_metadata_updated"===e.type||"contact_metadata_updated"===e.type||"user_metadata_updated"===e.type?e.type:"subscribe_metadata_updated"===e.eventName||"contact_metadata_updated"===e.eventName||"user_metadata_updated"===e.eventName?e.eventName:null;if(!t)return;const r=e.data;if(!r||"object"!=typeof r)return;const s=r,n="string"==typeof s.username?s.username:"string"==typeof s.userId?s.userId:"user_metadata_updated"===t?this.msyncCodec.getContext().userId:"",i=s.metadata&&"object"==typeof s.metadata&&!Array.isArray(s.metadata)?s.metadata:null,o="number"==typeof s.lastModified?s.lastModified:"string"==typeof s.lastModified?Number(s.lastModified):Number.NaN;if(!n||!i||!Number.isFinite(o))return;const a={notifyType:t,userId:n,metadata:i,lastModified:o};this.eventHub.dispatch(v,a)}handleContactNotify(e){if(Vs("[RosterSync] handleContactNotify",{eventName:e.eventName,type:e.type}),"string"!=typeof e.eventName)return;if(e.eventName!==z&&e.eventName!==H&&e.eventName!==W&&e.eventName!==J&&e.eventName!==Q)return;const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.from&&r.from&&"string"==typeof r.to&&r.to&&"string"==typeof r.message&&this.eventHub.dispatch(e.eventName,r)}handlePresenceNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t,s=Array.isArray(r.values)?r.values:[];if(0===s.length)return;const n=[];for(const i of s){if(!i||"object"!=typeof i)continue;const e=i,t=this.normalizePresenceStatus(e.status),r="string"==typeof e.uid?e.uid:"";r&&n.push({userId:r,statusDetails:t,ext:"string"==typeof e.ext?e.ext:"",lastTime:Number(e.last_time)||0,expire:Number(e.expiry)||0})}0!==n.length&&this.eventHub.dispatch(K,n)}handleGroupNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(g,r)}handleChatRoomNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"string"==typeof r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(f,r)}handleReactionNotify(e){const t=Array.isArray(e.data)?e.data:[];for(const r of t){if(!Bp(r)||"string"!=typeof r.messageId)continue;const e=this.resolveReactionConversationContext(r);e&&this.eventHub.dispatch(F,{messageId:r.messageId,conversationId:e.conversationId,conversationType:e.conversationType,from:e.from,to:e.to,reactions:this.normalizeReactionList(r.reactions),timestamp:this.normalizeTimestamp(r.ts)})}}handleConversationNotify(e){if(!Bp(e.data))return;const t=e.data;if("pin"!==t.op&&"pin_delete"!==t.op)return;const r=this.msyncCodec.getContext();if("string"==typeof t.res&&t.res===r.clientResource&&"string"==typeof t.from&&t.from===r.userId)return;const s="string"==typeof t.ext?t.ext:"",n="string"==typeof t.type?t.type:"",i="string"==typeof t.from?t.from:"",o="string"==typeof t.id?t.id:"";s&&i&&o&&this.eventHub.dispatch(B,{messageId:s,conversationId:"chat"===n?i:o,conversationType:"chat"===n?"singleChat":"groupChat",operation:"pin"===t.op?"pin":"unpin",operatorId:i,pinTime:"number"==typeof t.ts?t.ts:Number(t.ts)||void 0})}handleMultiDeviceNotify(e){if(!Bp(e.data)||"string"!=typeof e.eventName)return;const t=e.data;switch(e.eventName){case"onMultiDeviceContact":case"onMultiDeviceGroup":case"onMultiDeviceThread":case"onMultiDeviceConversation":case"onMultiDeviceMessageRemoved":return void this.eventHub.dispatch(e.eventName,t);default:return}}toMessageReceiptPayload(e){if(!Bp(e.data))return null;const t=e.data;if(!Array.isArray(t.messageIds)||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||"number"!=typeof t.timestamp)return null;const r=t.messageIds.filter(e=>"string"==typeof e&&e.length>0);if(0===r.length)return null;const s=r[0];if(!s)return null;const n=this.resolveMessageReceiptContext(s,t.conversationId,t.conversationType);if("groupChat"===n.conversationType){const e=new Set(r),s=Array.isArray(t.receiptDetails)?t.receiptDetails.flatMap(t=>{if(!Bp(t))return[];const r=t.messageId,s=t.count;return"string"==typeof r&&e.has(r)&&"number"==typeof s&&Number.isInteger(s)&&s>=0?[{messageId:r,count:s}]:[]}):[];return{messageIds:r,conversationId:n.conversationId,conversationType:"groupChat",timestamp:t.timestamp,receiptDetails:s}}return{messageIds:r,conversationId:n.conversationId,conversationType:"singleChat",timestamp:t.timestamp}}handleMessageDeliveredNotify(e){if(!Bp(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&this.eventHub.dispatch(D,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"singleChat"})}handleMessageRecalledNotify(e){if(!Bp(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&"string"==typeof t.conversationType&&this.eventHub.dispatch(P,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"chatRoom"===t.conversationType?"chatRoom":"groupChat"===t.conversationType?"groupChat":"singleChat",timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now()})}handleMessageUpdatedNotify(e){if(!Bp(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!Bp(t.message)||"string"!=typeof t.message.type||!Bp(t.message.body)||!Bp(t.message.ext))return;const r={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...Bp(t.message.modifiedInfo)?{modifiedInfo:{operatorId:"string"==typeof t.message.modifiedInfo.operatorId?t.message.modifiedInfo.operatorId:"",operationCount:"number"==typeof t.message.modifiedInfo.operationCount?t.message.modifiedInfo.operationCount:0,operationTime:"number"==typeof t.message.modifiedInfo.operationTime?t.message.modifiedInfo.operationTime:0}}:{}};this.eventHub.dispatch(x,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"chatRoom"===t.conversationType?"chatRoom":"groupChat"===t.conversationType?"groupChat":"singleChat",message:r,timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now()})}normalizeUpdatedMessageBody(e,t){if("text"!==e)return t;const r="string"==typeof t.content?t.content:"string"==typeof t.message?t.message:void 0;if(void 0===r)return t;const{message:s,...n}=t;return{...n,content:r}}handleChatThreadNotify(e){const t=e.data;if(!t||"object"!=typeof t)return;const r=t;"onChatThreadChange"===r.eventName&&r.payload&&"object"==typeof r.payload&&this.eventHub.dispatch(y,r)}normalizePresenceStatus(e){if(!e||"object"!=typeof e)return[];return Object.entries(e).map(([e,t])=>({device:e,status:Number(t)||0}))}destroy(){this.streamMessageHandler.destroy(),this.recentMessageIds.clear(),this.messageContexts.clear()}rememberMessageContext(e){const t=this.resolveMessageContextId(e),r=this.resolveMessageConversationContext(e);if(t&&r)for(this.messageContexts.delete(t),this.messageContexts.set(t,r);this.messageContexts.size>500;){const e=this.messageContexts.keys().next().value;if(!e)break;this.messageContexts.delete(e)}}resolveMessageReceiptContext(e,t,r){const s=this.messageContexts.get(e);return s||("groupChat"===r?{conversationId:t,conversationType:"groupChat"}:{conversationId:t,conversationType:"singleChat"})}resolveMessageContextId(e){return"string"==typeof e.msgServerId&&e.msgServerId.length>0?e.msgServerId:"string"==typeof e.msgLocalId&&e.msgLocalId.length>0?e.msgLocalId:""}resolveMessageConversationContext(e){if("string"!=typeof e.conversationId||!e.conversationId)return null;if("groupChat"===e.conversationType)return{conversationId:e.conversationId,conversationType:"groupChat"};if("chatRoom"===e.conversationType)return{conversationId:e.conversationId,conversationType:"chatRoom"};if("singleChat"!==e.conversationType)return null;const t=this.msyncCodec.getContext().userId,r="SEND"===e.direct||e.sender.userId===t?e.conversationId:e.sender.userId;return r?{conversationId:r,conversationType:"singleChat"}:null}resolveReactionConversationContext(e){const t="string"==typeof e.from?e.from:"",r="string"==typeof e.to?e.to:"",s="string"==typeof e.channel_type?e.channel_type:"";if(!t||!r)return null;if("groupChat"===s||"groupchat"===s||"group"===s)return{conversationId:r,conversationType:"groupChat",from:t,to:r};if(""!==s&&"chat"!==s&&"singleChat"!==s)return null;return{conversationId:t===this.msyncCodec.getContext().userId?r:t,conversationType:"singleChat",from:t,to:r}}normalizeReactionList(e){if(!Array.isArray(e))return[];const t=[];for(const r of e)Bp(r)&&"string"==typeof r.reaction&&t.push({reaction:r.reaction,count:"number"==typeof r.count&&Number.isFinite(r.count)?r.count:0,userList:Array.isArray(r.userList)?r.userList.filter(e=>"string"==typeof e):[],isAddedBySelf:"boolean"==typeof r.isAddedBySelf?r.isAddedBySelf:void 0,op:this.normalizeReactionOperations(r.op)});return t}normalizeReactionOperations(e){if(!Array.isArray(e))return;const t=[];for(const r of e)!Bp(r)||"string"!=typeof r.operator||"create"!==r.reactionType&&"delete"!==r.reactionType||t.push({operator:r.operator,reactionType:r.reactionType});return t.length>0?t:void 0}normalizeTimestamp(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){const t=Number(e);return Number.isFinite(t)?t:0}return 0}}const qp=()=>{const e=globalThis;return"function"==typeof e.fetch?e.fetch:void 0},$p=()=>ac({fetchImpl:qp()})??{request:e=>Promise.reject(un("Request capability is missing for current platform.",{code:nn,stage:Ys,retryable:!1,details:{capability:"request"}}))},jp=e=>e??$p(),Vp=e=>e instanceof Error?e.message:String(e);class Kp{constructor(e){this.requestAdapter=jp(e)}async downloadAndParse(e){const t=e.url.trim();if(!t)throw new mt("Combine message url is required",{code:ot.COMBINE_INVALID_INPUT,details:{fields:[{path:"url",message:"Combine message url is required",rule:"required"}]}});const r="number"==typeof e.maxItems?e.maxItems:300;Op(1,r);const s=_s(t,e.secret);try{const t=await this.requestAdapter.request({url:s,method:"GET",responseType:"arraybuffer",timeoutMs:e.timeoutMs??15e3,headers:{[_u]:bu()}});if(401===t.status||403===t.status)throw new pt(401===t.status?"Combine payload download unauthorized":"Combine payload download forbidden",{code:401===t.status?ot.AUTH_UNAUTHORIZED:ot.AUTH_FORBIDDEN,details:{url:s,httpStatus:t.status}});if(t.status>=400)throw new ft("Combine payload download failed",{code:ot.COMBINE_DOWNLOAD_FAILED,details:{status:t.status,url:s}});const n=(e=>{if(e.length<ip.length+1)throw new ft("Combine payload is too short",{code:ot.COMBINE_PARSE_FAILED});const t=e.subarray(0,ip.length);if(t[0]!==ip[0]||t[1]!==ip[1])throw new ft("Combine payload header is invalid",{code:ot.COMBINE_PARSE_FAILED});const r=e.subarray(0,e.length-1),s=hp(r),n=e[e.length-1]??0;if(n!==s)throw new ft("Combine payload checksum failed",{code:ot.COMBINE_PARSE_FAILED,details:{expectedChecksum:s,actualChecksum:n}});const i=[];let o=ip.length;const a=e.length-1;for(;o<a;){if(o+4>a)throw new ft("Combine payload length header is incomplete",{code:ot.COMBINE_PARSE_FAILED});const t=lp(e,o);if(o+=4,t<=0||o+t>a)throw new ft("Combine payload item length is invalid",{code:ot.COMBINE_PARSE_FAILED,details:{itemLength:t}});const r=e.subarray(o,o+t);o+=t;const s=yp(r,i.length);i.push(s)}if(o!==a)throw new ft("Combine payload has unexpected trailing bytes",{code:ot.COMBINE_PARSE_FAILED,details:{offset:o,expected:a}});return i})((e=>{if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if("string"==typeof e)return Hs(e);throw new ft("Combine payload response type is invalid",{code:ot.COMBINE_DOWNLOAD_FAILED})})(t.data));return Op(n.length,r),Mp(n),n.map(e=>({msgServerId:e.msgServerId??"",msgLocalId:e.msgLocalId??"",from:e.sender.userId,to:e.conversationId,sender:e.sender,conversationId:e.conversationId,conversationType:e.conversationType,type:e.type,sendStatus:"sent",ext:e.ext??{},timestamp:e.timestamp,body:e.body,direct:"RECEIVE"}))}catch(n){if(n instanceof mt||n instanceof pt||n instanceof ft)throw n;throw new ft("Combine payload download or parse failed",{code:ot.COMBINE_DOWNLOAD_FAILED,details:{cause:Vp(n),url:s}})}}}const zp=e=>{switch(e.type){case"image":{const t=e.body;return{url:t.originalImageUrl??t.bigImageUrl??t.thumbnailUrl??"",secret:t.secret}}case"video":case"voice":case"file":{const t=e.body;return{url:t.url??"",secret:t.secret}}default:return{url:""}}},Hp=e=>{switch(e.type){case"image":return e.body.filename??"image";case"video":return e.body.filename??"video";case"voice":return e.body.filename??"voice";case"file":return e.body.filename??"file";default:return"attachment"}},Wp=e=>{switch(e.type){case"image":case"video":case"voice":case"file":return e.body.filetype??"application/octet-stream";default:return"application/octet-stream"}};class Jp{constructor(e){this.requestAdapter=jp(e)}resolveMultiBodyTargets(e){const t=(Array.isArray(e.body)?e.body:[]).flatMap(t=>t&&mu(t.type)?[{...e,type:t.type,body:t}]:[]);if(0===t.length)throw new mt("message does not contain downloadable attachment",{code:ot.ATTACHMENT_INVALID,details:{fields:[{path:"message.type",message:"does not contain downloadable attachment",rule:"attachment_type"}]}});return t}assertHasDownloadUrl(e){const{url:t}=zp(e);if(!t)throw new mt("attachment url is required",{code:ot.ATTACHMENT_INVALID,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}})}async download(e,t=15e3){if("multi_body"===e.type){const r=this.resolveMultiBodyTargets(e);for(const e of r)this.assertHasDownloadUrl(e);const s=[];for(const e of r)s.push(await this.downloadSingle(e,t));return s}return this.downloadSingle(e,t)}async downloadSingle(e,t){if("image"!==e.type&&"video"!==e.type&&"voice"!==e.type&&"file"!==e.type)throw new mt("message does not contain downloadable attachment",{code:ot.ATTACHMENT_INVALID,details:{fields:[{path:"message.type",message:"does not contain downloadable attachment",rule:"attachment_type"}]}});const{url:r,secret:s}=zp(e);if(!r)throw new mt("attachment url is required",{code:ot.ATTACHMENT_INVALID,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}});let n;try{n=await this.requestAdapter.request({url:_s(r,s),method:"GET",responseType:"arraybuffer",timeoutMs:t,headers:{[_u]:bu()}})}catch(i){if("object"==typeof i&&null!==i&&i.code===nn)throw new lt("request adapter is required for attachment download");throw i}if(401===n.status)throw new pt("attachment download unauthorized",{code:ot.AUTH_UNAUTHORIZED,details:{url:r,httpStatus:n.status}});if(403===n.status)throw new pt("attachment download forbidden",{code:ot.AUTH_FORBIDDEN,details:{url:r,httpStatus:n.status}});if(404===n.status){const e=("string"==typeof n.data?n.data:"").includes("expired");throw new ut(e?"attachment file is expired":"attachment not found",e?ot.ATTACHMENT_EXPIRED:ot.ATTACHMENT_NOT_FOUND)}if(429===n.status)throw new ut("attachment download rate limited",ot.SERVICE_LIMIT_EXCEEDED);if(n.status>=400)throw new ut("attachment download failed",ot.FILE_DOWNLOAD_FAILED,{details:{status:n.status,url:r}});return{filename:Hp(e),mimeType:Wp(e),size:(()=>{switch(e.type){case"image":case"video":case"voice":return e.body.fileLength;case"file":return e.body.fileLength??e.body.fileSize;default:return}})(),data:new Uint8Array(n.data),downloadUrl:r}}}const Qp=(e,t,r)=>({Authorization:`Bearer ${e}`,Accept:t,[_u]:bu(),...r??{}}),Zp=async e=>{const t=Qp(e.token,"application/json",e.headers),r=Date.now(),s="upload.multipart.init"===e.operation?"REST_INIT_UPLOAD_TASK_IN_PARTS":"upload.multipart.complete"===e.operation?"REST_COMPLETE_UPLOAD_PART":"REST_ABORT_UPLOAD_PART",n=e.dataReportOperation?.startRequest({requestName:s,method:e.method,url:e.url});let i=0;Vs("Upload request start",{operation:e.operation,method:e.method});try{const s=await e.requestAdapter.request({url:e.url,method:e.method,headers:t,responseType:"json",timeoutMs:Qr});i=s.status;const a=Date.now()-r;if(s.status<200||s.status>=300)throw Ks("Upload response error",{operation:e.operation,method:e.method,status:s.status,duration:a}),new bt("Upload request failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{url:e.url,status:s.status}});Vs("Upload response success",{operation:e.operation,method:e.method,status:s.status,duration:a});const c="string"==typeof(o=s.data)?JSON.parse(o):o;return n?.finish({code:s.status,success:!0}),c}catch(a){if(n?.finish({code:0!==i?i:a instanceof bt?a.code:ot.UPLOAD_REQUEST_FAILED,success:!1,description:a instanceof Error?a.message:String(a)}),a instanceof bt)throw a;throw Ks("Upload request failed",{operation:e.operation,method:e.method}),new bt("Upload request failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{url:e.url}})}var o},Yp=async e=>{const t=Date.now(),r=e.dataReportOperation?.startRequest({requestName:"REST_UPLOAD_PART",method:"PUT",url:e.url});Vs("Upload part start",{operation:"upload.multipart.part",partNumber:e.partNumber});try{const s=await e.uploadAdapter.upload({url:e.url,method:"PUT",headers:Qp(e.token,"*/*",{"restrict-access":"true"}),source:{sourceType:"web-file",file:e.part,name:`${e.fileName}.part-${e.partNumber}`,mimeType:e.fileType,size:e.part.size},fields:{part_number:e.partNumber},fileFieldName:"part_file",timeoutMs:Qr,onProgress:t=>e.onProgress?.(t.loaded)}),n=Date.now()-t;if(s.status<200||s.status>=300)throw new bt("Upload part failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{url:e.url,partNumber:e.partNumber,status:s.status,response:s.body}});Vs("Upload part success",{operation:"upload.multipart.part",partNumber:e.partNumber,duration:n}),r?.finish({code:s.status,success:!0})}catch(s){const t=Fd(s),n=t.details&&"object"==typeof t.details?t.details:void 0;throw r?.finish({code:t.code,success:!1,description:t.message}),Ks("Upload part failed",{operation:"upload.multipart.part",partNumber:e.partNumber}),new bt(t.message,{code:t.code,details:{...n,url:e.url,partNumber:e.partNumber}})}},Xp=async e=>{if(e.fileSize<=as)throw new bt("Multipart not required",{code:ot.UPLOAD_REQUEST_FAILED,details:{reason:"file size below threshold"}});const{config:t,file:r,conversationId:s,conversationType:n,fileName:i,fileType:o,fileSize:a,messageType:c,imageType:d,md5:u,width:l,height:h}=e,p=(e=>jp(e))(t.requestAdapter),m=(e=>{if(e)return e;const t=Ic();if(t)return t;throw new bt("Upload adapter is required for multipart upload",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{capability:"upload"}})})(t.uploadAdapter),{orgName:g,appName:f}=fs(t.appKey),y=`${t.restBaseUrl}/${g}/${f}/sdk/chatfiles/part-upload`;let v;try{v=await Zp({url:y,method:"POST",token:t.token,operation:"upload.multipart.init",requestAdapter:p,dataReportOperation:e.dataReportOperation})}catch(O){throw new bt("Multipart init failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{stage:"init",cause:O,url:y}})}const I=(e=>{const t=e.entities?.[0],r="number"==typeof t?.file_upper_limit?t.file_upper_limit:0,s="number"==typeof t?.part_lower_limit?t.part_lower_limit:cs,n="string"==typeof t?.uuid?t.uuid:"";if(!n)throw new bt("Multipart init failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{response:e}});return{fileMaxSize:r,partMinSize:s,uuid:n}})(v);if(I.fileMaxSize&&a>I.fileMaxSize)throw new bt("File size exceeds limit",{code:ot.UPLOAD_SIZE_EXCEEDED,details:{fileSize:a,maxSize:I.fileMaxSize}});const b=I.partMinSize||cs,_=Math.ceil(a/b),T=Array.from({length:_},()=>0),C=`${t.restBaseUrl}/${g}/${f}/sdk/chatfiles/part-upload/${I.uuid}`,S=[],E=(t,r)=>{T[t]=r;const s=T.reduce((e,t)=>e+t,0),n=a?s/a*100:void 0;e.callbacks?.onFileUploadProgress?.({loaded:s,total:a,percent:n})};for(let M=0;M<_;M+=1){const s=M*b,n=Math.min(a,s+b),c=r.slice(s,n),d=String(M+1),u=Yp({url:C,token:t.token,partNumber:d,part:c,fileName:i,fileType:o,uploadAdapter:m,onProgress:e=>E(M,e),dataReportOperation:e.dataReportOperation}).finally(()=>{const e=S.indexOf(u);e>=0&&S.splice(e,1)});S.push(u),S.length>=4&&await Promise.race(S)}await Promise.all(S);const w=ys(n),A=bs(`${t.restBaseUrl}/${g}/${f}/sdk/chatfiles/part-upload/${I.uuid}`,{"restrict-access":"true","chat-type":w,"chat-target":s,"thumbnail-width":e.thumbnailWidth,"thumbnail-height":e.thumbnailHeight,md5:u??"",..."image"===c?{imageType:Ss(d),width:l,height:h}:{}}),R=await Zp({url:A,method:"POST",token:t.token,operation:"upload.multipart.complete",requestAdapter:p,dataReportOperation:e.dataReportOperation}),N=ws({response:R,restBaseUrl:t.restBaseUrl,orgName:g,appName:f,fileType:o,fileName:i,fallbackSize:a,messageType:c,imageType:d,useCustomAttachmentUpload:t.useCustomAttachmentUpload});return e.callbacks?.onFileUploadComplete?.(N),N},em=async e=>{const{config:t,file:r,conversationId:s,conversationType:n,messageType:i,imageType:o,md5:a,width:c,height:d,fileName:u,fileType:l,fileSize:h}=e,p=(e=>{if(e)return e;const t=Ic();if(t)return t;throw new bt("Upload adapter is required for simple upload",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{capability:"upload"}})})(t.uploadAdapter),{orgName:m,appName:g}=fs(t.appKey),f=ys(n),y=bs(`${t.restBaseUrl}/${m}/${g}/chatfiles`,{"chat-type":f,"chat-target":s,md5:a??"",..."image"===i?{imageType:Ss(o),width:c,height:d}:{}}),v=Date.now(),I=e.dataReportOperation?.startRequest({requestName:"UPLOAD_MSG_ATTACH",method:"POST",url:y});Vs("Upload request start",{operation:"upload.simple",method:"POST",fileSize:h,messageType:i});const b={};let _;void 0!==e.thumbnailWidth&&(b["thumbnail-width"]=String(e.thumbnailWidth)),void 0!==e.thumbnailHeight&&(b["thumbnail-height"]=String(e.thumbnailHeight));try{_=await p.upload({url:y,method:"POST",headers:{"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${t.token}`,[_u]:bu()},source:{sourceType:"web-file",file:r,name:u,mimeType:l,size:h},fields:b,fileFieldName:"file",timeoutMs:Qr,onProgress:t=>e.callbacks?.onFileUploadProgress?.(t)})}catch(T){const t=Fd(T),r=t.details&&"object"==typeof t.details?t.details:void 0,s=new bt(t.message,{code:t.code,details:{...r,url:y,...t.code===ot.UPLOAD_TIMEOUT?{timeout:Qr}:{}}});throw I?.finish({code:s.code,success:!1,description:s.message}),s.code===ot.UPLOAD_ABORTED?(Ks("Upload request aborted",{operation:"upload.simple"}),e.callbacks?.onFileUploadCanceled?.()):s.code===ot.UPLOAD_TIMEOUT?Ks("Upload request timeout",{operation:"upload.simple",timeout:Qr}):Ks("Upload request failed",{operation:"upload.simple"}),s}try{const r=JSON.parse(_.body),s=Date.now()-v;if(_.status>=400)throw Ks("Upload response error",{operation:"upload.simple",status:_.status,duration:s}),new bt("Upload failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{status:_.status,response:r}});Vs("Upload response success",{operation:"upload.simple",status:_.status,duration:s});const n=ws({response:r,restBaseUrl:t.restBaseUrl,orgName:m,appName:g,fileType:l,fileName:u,fallbackSize:h,messageType:i,imageType:o,useCustomAttachmentUpload:t.useCustomAttachmentUpload});return e.callbacks?.onFileUploadComplete?.(n),I?.finish({code:_.status||200,success:!0}),n}catch(T){throw I?.finish({code:T instanceof bt?T.code:ot.UPLOAD_REQUEST_FAILED,success:!1,description:T instanceof Error?T.message:String(T)}),T instanceof Error?T:new Error(String(T))}},tm=kc(),rm=e=>Object.prototype.toString.call(e),sm=e=>{const t=e&&"object"==typeof e?e:null,r="string"==typeof t?.path?t.path:void 0,s="string"==typeof t?.uri?t.uri:void 0,n="string"==typeof t?.name?t.name:void 0,i="string"==typeof t?.type?t.type:void 0,o="number"==typeof t?.size?t.size:void 0;return{kind:rm(e),isFile:"undefined"!=typeof File&&e instanceof File,isBlob:"undefined"!=typeof Blob&&e instanceof Blob,hasPath:"string"==typeof r&&r.length>0,pathPrefix:r?r.slice(0,48):void 0,hasUri:"string"==typeof s&&s.length>0,uriPrefix:s?s.slice(0,48):void 0,name:n,type:i,size:o}},nm=e=>({sourceType:e.source.sourceType,fileName:e.fileName,fileType:e.fileType,fileSize:e.fileSize,hasWebFile:Boolean(e.webFile),sourceName:e.source.name,sourceMimeType:e.source.mimeType,sourceSize:e.source.size}),im=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,om=e=>"object"==typeof e&&null!==e,am=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,cm=e=>"number"==typeof e.total&&e.total>0?am(e.loaded/e.total):"number"==typeof e.percent?am(e.percent/100):0,dm=e=>{if("number"==typeof e&&Number.isFinite(e)&&e>=0)return e},um=(e,t)=>{const r=om(t)?t:void 0,s=r?.code===nn&&r.stage===rn,n=r?.code===an&&r.stage===rn;return"miniapp-path"===e&&((e=>{if(!om(e))return!1;const t=om(e.details)?e.details:void 0;return e.code===nn&&e.stage===rn&&"string"==typeof t?.capability&&t.capability.includes("FileSystem")})(t)||n)||"rn-uri"===e&&s};class lm{constructor(e){this.config=e??null}updateConfig(e){this.config=e}updateAuthToken(e){this.config&&(this.config={...this.config,token:e})}async prepareMessage(e,t){if("multi_body"===e.type)return this.prepareMultiBodyMessage(e,t);if(!im(e.type))return e;const r=e.body;if(this.hasUploadedRemoteResource(e.type,r))return e;const s=this.resolveUploadUrl(e.type,r),n=rp.get(e.msgLocalId),i=Boolean(n);if(Ks("Attachment upload prepare entry",{operation:"upload.prepare.entry",msgLocalId:e.msgLocalId,messageType:e.type,conversationType:e.conversationType,hasFile:i,uploadUrl:s,cachedFile:sm(n),adapter:{hasRequestAdapter:Boolean(this.config?.requestAdapter),hasUploadAdapter:Boolean(this.config?.uploadAdapter),hasImageProcessor:Boolean(this.config?.imageProcessor),restBaseUrl:Boolean(this.config?.restBaseUrl),useCustomAttachmentUpload:this.config?.useCustomAttachmentUpload}}),!((e,t)=>!!t||!e||!gs(e))(s,i))return e;if(!n)throw new bt("Attachment file is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{msgLocalId:e.msgLocalId,url:s}});if(!this.config?.restBaseUrl)throw new bt("REST base url is required for upload",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"restBaseUrl missing"}});let o,a,c;try{o=await this.prepareAttachmentUpload(e,r,n),o.precheck?.hit||(c=Zh({operationName:"UPLOAD_MSG_ATTACH",operationType:"REST",msgId:e.msgLocalId,messageType:e.type})),a=o.precheck?.hit?this.buildPrecheckedUploadResult(e,o,t):await this.uploadAttachment(e,o,t,c),c?.finish({code:0,success:!0})}catch(d){const e=Fd(d);throw c?.finish({code:e.code,success:!1,description:e.message}),e.code===ot.UPLOAD_ABORTED&&t?.onFileUploadCanceled?.(),t?.onFileUploadError?.(e),e}return this.buildPreparedMessage(e,o,a)}async prepareMultiBodyMessage(e,t){const r=e.body,s=r.flatMap((e,t)=>e&&mu(e.type)?[t]:[]),n=r.map((t,r)=>{if(!t||!mu(t.type))return 0;return((e,t)=>{const r=dm(om(e)?e.size:void 0);if(void 0!==r)return r;const s=t;return dm(s.fileLength)??dm(s.fileSize)??0})(rp.get(cu(e.msgLocalId,r)),t)}),i=n.reduce((e,t)=>e+t,0);let o=0;const a=e=>{i<=0||t?.onFileUploadProgress?.({loaded:e,total:i,percent:e/i*100})};Ks("MultiBody attachment prepare started",{operation:"upload.multibody.prepare",msgLocalId:e.msgLocalId,segmentCount:r.length,segmentTypes:r.map(e=>e?.type),uploadIndexes:s,totalSize:i});for(let d=0;d<r.length;d+=1){const s=r[d];if(!s||!mu(s.type))continue;const u=n[d]??0,l={...e,type:s.type,msgLocalId:cu(e.msgLocalId,d),body:s};try{const n=await this.prepareMessage(l,this.withSegmentCallbacks({...t,onFileUploadProgress:e=>{i<=0?t?.onFileUploadProgress?.(e):a(o+cm(e)*u)}},e.msgLocalId));r[d]={...n.body,type:s.type},o+=u,a(o)}catch(c){throw Ks("MultiBody attachment segment failed",{operation:"upload.multibody.segment_failed",msgLocalId:e.msgLocalId,bodyIndex:d,segmentType:s.type,cause:c instanceof Error?c.message:String(c)}),gu(c,e.msgLocalId),c}}return e}withSegmentCallbacks(e,t){return{onFileUploadProgress:t=>{e?.onFileUploadProgress?.(t)},onFileUploadComplete:t=>{e?.onFileUploadComplete?.(t)},onFileUploadError:r=>{gu(r,t),e?.onFileUploadError?.(r)},onFileUploadCanceled:()=>{e?.onFileUploadCanceled?.()}}}resolveUploadUrl(e,t){if("image"===e){const e=t;return("string"==typeof e.localUrl?e.localUrl.trim():"")||("string"==typeof e.originalImageUrl?e.originalImageUrl.trim():"")}return"url"in t&&"string"==typeof t.url?t.url.trim():""}hasUploadedRemoteResource(e,t){if("image"===e){const e=t;return"string"==typeof e.originalImageUrl&&gs(e.originalImageUrl)}return"url"in t&&"string"==typeof t.url&&gs(t.url)}async prepareAttachmentUpload(e,t,r){const s=((e,t)=>{if(!e)throw new bt("Attachment file is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"file missing"}});const r=("number"==typeof t.fileLength?t.fileLength:void 0)??("fileSize"in t&&"number"==typeof t.fileSize?t.fileSize:void 0),s=os({file:e,fallbackName:t.filename,fallbackMimeType:t.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new bt("Attachment file is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"web file missing"}});return s})(r,t);if(Ks("Attachment file normalized",{operation:"upload.prepare.normalized",messageType:e.type,fileInfo:nm(s)}),"image"!==e.type){return{body:t,fileInfo:s,md5FileInfo:s,precheck:await this.maybePrecheck(e,s,s,void 0)}}const n=t,i=await this.resolveImageCandidate(n,s),o={...n,width:i.width,height:i.height,isOriginalImage:i.imagePolicy.resolvedImageType===ps},a=await this.maybePrecheck(e,i.fileInfo,s,i.imagePolicy.resolvedImageType);return{body:o,fileInfo:i.fileInfo,md5FileInfo:s,imageType:i.imagePolicy.resolvedImageType,precheck:a,originalWidth:n.width,originalHeight:n.height}}async resolveImageCandidate(e,t){const r=(e=>e.isGif?{resolvedImageType:ps,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:ps,reason:"explicit-original"}:{resolvedImageType:ms,reason:"default-large"})(e);if(Ks("Image send policy resolved",{operation:"upload.image.policy",reason:r.reason,imageType:r.resolvedImageType,isGif:e.isGif,source:nm(t)}),r.resolvedImageType===ps){let s=e.width,n=e.height;if(!s||!n){const e=this.resolveImageProcessor(t.source.sourceType);Ks("Image original info resolving",{operation:"upload.image.info",processorSourceType:t.source.sourceType,source:nm(t)});const r=await e.getImageInfo(t.source);s=r.width,n=r.height}return{imagePolicy:r,sourceKind:"origin",fileInfo:t,width:s,height:n}}try{const e=this.resolveImageProcessor(t.source.sourceType);Ks("Image big generation start",{operation:"upload.image.big.start",processorSourceType:t.source.sourceType,source:nm(t)});const s=await e.generateBigImage(t.source,{maxShortEdge:720,quality:.85});return{imagePolicy:r,sourceKind:"big",fileInfo:{source:s.source,fileName:s.fileName??t.fileName,fileType:s.fileType??t.fileType,fileSize:s.fileSize??t.fileSize,webFile:s.webFile},width:s.width,height:s.height}}catch(s){return Ks("Image big generation failed, fallback to original",{operation:"upload.image.big-fallback",reason:r.reason,error:s instanceof Error?s.message:String(s),source:nm(t)}),{imagePolicy:{resolvedImageType:ps,reason:"large-fallback-origin"},sourceKind:"origin",fileInfo:t,width:e.width??0,height:e.height??0}}}async maybePrecheck(e,t,r,s){if(!im(e.type))return;if(!0!==this.config?.enableMd5Check)return void Vs("Attachment precheck skipped because MD5 check is disabled",{operation:"upload.precheck.skip",reason:"md5-check-disabled",messageType:e.type,imageType:s,fileSize:t.fileSize});const n=Ts({messageType:e.type,fileSize:t.fileSize,imageType:s});if(!n.shouldPrecheck)return void Vs("Attachment precheck skipped",{operation:"upload.precheck.skip",messageType:e.type,imageType:s,fileSize:t.fileSize,thresholdBytes:n.thresholdBytes});let i;try{i=await this.computeMd5(r)}catch(a){if(um(r.source.sourceType,a))return void Ks("Attachment precheck skipped because md5 is unavailable",{operation:"upload.precheck.md5-unavailable",messageType:e.type,imageType:s,thresholdType:n.thresholdType,source:nm(r),error:a instanceof Error?a.message:String(a)});throw a}const o=await this.requestPrecheck(e,n.thresholdType,i,s);return Vs(o.hit?"Attachment precheck hit":"Attachment precheck miss",{operation:o.hit?"upload.precheck.hit":"upload.precheck.miss",messageType:e.type,imageType:s,exists:o.exists,existsType:o.existsType,uuid:o.uuid,hasShareSecret:"string"==typeof o.shareSecret&&o.shareSecret.length>0}),{...o,md5:i}}async computeMd5(e){const t=this.resolveImageProcessor(e.source.sourceType);return Ks("Attachment md5 compute start",{operation:"upload.md5.start",source:nm(e)}),t.computeMd5(e.source)}resolveImageProcessor(e){if(this.config?.imageProcessor)return Ks("Image processor resolved from platform adapter",{operation:"upload.image.processor",sourceType:e,processor:"platform"}),this.config.imageProcessor;if("web-file"===e)return Ks("Image processor resolved from web fallback",{operation:"upload.image.processor",sourceType:e,processor:"web-fallback"}),tm;throw Ks("Image processor missing",{operation:"upload.image.processor-missing",sourceType:e}),un("Image processor capability is missing for current platform",{code:nn,stage:rn,retryable:!1,details:{capability:"imageProcessor",sourceType:e}})}async requestPrecheck(e,t,r,s){if(!this.config)throw new bt("Upload config is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:n,appName:i}=fs(this.config.appKey),o=bs(`${this.config.restBaseUrl}/${n}/${i}/chatfiles/exists`,{md5:r,..."image"===e.type?{imageType:Ss(s)}:{}}),a=await this.requestJson({url:o,method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,Accept:"application/json"},operation:"upload.precheck"}).catch(n=>{Ks("Attachment precheck failed, fallback to upload",{operation:"upload.precheck.fail-open",messageType:e.type,imageType:s,thresholdType:t,md5:r,error:n instanceof Error?n.message:String(n)})});return a?(e=>{const t=e.entities?.[0],r=!0===t?.exists,s="string"==typeof t?.uuid&&t.uuid.length>0?t.uuid:void 0,n=t,i=n?.["exists-type"]??n?.existsType,o="origin"===i?ps:i===ms||i===ps?i:void 0,a="string"==typeof t?.["share-secret"]?t["share-secret"]:void 0;if(r&&!s)throw new bt("Upload precheck response missing uuid",{code:ot.UPLOAD_REQUEST_FAILED,details:{response:e}});return{uuid:s,exists:r,existsType:o,shareSecret:a,hit:(c={exists:r,uuid:s},c.exists&&"string"==typeof c.uuid&&c.uuid.length>0)};var c})(a):{exists:!1,hit:!1}}async requestJson(e){return this.requestByAdapter(jp(this.config?.requestAdapter),e)}async requestByAdapter(e,t){const r=await e.request({url:t.url,method:t.method,headers:t.headers,responseType:"json",timeoutMs:Qr});if(r.status>=400)throw new bt("Upload precheck request failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{url:t.url,status:r.status,operation:t.operation}});return"string"==typeof r.data?JSON.parse(r.data):r.data}buildPrecheckedUploadResult(e,t,r){if(!this.config||!t.precheck)throw new bt("Precheck result is required",{code:ot.UPLOAD_REQUEST_FAILED});if(!t.precheck.uuid)throw new bt("Precheck hit missing uuid",{code:ot.UPLOAD_REQUEST_FAILED,details:{precheck:t.precheck}});if(!im(e.type))throw new bt("Attachment message type is invalid",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:e.type}});const{orgName:s,appName:n}=fs(this.config.appKey),i="image"===e.type?t.precheck.existsType??t.imageType:void 0,o="image"===e.type&&i===ps?t.md5FileInfo:t.fileInfo,a="image"===e.type&&i===ps?t.originalWidth:"image"===e.type?t.body.width:void 0,c="image"===e.type&&i===ps?t.originalHeight:"image"===e.type?t.body.height:void 0,d={entities:[{uuid:t.precheck.uuid,...t.precheck.shareSecret?{"share-secret":t.precheck.shareSecret}:{}}]},u=ws({response:d,restBaseUrl:this.config.restBaseUrl,orgName:s,appName:n,fileType:o.fileType,fileName:o.fileName,fallbackSize:o.fileSize,messageType:e.type,imageType:i,width:a,height:c,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return r?.onFileUploadComplete?.(u),u}async uploadAttachment(e,t,r,s){if(!this.config)throw new bt("Upload config is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING});if(!im(e.type))throw new bt("Attachment message type is invalid",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:e.type}});const n=e.type,i=await this.resolveUploadMetadata(n,t);if(!t.fileInfo.webFile){if(this.config.uploadAdapter)return this.uploadByAdapter(this.config.uploadAdapter,e,t,i,r);throw new bt("Upload adapter is required for non-web file source",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{sourceType:t.fileInfo.source.sourceType}})}const o={message:e,file:t.fileInfo.webFile,conversationId:e.conversationId,conversationType:e.conversationType,messageType:n,imageType:t.imageType,md5:i.md5,width:i.width,height:i.height,fileName:t.fileInfo.fileName,fileType:t.fileInfo.fileType,fileSize:t.fileInfo.fileSize,thumbnailWidth:this.resolveThumbnailWidth(n,t.body),thumbnailHeight:this.resolveThumbnailHeight(n,t.body),callbacks:r,config:this.config,dataReportOperation:s},a=!1!==this.config?.enableMultipartUpload,c=a&&t.fileInfo.fileSize>as;if(Ks("Attachment web upload selected",{operation:"upload.web.selected",messageType:n,source:nm(t.fileInfo),multipartEnabled:a,uploadMode:c?"multipart":"simple"}),c)try{return await Xp(o)}catch(d){const e=d instanceof bt?d.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return em(o);throw d}return this.config.uploadAdapter?(Ks("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:n,source:nm(t.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,e,t,i,r)):em(o)}async uploadByAdapter(e,t,r,s,n){if(!this.config)throw new bt("Upload config is required",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING});const{orgName:i,appName:o}=fs(this.config.appKey),a=ys(t.conversationType);if(!im(t.type))throw new bt("Attachment message type is invalid",{code:ot.UPLOAD_REQUIRED_FIELD_MISSING,details:{messageType:t.type}});const c=t.type,d=bs(`${this.config.restBaseUrl}/${i}/${o}/chatfiles`,{"chat-type":a,"chat-target":t.conversationId,md5:s.md5,..."image"===c?{imageType:Ss(r.imageType),width:s.width,height:s.height}:{}}),u={},l={"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${this.config.token}`,[_u]:bu()},h=this.resolveThumbnailWidth(c,r.body),p=this.resolveThumbnailHeight(c,r.body);void 0!==h&&(u["thumbnail-width"]=String(h)),void 0!==p&&(u["thumbnail-height"]=String(p)),Ks("Attachment adapter upload start",{operation:"upload.adapter.start",messageType:c,source:nm(r.fileInfo),uploadUrl:d,fields:u});const m=await e.upload({url:d,headers:l,source:r.fileInfo.source,fields:u,onProgress:e=>{n?.onFileUploadProgress?.(e)}});if(m.status>=400){const e=m.body??"",t=413===m.status?ot.FILE_TOO_LARGE:"string"==typeof e&&e.includes("content improper")?ot.FILE_CONTENT_IMPROPER:ot.UPLOAD_REQUEST_FAILED;throw new bt("Upload failed",{code:t,details:{status:m.status,response:m.body}})}let g;try{g=JSON.parse(m.body)}catch(y){throw new bt("Upload response parse failed",{code:ot.UPLOAD_REQUEST_FAILED,details:{response:m.body,cause:y instanceof Error?y.message:String(y)}})}const f=ws({response:g,restBaseUrl:this.config.restBaseUrl,orgName:i,appName:o,fileType:r.fileInfo.fileType,fileName:r.fileInfo.fileName,fallbackSize:r.fileInfo.fileSize,messageType:c,imageType:r.imageType,width:s.width,height:s.height,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload});return n?.onFileUploadComplete?.(f),f}buildPreparedMessage(e,t,r){if("image"===e.type){const s=t.body,n={...e,body:{...s,isOriginalImage:r.isOriginalImage??s.isOriginalImage,originalImageUrl:r.originalImageUrl??s.originalImageUrl,bigImageUrl:r.bigImageUrl??s.bigImageUrl,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename,thumbnailUrl:r.thumbnailUrl??s.thumbnailUrl,width:r.width??s.width,height:r.height??s.height}};return ml(e,n),Il(e,n),n}if("video"===e.type){const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename,thumbnailUrl:r.thumbnailUrl??s.thumbnailUrl}};return ml(e,n),n}if("voice"===e.type){const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename}};return ml(e,n),n}if("combine"===e.type){const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename}};return ml(e,n),n}const s=t.body,n={...e,body:{...s,url:r.url,secret:r.secret??s.secret,fileLength:r.fileLength??s.fileLength??t.fileInfo.fileSize,filetype:r.filetype??s.filetype,filename:r.filename??s.filename}};return ml(e,n),n}resolveThumbnailWidth(e,t){if("video"===e){const e="width"in t?t.width:void 0;return"number"==typeof e&&e>0?e:void 0}}resolveThumbnailHeight(e,t){if("video"===e){const e="height"in t?t.height:void 0;return"number"==typeof e&&e>0?e:void 0}}async resolveUploadMetadata(e,t){let r=t.precheck?.md5??"";if(!t.precheck)try{r=await this.computeMd5(t.md5FileInfo)}catch(n){if(!um(t.md5FileInfo.source.sourceType,n))throw n;Ks("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:nm(t.md5FileInfo),error:n instanceof Error?n.message:String(n)})}const s=t.body;return{md5:r,width:"image"===e&&"number"==typeof s.width&&s.width>0?s.width:void 0,height:"image"===e&&"number"==typeof s.height&&s.height>0?s.height:void 0}}}class hm{constructor(e,t){this.unsubscribeNetwork=null,this.unsubscribeVisibility=null,this.lastOnline=null,this.lastForeground=null,this.runtime=e,this.handlers=t}start(){this.unsubscribeNetwork||this.unsubscribeVisibility||(this.unsubscribeNetwork=this.runtime.onNetworkChange(e=>{this.handleNetworkChange(e)}),this.unsubscribeVisibility=this.runtime.onAppVisibilityChange(e=>{this.handleVisibilityChange(e)}))}stop(){this.unsubscribeNetwork?.(),this.unsubscribeVisibility?.(),this.unsubscribeNetwork=null,this.unsubscribeVisibility=null,this.lastOnline=null,this.lastForeground=null}handleNetworkChange(e){this.lastOnline!==e&&(this.lastOnline=e,e?this.handlers.onOnline():this.handlers.onOffline())}handleVisibilityChange(e){this.lastForeground!==e&&(this.lastForeground=e,e?this.handlers.onForeground():this.handlers.onBackground())}}const pm="__internal:core";class mm{constructor(e,t){this.runtimeEventBridge=null,this.handleOnline=()=>{this.connectionManager.handleOnline()},this.handleOffline=()=>{this.connectionManager.handleOffline()},this.handleForegroundChange=e=>{e&&this.connectionManager.handleForeground()},this.eventHub=t,this.connectionManager=new tp({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const r=this.connectionManager.getMsyncCodec(),s=e.restBaseUrl?new lm({restBaseUrl:e.restBaseUrl,token:e.token,appKey:e.appKey,useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,enableMultipartUpload:e.enableMultipartUpload,requestAdapter:e.platformAdapter?.request,uploadAdapter:e.platformAdapter?.upload,imageProcessor:e.platformAdapter?.imageProcessor}):void 0;this.messageSender=new Dp(r,null,this.eventHub,s),this.messageReceiver=new Gp(r,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new Kp(e.platformAdapter?.request),this.attachmentDownloader=new Jp(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(pm,{[a]:e=>{const t=this.connectionManager.getWebSocket();t&&this.messageSender.setWebSocket(t)},[c]:e=>{this.messageSender.setWebSocket(null)},[d]:e=>{this.messageSender.setWebSocket(null)},[I]:e=>{this.messageReceiver.rememberSentMessageContext(e)}})}registerNetworkListeners(){const e=this.resolveRuntimeAdapter();this.runtimeEventBridge=new hm(e,{onOnline:this.handleOnline,onOffline:this.handleOffline,onForeground:()=>{this.handleForegroundChange(!0)},onBackground:()=>{this.handleForegroundChange(!1)}}),this.runtimeEventBridge.start()}unregisterNetworkListeners(){this.runtimeEventBridge?.stop(),this.runtimeEventBridge=null}resolveRuntimeAdapter(){return this.platformAdapter?this.platformAdapter.runtime:this.createBrowserRuntimeAdapter()}createBrowserRuntimeAdapter(){return{getPlatform:()=>"web",onNetworkChange(e){if("undefined"==typeof window)return()=>{};const t=()=>{e(!0)},r=()=>{e(!1)};return window.addEventListener("online",t),window.addEventListener("offline",r),"undefined"!=typeof navigator&&"boolean"==typeof navigator.onLine&&e(navigator.onLine),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",r)}},onAppVisibilityChange(e){if("undefined"==typeof document)return()=>{};const t=()=>{e("visible"===document.visibilityState)};return document.addEventListener("visibilitychange",t),t(),()=>{document.removeEventListener("visibilitychange",t)}}}}async connect(e){return this.connectionManager.connect(e)}async disconnect(){return this.connectionManager.disconnect()}getConnectionStatus(){return this.connectionManager.getConnectionStatus()}recoverConnectionForSend(){return this.connectionManager.recoverConnectionForSend()}getClientResource(){return this.connectionManager.getClientResource()}renewToken(e,t){const r=this.connectionManager.renewToken(e,t);return this.messageSender.updateAuthToken(e),r}async sendMessage(e,t){return this.messageSender.sendMessage(e,t)}async sendMessageAction(e,t){return this.messageSender.sendAction(e,t)}async sendChatRoomOperation(e,t){return this.messageSender.sendChatRoomOperation(e,t)}async downloadAndParseCombineMessage(e){return this.combineMessageDownloader.downloadAndParse(e)}async downloadAttachment(e,t){return this.attachmentDownloader.download(e,t)}decodeServerMessageMeta(e){return this.connectionManager.getMsyncCodec().decodeServerMessageMeta(e)}destroy(){this.unregisterNetworkListeners(),this.connectionManager.destroy(),this.messageSender.destroy(),this.messageReceiver.destroy(),this.eventHub.removeEventHandler(pm),rp.clear()}}var gm,fm,ym;(fm=gm||(gm={})).assertEqual=e=>{},fm.assertIs=function(e){},fm.assertNever=function(e){throw new Error},fm.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},fm.getValidEnumValues=e=>{const t=fm.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(const s of t)r[s]=e[s];return fm.objectValues(r)},fm.objectValues=e=>fm.objectKeys(e).map(function(t){return e[t]}),fm.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},fm.find=(e,t)=>{for(const r of e)if(t(r))return r},fm.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,fm.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},fm.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(ym||(ym={})).mergeShapes=(e,t)=>({...e,...t});const vm=gm.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Im=e=>{switch(typeof e){case"undefined":return vm.undefined;case"string":return vm.string;case"number":return Number.isNaN(e)?vm.nan:vm.number;case"boolean":return vm.boolean;case"function":return vm.function;case"bigint":return vm.bigint;case"symbol":return vm.symbol;case"object":return Array.isArray(e)?vm.array:null===e?vm.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?vm.promise:"undefined"!=typeof Map&&e instanceof Map?vm.map:"undefined"!=typeof Set&&e instanceof Set?vm.set:"undefined"!=typeof Date&&e instanceof Date?vm.date:vm.object;default:return vm.unknown}},bm=gm.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class _m extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},s=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)r._errors.push(t(n));else{let e=r,s=0;for(;s<n.path.length;){const r=n.path[s];s===n.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(n))):e[r]=e[r]||{_errors:[]},e=e[r],s++}}};return s(this),r}static assert(e){if(!(e instanceof _m))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,gm.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const s of this.issues)if(s.path.length>0){const r=s.path[0];t[r]=t[r]||[],t[r].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}_m.create=e=>new _m(e);const Tm=(e,t)=>{let r;switch(e.code){case bm.invalid_type:r=e.received===vm.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case bm.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,gm.jsonStringifyReplacer)}`;break;case bm.unrecognized_keys:r=`Unrecognized key(s) in object: ${gm.joinValues(e.keys,", ")}`;break;case bm.invalid_union:r="Invalid input";break;case bm.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${gm.joinValues(e.options)}`;break;case bm.invalid_enum_value:r=`Invalid enum value. Expected ${gm.joinValues(e.options)}, received '${e.received}'`;break;case bm.invalid_arguments:r="Invalid function arguments";break;case bm.invalid_return_type:r="Invalid function return type";break;case bm.invalid_date:r="Invalid date";break;case bm.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:gm.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case bm.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case bm.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case bm.custom:r="Invalid input";break;case bm.invalid_intersection_types:r="Intersection results could not be merged";break;case bm.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case bm.not_finite:r="Number must be finite";break;default:r=t.defaultError,gm.assertNever(e)}return{message:r}};let Cm=Tm;function Sm(e,t){const r=Cm,s=(e=>{const{data:t,path:r,errorMaps:s,issueData:n}=e,i=[...r,...n.path||[]],o={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let a="";const c=s.filter(e=>!!e).slice().reverse();for(const d of c)a=d(o,{data:t,defaultError:a}).message;return{...n,path:i,message:a}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Tm?void 0:Tm].filter(e=>!!e)});e.common.issues.push(s)}class Em{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if("aborted"===s.status)return wm;"dirty"===s.status&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const s of t){const e=await s.key,t=await s.value;r.push({key:e,value:t})}return Em.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:t,value:n}=s;if("aborted"===t.status)return wm;if("aborted"===n.status)return wm;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!s.alwaysSet||(r[t.value]=n.value)}return{status:e.value,value:r}}}const wm=Object.freeze({status:"aborted"}),Am=e=>({status:"dirty",value:e}),Rm=e=>({status:"valid",value:e}),Nm=e=>"aborted"===e.status,Om=e=>"dirty"===e.status,Mm=e=>"valid"===e.status,Um=e=>"undefined"!=typeof Promise&&e instanceof Promise;var Lm,km;(km=Lm||(Lm={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},km.toString=e=>"string"==typeof e?e:e?.message;class Dm{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Pm=(e,t)=>{if(Mm(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new _m(e.common.issues);return this._error=t,this._error}}};function xm(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:s,description:n}=e;if(t&&(r||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??s??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??r??n.defaultError}},description:n}}class Fm{get description(){return this._def.description}_getType(e){return Im(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Im(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Em,ctx:{common:e.parent.common,data:e.data,parsedType:Im(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Um(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Im(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Pm(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Im(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return Mm(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Mm(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Im(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await(Um(s)?s:Promise.resolve(s));return Pm(r,n)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const n=e(t),i=()=>s.addIssue({code:bm.custom,...r(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(i(),!1)):!!n||(i(),!1)})}refinement(e,t){return this._refinement((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1))}_refinement(e){return new xg({schema:this,typeName:Wg.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Fg.create(this,this._def)}nullable(){return Bg.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return _g.create(this)}promise(){return Pg.create(this,this._def)}or(e){return Sg.create([this,e],this._def)}and(e){return wg.create(this,e,this._def)}transform(e){return new xg({...xm(this._def),schema:this,typeName:Wg.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Gg({...xm(this._def),innerType:this,defaultValue:t,typeName:Wg.ZodDefault})}brand(){return new jg({typeName:Wg.ZodBranded,type:this,...xm(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new qg({...xm(this._def),innerType:this,catchValue:t,typeName:Wg.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Vg.create(this,e)}readonly(){return Kg.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Bm=/^c[^\s-]{8,}$/i,Gm=/^[0-9a-z]+$/,qm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$m=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,jm=/^[a-z0-9_-]{21}$/i,Vm=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Km=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,zm=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Hm;const Wm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Jm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Qm=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Zm=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ym=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Xm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,eg="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",tg=new RegExp(`^${eg}$`);function rg(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function sg(e){return new RegExp(`^${rg(e)}$`)}function ng(e){let t=`${eg}T${rg(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function ig(e,t){return!("v4"!==t&&t||!Wm.test(e))||!("v6"!==t&&t||!Qm.test(e))}function og(e,t){if(!Vm.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(s));return"object"==typeof n&&null!==n&&((!("typ"in n)||"JWT"===n?.typ)&&(!!n.alg&&(!t||n.alg===t)))}catch{return!1}}function ag(e,t){return!("v4"!==t&&t||!Jm.test(e))||!("v6"!==t&&t||!Zm.test(e))}class cg extends Fm{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==vm.string){const t=this._getOrReturnCtx(e);return Sm(t,{code:bm.invalid_type,expected:vm.string,received:t.parsedType}),wm}const t=new Em;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),Sm(r,{code:bm.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("max"===s.kind)e.data.length>s.value&&(r=this._getOrReturnCtx(e,r),Sm(r,{code:bm.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("length"===s.kind){const n=e.data.length>s.value,i=e.data.length<s.value;(n||i)&&(r=this._getOrReturnCtx(e,r),n?Sm(r,{code:bm.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&Sm(r,{code:bm.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)zm.test(e.data)||(r=this._getOrReturnCtx(e,r),Sm(r,{validation:"email",code:bm.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)Hm||(Hm=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Hm.test(e.data)||(r=this._getOrReturnCtx(e,r),Sm(r,{validation:"emoji",code:bm.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)$m.test(e.data)||(r=this._getOrReturnCtx(e,r),Sm(r,{validation:"uuid",code:bm.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)jm.test(e.data)||(r=this._getOrReturnCtx(e,r),Sm(r,{validation:"nanoid",code:bm.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)Bm.test(e.data)||(r=this._getOrReturnCtx(e,r),Sm(r,{validation:"cuid",code:bm.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)Gm.test(e.data)||(r=this._getOrReturnCtx(e,r),Sm(r,{validation:"cuid2",code:bm.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)qm.test(e.data)||(r=this._getOrReturnCtx(e,r),Sm(r,{validation:"ulid",code:bm.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),Sm(r,{validation:"url",code:bm.invalid_string,message:s.message}),t.dirty()}else if("regex"===s.kind){s.regex.lastIndex=0;s.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),Sm(r,{validation:"regex",code:bm.invalid_string,message:s.message}),t.dirty())}else if("trim"===s.kind)e.data=e.data.trim();else if("includes"===s.kind)e.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(e,r),Sm(r,{code:bm.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),t.dirty());else if("toLowerCase"===s.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===s.kind)e.data=e.data.toUpperCase();else if("startsWith"===s.kind)e.data.startsWith(s.value)||(r=this._getOrReturnCtx(e,r),Sm(r,{code:bm.invalid_string,validation:{startsWith:s.value},message:s.message}),t.dirty());else if("endsWith"===s.kind)e.data.endsWith(s.value)||(r=this._getOrReturnCtx(e,r),Sm(r,{code:bm.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty());else if("datetime"===s.kind){ng(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Sm(r,{code:bm.invalid_string,validation:"datetime",message:s.message}),t.dirty())}else if("date"===s.kind){tg.test(e.data)||(r=this._getOrReturnCtx(e,r),Sm(r,{code:bm.invalid_string,validation:"date",message:s.message}),t.dirty())}else if("time"===s.kind){sg(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Sm(r,{code:bm.invalid_string,validation:"time",message:s.message}),t.dirty())}else"duration"===s.kind?Km.test(e.data)||(r=this._getOrReturnCtx(e,r),Sm(r,{validation:"duration",code:bm.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?ig(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Sm(r,{validation:"ip",code:bm.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?og(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),Sm(r,{validation:"jwt",code:bm.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?ag(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Sm(r,{validation:"cidr",code:bm.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?Ym.test(e.data)||(r=this._getOrReturnCtx(e,r),Sm(r,{validation:"base64",code:bm.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?Xm.test(e.data)||(r=this._getOrReturnCtx(e,r),Sm(r,{validation:"base64url",code:bm.invalid_string,message:s.message}),t.dirty()):gm.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:bm.invalid_string,...Lm.errToObj(r)})}_addCheck(e){return new cg({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Lm.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Lm.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Lm.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Lm.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Lm.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Lm.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Lm.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Lm.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Lm.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Lm.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Lm.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Lm.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Lm.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Lm.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...Lm.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Lm.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Lm.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Lm.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Lm.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Lm.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Lm.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Lm.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Lm.errToObj(t)})}nonempty(e){return this.min(1,Lm.errToObj(e))}trim(){return new cg({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new cg({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new cg({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function dg(e,t){const r=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=r>s?r:s;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}cg.create=e=>new cg({checks:[],typeName:Wg.ZodString,coerce:e?.coerce??!1,...xm(e)});class ug extends Fm{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==vm.number){const t=this._getOrReturnCtx(e);return Sm(t,{code:bm.invalid_type,expected:vm.number,received:t.parsedType}),wm}let t;const r=new Em;for(const s of this._def.checks)if("int"===s.kind)gm.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Sm(t,{code:bm.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty());else if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),Sm(t,{code:bm.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),Sm(t,{code:bm.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==dg(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),Sm(t,{code:bm.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Sm(t,{code:bm.not_finite,message:s.message}),r.dirty()):gm.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Lm.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Lm.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Lm.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Lm.toString(t))}setLimit(e,t,r,s){return new ug({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Lm.toString(s)}]})}_addCheck(e){return new ug({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Lm.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Lm.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Lm.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Lm.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Lm.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Lm.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Lm.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Lm.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Lm.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&gm.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ug.create=e=>new ug({checks:[],typeName:Wg.ZodNumber,coerce:e?.coerce||!1,...xm(e)});class lg extends Fm{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==vm.bigint)return this._getInvalidInput(e);let t;const r=new Em;for(const s of this._def.checks)if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),Sm(t,{code:bm.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),Sm(t,{code:bm.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),Sm(t,{code:bm.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):gm.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Sm(t,{code:bm.invalid_type,expected:vm.bigint,received:t.parsedType}),wm}gte(e,t){return this.setLimit("min",e,!0,Lm.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Lm.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Lm.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Lm.toString(t))}setLimit(e,t,r,s){return new lg({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Lm.toString(s)}]})}_addCheck(e){return new lg({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Lm.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Lm.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Lm.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Lm.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Lm.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}lg.create=e=>new lg({checks:[],typeName:Wg.ZodBigInt,coerce:e?.coerce??!1,...xm(e)});class hg extends Fm{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==vm.boolean){const t=this._getOrReturnCtx(e);return Sm(t,{code:bm.invalid_type,expected:vm.boolean,received:t.parsedType}),wm}return Rm(e.data)}}hg.create=e=>new hg({typeName:Wg.ZodBoolean,coerce:e?.coerce||!1,...xm(e)});class pg extends Fm{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==vm.date){const t=this._getOrReturnCtx(e);return Sm(t,{code:bm.invalid_type,expected:vm.date,received:t.parsedType}),wm}if(Number.isNaN(e.data.getTime())){return Sm(this._getOrReturnCtx(e),{code:bm.invalid_date}),wm}const t=new Em;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),Sm(r,{code:bm.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),Sm(r,{code:bm.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):gm.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new pg({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Lm.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Lm.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}pg.create=e=>new pg({checks:[],coerce:e?.coerce||!1,typeName:Wg.ZodDate,...xm(e)});class mg extends Fm{_parse(e){if(this._getType(e)!==vm.symbol){const t=this._getOrReturnCtx(e);return Sm(t,{code:bm.invalid_type,expected:vm.symbol,received:t.parsedType}),wm}return Rm(e.data)}}mg.create=e=>new mg({typeName:Wg.ZodSymbol,...xm(e)});class gg extends Fm{_parse(e){if(this._getType(e)!==vm.undefined){const t=this._getOrReturnCtx(e);return Sm(t,{code:bm.invalid_type,expected:vm.undefined,received:t.parsedType}),wm}return Rm(e.data)}}gg.create=e=>new gg({typeName:Wg.ZodUndefined,...xm(e)});class fg extends Fm{_parse(e){if(this._getType(e)!==vm.null){const t=this._getOrReturnCtx(e);return Sm(t,{code:bm.invalid_type,expected:vm.null,received:t.parsedType}),wm}return Rm(e.data)}}fg.create=e=>new fg({typeName:Wg.ZodNull,...xm(e)});class yg extends Fm{constructor(){super(...arguments),this._any=!0}_parse(e){return Rm(e.data)}}yg.create=e=>new yg({typeName:Wg.ZodAny,...xm(e)});class vg extends Fm{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Rm(e.data)}}vg.create=e=>new vg({typeName:Wg.ZodUnknown,...xm(e)});class Ig extends Fm{_parse(e){const t=this._getOrReturnCtx(e);return Sm(t,{code:bm.invalid_type,expected:vm.never,received:t.parsedType}),wm}}Ig.create=e=>new Ig({typeName:Wg.ZodNever,...xm(e)});class bg extends Fm{_parse(e){if(this._getType(e)!==vm.undefined){const t=this._getOrReturnCtx(e);return Sm(t,{code:bm.invalid_type,expected:vm.void,received:t.parsedType}),wm}return Rm(e.data)}}bg.create=e=>new bg({typeName:Wg.ZodVoid,...xm(e)});class _g extends Fm{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==vm.array)return Sm(t,{code:bm.invalid_type,expected:vm.array,received:t.parsedType}),wm;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(Sm(t,{code:e?bm.too_big:bm.too_small,minimum:n?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(Sm(t,{code:bm.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(Sm(t,{code:bm.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>s.type._parseAsync(new Dm(t,e,t.path,r)))).then(e=>Em.mergeArray(r,e));const n=[...t.data].map((e,r)=>s.type._parseSync(new Dm(t,e,t.path,r)));return Em.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new _g({...this._def,minLength:{value:e,message:Lm.toString(t)}})}max(e,t){return new _g({...this._def,maxLength:{value:e,message:Lm.toString(t)}})}length(e,t){return new _g({...this._def,exactLength:{value:e,message:Lm.toString(t)}})}nonempty(e){return this.min(1,e)}}function Tg(e){if(e instanceof Cg){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=Fg.create(Tg(s))}return new Cg({...e._def,shape:()=>t})}return e instanceof _g?new _g({...e._def,type:Tg(e.element)}):e instanceof Fg?Fg.create(Tg(e.unwrap())):e instanceof Bg?Bg.create(Tg(e.unwrap())):e instanceof Ag?Ag.create(e.items.map(e=>Tg(e))):e}_g.create=(e,t)=>new _g({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Wg.ZodArray,...xm(t)});class Cg extends Fm{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=gm.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==vm.object){const t=this._getOrReturnCtx(e);return Sm(t,{code:bm.invalid_type,expected:vm.object,received:t.parsedType}),wm}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof Ig&&"strip"===this._def.unknownKeys))for(const a in r.data)n.includes(a)||i.push(a);const o=[];for(const a of n){const e=s[a],t=r.data[a];o.push({key:{status:"valid",value:a},value:e._parse(new Dm(r,t,r.path,a)),alwaysSet:a in r.data})}if(this._def.catchall instanceof Ig){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of i)o.push({key:{status:"valid",value:t},value:{status:"valid",value:r.data[t]}});else if("strict"===e)i.length>0&&(Sm(r,{code:bm.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const s=r.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new Dm(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>Em.mergeObjectSync(t,e)):Em.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return Lm.errToObj,new Cg({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const s=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:Lm.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new Cg({...this._def,unknownKeys:"strip"})}passthrough(){return new Cg({...this._def,unknownKeys:"passthrough"})}extend(e){return new Cg({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Cg({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Wg.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Cg({...this._def,catchall:e})}pick(e){const t={};for(const r of gm.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new Cg({...this._def,shape:()=>t})}omit(e){const t={};for(const r of gm.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new Cg({...this._def,shape:()=>t})}deepPartial(){return Tg(this)}partial(e){const t={};for(const r of gm.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new Cg({...this._def,shape:()=>t})}required(e){const t={};for(const r of gm.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Fg;)e=e._def.innerType;t[r]=e}return new Cg({...this._def,shape:()=>t})}keyof(){return Lg(gm.objectKeys(this.shape))}}Cg.create=(e,t)=>new Cg({shape:()=>e,unknownKeys:"strip",catchall:Ig.create(),typeName:Wg.ZodObject,...xm(t)}),Cg.strictCreate=(e,t)=>new Cg({shape:()=>e,unknownKeys:"strict",catchall:Ig.create(),typeName:Wg.ZodObject,...xm(t)}),Cg.lazycreate=(e,t)=>new Cg({shape:e,unknownKeys:"strip",catchall:Ig.create(),typeName:Wg.ZodObject,...xm(t)});class Sg extends Fm{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const s of e)if("dirty"===s.result.status)return t.common.issues.push(...s.ctx.common.issues),s.result;const r=e.map(e=>new _m(e.ctx.common.issues));return Sm(t,{code:bm.invalid_union,unionErrors:r}),wm});{let e;const s=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},n=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map(e=>new _m(e));return Sm(t,{code:bm.invalid_union,unionErrors:n}),wm}}get options(){return this._def.options}}function Eg(e,t){const r=Im(e),s=Im(t);if(e===t)return{valid:!0,data:e};if(r===vm.object&&s===vm.object){const r=gm.objectKeys(t),s=gm.objectKeys(e).filter(e=>-1!==r.indexOf(e)),n={...e,...t};for(const i of s){const r=Eg(e[i],t[i]);if(!r.valid)return{valid:!1};n[i]=r.data}return{valid:!0,data:n}}if(r===vm.array&&s===vm.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const n=Eg(e[s],t[s]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===vm.date&&s===vm.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Sg.create=(e,t)=>new Sg({options:e,typeName:Wg.ZodUnion,...xm(t)});class wg extends Fm{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(Nm(e)||Nm(s))return wm;const n=Eg(e.value,s.value);return n.valid?((Om(e)||Om(s))&&t.dirty(),{status:t.value,value:n.data}):(Sm(r,{code:bm.invalid_intersection_types}),wm)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}wg.create=(e,t,r)=>new wg({left:e,right:t,typeName:Wg.ZodIntersection,...xm(r)});class Ag extends Fm{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==vm.array)return Sm(r,{code:bm.invalid_type,expected:vm.array,received:r.parsedType}),wm;if(r.data.length<this._def.items.length)return Sm(r,{code:bm.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),wm;!this._def.rest&&r.data.length>this._def.items.length&&(Sm(r,{code:bm.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new Dm(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>Em.mergeArray(t,e)):Em.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new Ag({...this._def,rest:e})}}Ag.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ag({items:e,typeName:Wg.ZodTuple,rest:null,...xm(t)})};class Rg extends Fm{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==vm.object)return Sm(r,{code:bm.invalid_type,expected:vm.object,received:r.parsedType}),wm;const s=[],n=this._def.keyType,i=this._def.valueType;for(const o in r.data)s.push({key:n._parse(new Dm(r,o,r.path,o)),value:i._parse(new Dm(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?Em.mergeObjectAsync(t,s):Em.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new Rg(t instanceof Fm?{keyType:e,valueType:t,typeName:Wg.ZodRecord,...xm(r)}:{keyType:cg.create(),valueType:e,typeName:Wg.ZodRecord,...xm(t)})}}class Ng extends Fm{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==vm.map)return Sm(r,{code:bm.invalid_type,expected:vm.map,received:r.parsedType}),wm;const s=this._def.keyType,n=this._def.valueType,i=[...r.data.entries()].map(([e,t],i)=>({key:s._parse(new Dm(r,e,r.path,[i,"key"])),value:n._parse(new Dm(r,t,r.path,[i,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of i){const s=await r.key,n=await r.value;if("aborted"===s.status||"aborted"===n.status)return wm;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of i){const s=r.key,n=r.value;if("aborted"===s.status||"aborted"===n.status)return wm;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}Ng.create=(e,t,r)=>new Ng({valueType:t,keyType:e,typeName:Wg.ZodMap,...xm(r)});class Og extends Fm{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==vm.set)return Sm(r,{code:bm.invalid_type,expected:vm.set,received:r.parsedType}),wm;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(Sm(r,{code:bm.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&(Sm(r,{code:bm.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const r=new Set;for(const s of e){if("aborted"===s.status)return wm;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}const o=[...r.data.values()].map((e,t)=>n._parse(new Dm(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>i(e)):i(o)}min(e,t){return new Og({...this._def,minSize:{value:e,message:Lm.toString(t)}})}max(e,t){return new Og({...this._def,maxSize:{value:e,message:Lm.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Og.create=(e,t)=>new Og({valueType:e,minSize:null,maxSize:null,typeName:Wg.ZodSet,...xm(t)});class Mg extends Fm{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Mg.create=(e,t)=>new Mg({getter:e,typeName:Wg.ZodLazy,...xm(t)});class Ug extends Fm{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Sm(t,{received:t.data,code:bm.invalid_literal,expected:this._def.value}),wm}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Lg(e,t){return new kg({values:e,typeName:Wg.ZodEnum,...xm(t)})}Ug.create=(e,t)=>new Ug({value:e,typeName:Wg.ZodLiteral,...xm(t)});class kg extends Fm{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return Sm(t,{expected:gm.joinValues(r),received:t.parsedType,code:bm.invalid_type}),wm}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return Sm(t,{received:t.data,code:bm.invalid_enum_value,options:r}),wm}return Rm(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return kg.create(e,{...this._def,...t})}exclude(e,t=this._def){return kg.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}kg.create=Lg;class Dg extends Fm{_parse(e){const t=gm.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==vm.string&&r.parsedType!==vm.number){const e=gm.objectValues(t);return Sm(r,{expected:gm.joinValues(e),received:r.parsedType,code:bm.invalid_type}),wm}if(this._cache||(this._cache=new Set(gm.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=gm.objectValues(t);return Sm(r,{received:r.data,code:bm.invalid_enum_value,options:e}),wm}return Rm(e.data)}get enum(){return this._def.values}}Dg.create=(e,t)=>new Dg({values:e,typeName:Wg.ZodNativeEnum,...xm(t)});class Pg extends Fm{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==vm.promise&&!1===t.common.async)return Sm(t,{code:bm.invalid_type,expected:vm.promise,received:t.parsedType}),wm;const r=t.parsedType===vm.promise?t.data:Promise.resolve(t.data);return Rm(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Pg.create=(e,t)=>new Pg({type:e,typeName:Wg.ZodPromise,...xm(t)});class xg extends Fm{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Wg.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,n={addIssue:e=>{Sm(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===s.type){const e=s.transform(r.data,n);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return wm;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?wm:"dirty"===s.status||"dirty"===t.value?Am(s.value):s});{if("aborted"===t.value)return wm;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?wm:"dirty"===s.status||"dirty"===t.value?Am(s.value):s}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,n);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===s.status?wm:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?wm:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===s.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Mm(e))return wm;const i=s.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>Mm(e)?Promise.resolve(s.transform(e.value,n)).then(e=>({status:t.value,value:e})):wm)}gm.assertNever(s)}}xg.create=(e,t,r)=>new xg({schema:e,typeName:Wg.ZodEffects,effect:t,...xm(r)}),xg.createWithPreprocess=(e,t,r)=>new xg({schema:t,effect:{type:"preprocess",transform:e},typeName:Wg.ZodEffects,...xm(r)});class Fg extends Fm{_parse(e){return this._getType(e)===vm.undefined?Rm(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Fg.create=(e,t)=>new Fg({innerType:e,typeName:Wg.ZodOptional,...xm(t)});class Bg extends Fm{_parse(e){return this._getType(e)===vm.null?Rm(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Bg.create=(e,t)=>new Bg({innerType:e,typeName:Wg.ZodNullable,...xm(t)});class Gg extends Fm{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===vm.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Gg.create=(e,t)=>new Gg({innerType:e,typeName:Wg.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...xm(t)});class qg extends Fm{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Um(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new _m(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new _m(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}qg.create=(e,t)=>new qg({innerType:e,typeName:Wg.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...xm(t)});class $g extends Fm{_parse(e){if(this._getType(e)!==vm.nan){const t=this._getOrReturnCtx(e);return Sm(t,{code:bm.invalid_type,expected:vm.nan,received:t.parsedType}),wm}return{status:"valid",value:e.data}}}$g.create=e=>new $g({typeName:Wg.ZodNaN,...xm(e)});class jg extends Fm{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Vg extends Fm{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?wm:"dirty"===e.status?(t.dirty(),Am(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?wm:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Vg({in:e,out:t,typeName:Wg.ZodPipeline})}}class Kg extends Fm{_parse(e){const t=this._def.innerType._parse(e),r=e=>(Mm(e)&&(e.value=Object.freeze(e.value)),e);return Um(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function zg(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Hg(e,t={},r){return e?yg.create().superRefine((s,n)=>{const i=e(s);if(i instanceof Promise)return i.then(e=>{if(!e){const e=zg(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=zg(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}}):yg.create()}var Wg,Jg;Kg.create=(e,t)=>new Kg({innerType:e,typeName:Wg.ZodReadonly,...xm(t)}),(Jg=Wg||(Wg={})).ZodString="ZodString",Jg.ZodNumber="ZodNumber",Jg.ZodNaN="ZodNaN",Jg.ZodBigInt="ZodBigInt",Jg.ZodBoolean="ZodBoolean",Jg.ZodDate="ZodDate",Jg.ZodSymbol="ZodSymbol",Jg.ZodUndefined="ZodUndefined",Jg.ZodNull="ZodNull",Jg.ZodAny="ZodAny",Jg.ZodUnknown="ZodUnknown",Jg.ZodNever="ZodNever",Jg.ZodVoid="ZodVoid",Jg.ZodArray="ZodArray",Jg.ZodObject="ZodObject",Jg.ZodUnion="ZodUnion",Jg.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Jg.ZodIntersection="ZodIntersection",Jg.ZodTuple="ZodTuple",Jg.ZodRecord="ZodRecord",Jg.ZodMap="ZodMap",Jg.ZodSet="ZodSet",Jg.ZodFunction="ZodFunction",Jg.ZodLazy="ZodLazy",Jg.ZodLiteral="ZodLiteral",Jg.ZodEnum="ZodEnum",Jg.ZodEffects="ZodEffects",Jg.ZodNativeEnum="ZodNativeEnum",Jg.ZodOptional="ZodOptional",Jg.ZodNullable="ZodNullable",Jg.ZodDefault="ZodDefault",Jg.ZodCatch="ZodCatch",Jg.ZodPromise="ZodPromise",Jg.ZodBranded="ZodBranded",Jg.ZodPipeline="ZodPipeline",Jg.ZodReadonly="ZodReadonly";const Qg=cg.create,Zg=ug.create,Yg=hg.create;yg.create;const Xg=vg.create,ef=Ig.create,tf=_g.create,rf=Cg.create,sf=Sg.create;wg.create,Ag.create;const nf=Rg.create,of=kg.create;Pg.create,Fg.create,Bg.create;const af=nf(Xg()),cf={text:rf({content:Qg()}),image:rf({isGif:Yg(),isOriginalImage:Yg()}),video:rf({duration:Zg()}),voice:rf({duration:Zg()}),file:af,location:rf({latitude:Zg(),longitude:Zg()}),cmd:rf({action:Qg()}),custom:rf({event:Qg()}),combine:rf({title:Qg(),summary:Qg(),filename:Qg(),filetype:Qg(),combineLevel:Zg()}),multi_body:tf(rf({type:Qg()}).passthrough()).min(2)},df=rf({msgServerId:Qg(),msgLocalId:Qg(),from:Qg(),to:Qg(),sender:rf({userId:Qg(),nickname:Qg().optional(),avatarUrl:Qg().optional()}),conversationId:Qg(),conversationType:of(["singleChat","groupChat","chatRoom"]),type:of(["text","image","video","voice","file","location","cmd","custom","combine","multi_body"]),sendStatus:of(["sending","sent","failed"]),timestamp:Zg(),ext:af,body:sf([af,tf(rf({type:Qg()}).passthrough()).min(2)])});const uf=Yg().optional().catch(void 0),lf=Zg().finite().optional().catch(void 0),hf=Qg().optional().catch(void 0),pf=rf({msgLocalId:hf,sendStatus:of(["sending","sent","failed"]).optional().catch(void 0),direct:of(["SEND","RECEIVE"]).optional().catch(void 0),isOnline:uf,receiverList:tf(Qg()).optional().catch(void 0),deliverOnlineOnly:uf,webhookEnv:hf,priority:of(["high","normal","low"]).optional().catch(void 0),isBroadcast:uf,isContentReplaced:uf,combineLevel:lf,modifiedInfo:rf({operatorId:Qg(),operationCount:Zg().finite(),operationTime:Zg().finite()}).optional().catch(void 0),reactions:tf(rf({reaction:Qg(),count:Zg(),userList:tf(Qg()),isAddedBySelf:Yg().optional(),op:tf(rf({operator:Qg(),reactionType:of(["create","delete"])})).optional()})).optional().catch(void 0),groupReadCount:Zg().int().nonnegative().optional().catch(void 0),isPeerRead:uf,needReadReceipt:uf,isChatThread:uf,chatThread:rf({messageId:Qg(),parentId:Qg(),chatThreadName:Qg().optional()}).optional().catch(void 0),chatThreadOverview:rf({chatThreadId:Qg(),parentId:Qg(),name:Qg().optional(),lastMessage:Hg(e=>{const t=df.safeParse(e);return!!t.success&&("multi_body"===t.data.type?cf.multi_body.safeParse(t.data.body).success:cf[t.data.type].safeParse(t.data.body).success)}).transform(function(e){return{...df.parse(e),body:e.body,...mf(e)}}).nullable().optional().catch(null),createdAt:Zg().optional(),updatedAt:Zg().optional(),messageCount:Zg().optional()}).optional().catch(void 0),stream:rf({customType:Qg().optional(),seq:Zg(),status:of(["STREAM_START","STREAM_START_COMPLETED","STREAM_IN_PROGRESS","STREAM_COMPLETED","STREAM_FULL","STREAM_ERROR"]),errorType:Zg(),finishReason:Zg().optional(),deltaText:Qg(),fullText:Qg()}).optional().catch(void 0),userInfoUpdateTime:lf,namecardUpdateTime:lf}),mf=e=>{const t=pf.safeParse(e);if(!t.success)return{};for(const[r,s]of Object.entries(t.data))void 0===s&&Reflect.deleteProperty(t.data,r);return t.data},gf=e=>JSON.stringify(e,(e,t)=>t&&"object"==typeof t&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).filter(([,e])=>void 0!==e).sort(([e],[t])=>e.localeCompare(t))):t),ff=e=>e.map(e=>{const t={...e};return"string"==typeof t.localUrl&&t.localUrl.startsWith("blob:")&&(t.localUrl=""),delete t.data,t}),yf=e=>{if(Array.isArray(e))return ff(e);const t={...e};return delete t.type,delete t.messageList,t},vf=e=>{if("singleChat"!==e.conversationType)return e.conversationId;const t=e.to||("SEND"===e.direct?e.conversationId:"RECEIVE"===e.direct?e.currentUserId:e.from?e.from===e.currentUserId?e.conversationId:e.currentUserId:""),r=t.indexOf("/");return r<0?t:t.slice(0,r)},If=e=>{if(e.length>=1048576){const t=[],r=32768;for(let s=0;s<e.length;s+=r)t.push(String.fromCharCode(...e.subarray(s,s+r)));return btoa(t.join(""))}let t="";for(let r=0;r<e.length;r+=1){const s=e[r];void 0!==s&&(t+=String.fromCharCode(s))}return btoa(t)},bf=e=>{const t=new Uint8Array(fa.util.base64.length(e));return fa.util.base64.decode(e,t,0),t};class _f{getCrypto(){return fn().crypto}constructor(e,t){if(this.enabled=(()=>{const e=fn();if([e.wx,e.qq,e.tt,e.swan,e.my,e.dd,e.jd,e.ks,e.uni].some(e=>void 0!==e))return!1;const t=Mn(e);if("web"!==t.framework&&"worker"!==t.framework&&t.platform!==Qs.ELECTRON_RENDERER)return!1;const r=e.crypto;return void 0!==r&&void 0!==r.subtle&&"function"==typeof r.getRandomValues&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder})(),this.enabled){const r=`${e}:${t}`;this.keyPromise=this.deriveKey(r)}else this.keyPromise=null}isEnabled(){return this.enabled}async encrypt(e){if(!this.enabled||!this.keyPromise)return e;const t=await this.keyPromise,r=new TextEncoder,s=this.getCrypto().getRandomValues(new Uint8Array(12)),n=r.encode(e),i=await this.getCrypto().subtle.encrypt({name:"AES-GCM",iv:s},t,n),o={__enc:!0,v:1,alg:"AES-GCM",kdf:"SHA-256",iv:If(s),ct:If(new Uint8Array(i))};return JSON.stringify(o)}async decrypt(e){if(!this.enabled||!this.keyPromise)return e;let t;try{t=JSON.parse(e)}catch{return e}if(!(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return!0===t.__enc&&1===t.v&&"AES-GCM"===t.alg&&"SHA-256"===t.kdf&&"string"==typeof t.iv&&"string"==typeof t.ct})(t))return e;try{const e=await this.keyPromise,r=bf(t.iv),s=bf(t.ct),n=await this.getCrypto().subtle.decrypt({name:"AES-GCM",iv:r},e,s);return(new TextDecoder).decode(n)}catch{return null}}async deriveKey(e){const t=(new TextEncoder).encode(e),r=this.getCrypto(),s=await r.subtle.digest("SHA-256",t);return r.subtle.importKey("raw",s,{name:"AES-GCM"},!1,["encrypt","decrypt"])}}const Tf="conversationMap",Cf="userInfoMap",Sf="groupNamecardMap",Ef="contactRelationMap",wf="contactVersion",Af="contactMeta",Rf="sessionListMap",Nf="sessionListCheckpoint",Of="joinedGroupPreview",Mf="metadata",Uf=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class Lf{constructor(e,t,r){this.store=e,this.key=t,this.schemaVersion=r}async load(){const e={schemaVersion:this.schemaVersion,lastFlush:0},t=await this.store.readAsync(this.key,e);return t.schemaVersion!==this.schemaVersion?e:t}async save(e){await this.store.writeAsync(this.key,e)}async touchLastFlush(){const e={schemaVersion:this.schemaVersion,lastFlush:Date.now()};return await this.save(e),e}}const kf=()=>{const e="undefined"!=typeof window?window.localStorage:void 0;if(e&&"function"==typeof e.getItem)return e;const t=fn().localStorage;return t&&"function"==typeof t.getItem?t:null};class Df{constructor(e,t){this.storage=t??Df.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!Df.checkAvailable())return null;const e=kf();return e?{getItem:t=>Promise.resolve(e.getItem(t)),setItem:(t,r)=>(e.setItem(t,r),Promise.resolve()),removeItem:t=>(e.removeItem(t),Promise.resolve())}:null}static checkAvailable(){const e=kf();if(!e)return!1;try{const t="__im_sdk_cache_test__";return e.setItem(t,"1"),e.removeItem(t),!0}catch{return!1}}async readAsync(e,t){if(!this.storage)return t;try{const r=await this.storage.getItem(e);if(!r)return t;let s=r;if(this.cryptoAdapter&&this.cryptoAdapter.isEnabled()){const e=await this.cryptoAdapter.decrypt(r);if(null===e)return t;s=e}return Lu(s,t)}catch(r){return Ks("CacheStore read failed",r),t}}async writeAsync(e,t){await this.writeInternal(e,t,!1)}async writeStrictAsync(e,t){await this.writeInternal(e,t,!0)}async writeInternal(e,t,r){if(!this.storage)return;const s=(e=>{try{return JSON.stringify(e)}catch{return null}})(t);if(null!==s)try{const t=this.cryptoAdapter&&this.cryptoAdapter.isEnabled()?await this.cryptoAdapter.encrypt(s):s;await this.storage.setItem(e,t)}catch(n){if(Hc(n))throw n;if(r)throw n;Ks("CacheStore write failed",n)}else if(r)throw new TypeError("CacheStore value cannot be serialized")}async remove(e){if(this.storage)try{await this.storage.removeItem(e)}catch(t){Ks("CacheStore remove failed",t)}}}const Pf={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},xf={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class Ff{constructor(){this.items=new Map,this.versionState=Pf,this.meta=xf}load(e,t,r){this.items.clear();for(const s of e){const e=this.normalizeRecord(s);e&&this.items.set(e.userId,e)}this.versionState=this.normalizeVersionState(t),this.meta=this.normalizeMeta(r)}getAll(){return Array.from(this.items.values()).sort((e,t)=>e.addTs!==t.addTs?e.addTs-t.addTs:e.userId.localeCompare(t.userId))}getVersionState(){return this.versionState}getMeta(){return this.meta}getUserIds(){return Array.from(this.items.keys())}replaceAll(e){this.items.clear(),this.upsert(e)}upsert(e){for(const t of e){const e=this.normalizeRecord(t);e&&this.items.set(e.userId,e)}}addByNotice(e,t){const r=e.trim();return!!r&&(!this.items.has(r)&&(this.items.set(r,{userId:r,remark:"",sign:"",addTs:t,updatedAt:t,metadataUpdatedAt:t}),!0))}remove(e){return this.items.delete(e)}updateRemark(e,t,r){const s=this.items.get(e);return!(!s||s.remark===t)&&(this.items.set(e,{...s,remark:t,updatedAt:r}),!0)}setVersionState(e){this.versionState=this.normalizeVersionState(e)}updateVersionFromNotice(e,t){const r=e.trim();return!!r&&((this.versionState.version!==r||"roster_notice"!==this.versionState.lastVersionSource)&&(this.versionState={version:r,lastVersionCheckAt:t,lastVersionSource:"roster_notice"},!0))}setMeta(e){this.meta=this.normalizeMeta(e)}updateMeta(e){this.meta={cacheIntegrity:e.cacheIntegrity,reason:"complete"===e.cacheIntegrity?void 0:e.reason,lastSyncTs:e.lastSyncTs??this.meta.lastSyncTs,lastSuccessfulVersion:e.lastSuccessfulVersion??this.meta.lastSuccessfulVersion,lastSyncMode:e.lastSyncMode??this.meta.lastSyncMode}}computeIntegrity(e){if(0===this.items.size&&!this.meta.lastSuccessfulVersion)return{...this.meta,cacheIntegrity:"incomplete",reason:"first_sync_pending"};const t=new Set(e.map(e=>e.userId));return this.getUserIds().some(e=>!t.has(e))?{...this.meta,cacheIntegrity:"incomplete",reason:"user_info_missing"}:{...this.meta,cacheIntegrity:"complete",reason:void 0}}buildSnapshot(e,t){const r=new Map(e.map(e=>[e.userId,e])),s=this.getAll().map(e=>{const t=r.get(e.userId);return{userId:e.userId,userInfo:{userId:e.userId,nickname:t?.nickname,avatarUrl:t?.avatarUrl,sign:t?.sign??e.sign,ext:t?.ext},remark:e.remark,addTs:e.addTs}}),n="complete"===this.computeIntegrity(e).cacheIntegrity;return{items:s,source:t,version:this.versionState.version||this.meta.lastSuccessfulVersion,complete:n}}normalizeRecord(e){if(!Uu(e))return null;const t="string"==typeof e.userId?e.userId:"";return t?{userId:t,remark:"string"==typeof e.remark?e.remark:"",sign:"string"==typeof e.sign?e.sign:"",addTs:"number"==typeof e.addTs?e.addTs:0,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:0,metadataUpdatedAt:"number"==typeof e.metadataUpdatedAt?e.metadataUpdatedAt:0}:null}normalizeVersionState(e){return Uu(e)?{version:"string"==typeof e.version?e.version:"",lastVersionCheckAt:"number"==typeof e.lastVersionCheckAt?e.lastVersionCheckAt:0,lastVersionSource:"metadata"===e.lastVersionSource||"sync_page"===e.lastVersionSource||"roster_notice"===e.lastVersionSource?e.lastVersionSource:"metadata"}:Pf}normalizeMeta(e){return Uu(e)?{cacheIntegrity:"complete"===e.cacheIntegrity?"complete":"incomplete",reason:"quota_exceeded"===e.reason||"user_info_missing"===e.reason||"corrupted"===e.reason||"manual_reset"===e.reason||"first_sync_pending"===e.reason?e.reason:void 0,lastSyncTs:"number"==typeof e.lastSyncTs?e.lastSyncTs:0,lastSuccessfulVersion:"string"==typeof e.lastSuccessfulVersion?e.lastSuccessfulVersion:"",lastSyncMode:"full"===e.lastSyncMode||"incremental"===e.lastSyncMode||"skipped"===e.lastSyncMode?e.lastSyncMode:"skipped"}:xf}}const Bf=(e,t,r)=>{if(t<=0)return{kept:e,removed:[]};const s=[],n=[];for(const i of e)r-i.lastUpdate>t?n.push(i):s.push(i);return{kept:s,removed:n}},Gf=(e,t)=>{if(t<=0||0===e.length)return{kept:e,removed:[]};const r=[...e].sort((e,t)=>e.lastAccess-t.lastAccess).slice(0,t),s=new Set(r);return{kept:e.filter(e=>!s.has(e)),removed:r}},qf=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r};class $f{constructor(){this.items=[]}load(e,t){const r=[];for(const s of e){const e=this.normalizeItem(s,t);e&&r.push(e)}this.items=r}getAll(){return this.items}setAll(e){this.items=[...e]}updateLastAccess(e,t){if(0===e.length)return!1;let r=!1;for(const s of e){const e=this.findIndex(s.conversationId,s.type);if(e<0)continue;const n=this.items[e];n&&(n.lastAccess!==t&&(this.items[e]={...n,lastAccess:t},r=!0))}return r}removeExpired(e,t){const r=Bf(this.items,e,t);return this.items=[...r.kept],r.removed.length>0}evictByLru(e){const t=Gf(this.items,e);return this.items=[...t.kept],t.removed.length>0}trimMax(e){if(!e||this.items.length<=e)return!1;const t=[...this.items].sort((e,t)=>e.lastAccess-t.lastAccess),r=Math.max(this.items.length-e,0),s=t.slice(0,r),n=new Set(s);return this.items=this.items.filter(e=>!n.has(e)),s.length>0}findIndex(e,t){return this.items.findIndex(r=>r.conversationId===e&&r.type===t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;const r=e;if("string"!=typeof r.conversationId||0===r.conversationId.length)return null;const s="single"===(n=r.type)||"chat"===n||"singleChat"===n?"singleChat":"group"===n||"groupchat"===n||"groupChat"===n?"groupChat":"room"===n||"chatroom"===n||"chatRoom"===n?"chatRoom":null;var n;if(!s)return null;const i=this.normalizeMessage(r.lastMessage);return{conversationId:r.conversationId,type:s,lastMessage:i,unreadCount:"number"==typeof r.unreadCount?r.unreadCount:0,isPinned:"boolean"==typeof r.isPinned?r.isPinned:void 0,pinnedTime:"number"==typeof r.pinnedTime?r.pinnedTime:void 0,marks:qf(r.marks),lastAccess:"number"==typeof r.lastAccess?r.lastAccess:0,lastUpdate:"number"==typeof r.lastUpdate?r.lastUpdate:t}}normalizeMessage(e){if(!e||"object"!=typeof e)return null;if(!Uu(e))return null;const t="string"==typeof e.msgId?e.msgId:"",r="string"==typeof e.type?e.type:"",s="number"==typeof e.timestamp?e.timestamp:0,n=Array.isArray(e.body)||Uu(e.body)?e.body:{};return t?{...mf(e),msgId:t,from:"string"==typeof e.from?e.from:void 0,to:"string"==typeof e.to?e.to:void 0,sender:Uu(e.sender)&&"string"==typeof e.sender.userId?{userId:e.sender.userId,nickname:"string"==typeof e.sender.nickname?e.sender.nickname:void 0,avatarUrl:"string"==typeof e.sender.avatarUrl?e.sender.avatarUrl:void 0}:void 0,type:r,body:yf(n),ext:Uu(e.ext)?e.ext:void 0,timestamp:s}:null}}const jf=(e,t)=>`${e}:${t}`;class Vf{constructor(){this.items=new Map}load(e,t){this.items.clear();for(const r of e){const e=this.normalizeItem(r,t);e&&this.items.set(jf(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,r,s){const n=jf(e,t),i=this.items.get(n);return i?(s&&this.items.set(n,{...i,lastAccess:r}),i):null}getByGroupId(e,t,r){const s=[];for(const n of this.items.values())n.groupId===e&&(s.push(n),r&&this.items.set(jf(n.groupId,n.userId),{...n,lastAccess:t}));return s}setAll(e,t){for(const r of e){const e=this.normalizeItem(r,t);if(!e)continue;const s=jf(e.groupId,e.userId),n=this.items.get(s);this.items.set(s,{...e,lastAccess:n?.lastAccess??e.lastAccess,lastUpdate:t})}}remove(e){for(const t of e)this.items.delete(jf(t.groupId,t.userId))}removeExpired(e,t,r=new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!r.has(e.userId)),i=Bf(n,e,t),o=new Set(i.removed.map(e=>jf(e.groupId,e.userId)));this.items.clear();for(const a of s)o.has(jf(a.groupId,a.userId))||this.items.set(jf(a.groupId,a.userId),a);return i.removed.length>0}evictByLru(e,t=new Set){const r=Array.from(this.items.values()),s=r.filter(e=>!t.has(e.userId)),n=Gf(s,Math.min(e,s.length)),i=new Set(n.removed.map(e=>jf(e.groupId,e.userId)));this.items.clear();for(const o of r)i.has(jf(o.groupId,o.userId))||this.items.set(jf(o.groupId,o.userId),o);return n.removed.length>0}trimMax(e,t=new Set){return!(e<=0||this.items.size<=e)&&this.evictByLru(Math.max(this.items.size-e,0),t)}normalizeItem(e,t){if(!e||!Uu(e))return null;const r="string"==typeof e.groupId?e.groupId:"",s="string"==typeof e.userId?e.userId:"";if(!r||!s)return null;return{groupId:r,userId:s,namecard:"string"==typeof e.namecard?e.namecard:"",namecardUpdateTime:"number"==typeof e.namecardUpdateTime?e.namecardUpdateTime:void 0,lastSyncAt:"number"==typeof e.lastSyncAt?e.lastSyncAt:void 0,lastAccess:"number"==typeof e.lastAccess?e.lastAccess:0,lastUpdate:"number"==typeof e.lastUpdate?e.lastUpdate:t}}}const Kf=100,zf=3e3,Hf=e=>({...e}),Wf=e=>"object"==typeof e&&null!==e,Jf=e=>"DEFAULT"===e||"ALL"===e||"AT"===e||"NONE"===e?e:"mentionOnly"===e?"AT":"mute"===e?"NONE":"default"===e?"DEFAULT":2===e?"AT":3===e?"NONE":0===e?"DEFAULT":1===e?"ALL":void 0;class Qf{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:Kf,serverLimit:zf,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:Kf,serverLimit:zf,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return Wf(t=e)&&"string"==typeof t.groupId&&0!==t.groupId.length?{groupId:t.groupId,name:"string"==typeof t.name?t.name:"",description:"string"==typeof t.description?t.description:void 0,memberCount:"number"==typeof t.memberCount?t.memberCount:void 0,role:"owner"===t.role||"admin"===t.role||"member"===t.role?t.role:void 0,disabled:"boolean"==typeof t.disabled?t.disabled:void 0,ownerId:"string"==typeof t.ownerId?t.ownerId:void 0,avatarUrl:"string"==typeof t.avatarUrl?t.avatarUrl:void 0,muteAllMembers:"boolean"==typeof t.muteAllMembers?t.muteAllMembers:void 0,muteExpiration:"number"==typeof t.muteExpiration?t.muteExpiration:void 0,remindType:Jf(t.remindType),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,updatedAt:"number"==typeof t.updatedAt?t.updatedAt:void 0,joinedAt:"number"==typeof t.joinedAt?t.joinedAt:void 0}:null;var t}).filter(e=>null!==e):[];this.items=t.slice(0,Kf),this.meta=(e=>{const t=Wf(e)?e:{};return{integrity:"synced"===t.integrity||"limited"===t.integrity||"incomplete"===t.integrity||"unknown"===t.integrity?t.integrity:"preview",limited:!0===t.limited,storageLimit:"number"==typeof t.storageLimit?t.storageLimit:Kf,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:zf,source:"localPreview",lastSyncFinishedTs:"number"==typeof t.lastSyncFinishedTs?t.lastSyncFinishedTs:void 0,lastSuccessfulAt:"number"==typeof t.lastSuccessfulAt?t.lastSuccessfulAt:void 0,reason:"string"==typeof t.reason?t.reason:void 0}})(e.meta)}setSnapshot(e){this.items=e.items.map(e=>Hf(e)).slice(0,Kf),this.meta={...e.meta,source:"localPreview",storageLimit:Kf,serverLimit:zf,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>Hf(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>Hf(e)),meta:{...this.meta,source:"localPreview"}}}}const Zf=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,Yf=e=>{if(!Uu(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!Array.isArray(e.body)&&!Uu(e.body))return null;const r=((e,t)=>{if(Uu(e)&&"string"==typeof e.userId){const t={userId:e.userId};return"string"==typeof e.nickname&&(t.nickname=e.nickname),"string"==typeof e.avatarUrl&&(t.avatarUrl=e.avatarUrl),t}return t?{userId:t}:null})(e.sender,e.from);if(!r)return null;const s=Zf(e.conversationType);return{...mf({...e,sendStatus:e.sendStatus??e.status}),msgServerId:t,from:e.from,to:"string"==typeof e.to?e.to:"",sender:r,body:yf(e.body),ext:Uu(e.ext)?e.ext:{},timestamp:e.timestamp,..."string"==typeof e.conversationId?{conversationId:e.conversationId}:{},...s?{conversationType:s}:{},..."string"==typeof e.type&&e.type.length>0?{type:e.type}:{}}},Xf=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r},ey=(e,t)=>{const r="number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,s="number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:0;if(r!==s)return s-r;const n=e.lastMessageAt??e.updatedAt,i=t.lastMessageAt??t.updatedAt;return n!==i?i-n:e.conversationId.localeCompare(t.conversationId)};class ty{constructor(){this.items=[]}load(e,t){const r=[];for(const s of e){const e=this.normalizeItem(s,t);e&&r.push(e)}this.items=r.sort(ey)}getAll(){return this.items}setAll(e){const t=Date.now(),r=[];for(const s of e){const e=this.normalizeItem(s,t);e&&r.push(e)}this.items=r.sort(ey)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!Uu(e))return null;const r=e,s="string"==typeof r.conversationId?r.conversationId:"";if(!s)return null;const n=Zf(r.conversationType);if(!n)return null;const i="string"==typeof r.conversationName&&r.conversationName.length>0?r.conversationName:s,o="string"==typeof r.conversationAvatar?r.conversationAvatar:void 0;return{conversationId:s,conversationType:n,unreadCount:"number"==typeof e.unreadCount&&e.unreadCount>=0?Math.floor(e.unreadCount):0,lastMessage:Yf(e.lastMessage),lastMessageAt:"number"==typeof e.lastMessageAt?e.lastMessageAt:void 0,isPinned:"boolean"==typeof e.isPinned?e.isPinned:void 0,pinnedTimestamp:"number"==typeof r.pinnedTimestamp?r.pinnedTimestamp:void 0,marks:Xf(e.marks),readAt:"number"==typeof r.readAt?r.readAt:void 0,remindType:(a=e.remindType,"DEFAULT"===a||"ALL"===a||"AT"===a||"NONE"===a?a:"mentionOnly"===a?"AT":"mute"===a?"NONE":"DEFAULT"),conversationName:i,conversationAvatar:o,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:t};var a}}class ry{constructor(){this.items=new Map}load(e,t){this.items.clear();for(const r of e){const e=this.normalizeItem(r,t);e&&this.items.set(e.userId,e)}}getAll(){return Array.from(this.items.values())}getByIds(e,t,r){const s=[];for(const n of e){const e=this.items.get(n);e&&(s.push(e),r&&this.items.set(n,{...e,lastAccess:t}))}return s}setAll(e,t){for(const r of e){const e=this.normalizeItem(r,t);if(!e)continue;const s=this.items.get(e.userId),n=s?.lastAccess??e.lastAccess;this.items.set(e.userId,{...e,lastAccess:n,lastUpdate:e.lastUpdate})}}remove(e){for(const t of e)this.items.delete(t)}removeExpired(e,t,r=new Set){const s=Array.from(this.items.values()),n=s.filter(e=>!r.has(e.userId)),i=Bf(n,e,t),o=new Set(i.removed.map(e=>e.userId));this.items.clear();for(const a of s)o.has(a.userId)||this.items.set(a.userId,a);return i.removed.length>0}evictByLru(e,t=new Set){const r=Array.from(this.items.values()),s=r.filter(e=>!t.has(e.userId)),n=Gf(s,Math.min(e,s.length)),i=new Set(n.removed.map(e=>e.userId));this.items.clear();for(const o of r)i.has(o.userId)||this.items.set(o.userId,o);return n.removed.length>0}trimMax(e,t=new Set){if(e<=0||this.items.size<=e)return!1;const r=Array.from(this.items.values()),s=Math.max(r.length-e,0);return this.evictByLru(s,t)}normalizeItem(e,t){if(!e||"object"!=typeof e)return null;if(!Uu(e))return null;const r="string"==typeof e.userId?e.userId:"";if(!r)return null;return{userId:r,nickname:"string"==typeof e.nickname?e.nickname:void 0,avatarUrl:"string"==typeof e.avatarUrl?e.avatarUrl:void 0,sign:"string"==typeof e.sign?e.sign:void 0,ext:"string"==typeof e.ext?e.ext:void 0,userInfoUpdateTime:"number"==typeof e.userInfoUpdateTime?e.userInfoUpdateTime:void 0,lastSyncAt:"number"==typeof e.lastSyncAt?e.lastSyncAt:void 0,lastAccess:"number"==typeof e.lastAccess?e.lastAccess:0,lastUpdate:"number"==typeof e.lastUpdate?e.lastUpdate:t}}}const sy=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,ny=e=>e.lastMessageAt??e.updatedAt,iy=e=>[...e].sort((e,t)=>{const r=sy(t)-sy(e);if(0!==r)return r;const s=ny(t)-ny(e);return 0!==s?s:e.conversationId.localeCompare(t.conversationId)}),oy=e=>`${e.conversationType}:${e.conversationId}`,ay=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,cy=(e,t)=>((e,t)=>ny(t)>ny(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:ay(e,t),lastMessageAt:Math.max(e.lastMessageAt??0,t.lastMessageAt??0),isPinned:t.isPinned??e.isPinned,pinnedTimestamp:"number"==typeof t.pinnedTimestamp?t.pinnedTimestamp:e.pinnedTimestamp,marks:t.marks.length>0?t.marks:e.marks,readAt:t.readAt??e.readAt,remindType:t.remindType??e.remindType,conversationName:t.conversationName===t.conversationId?e.conversationName:t.conversationName,conversationAvatar:t.conversationAvatar??e.conversationAvatar,updatedAt:Math.max(e.updatedAt,t.updatedAt)}:e,dy=e=>{const t=new Map,r=new Set;for(const i of e.snapshot)r.add(oy(i));for(const i of e.existing)t.set(oy(i),i);const s=e.snapshot.map(e=>{const r=t.get(oy(e));return r?cy(e,r):e}),n=e.existing.filter(t=>!r.has(oy(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return iy([...s,...n])},uy=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],ly=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),hy=e=>({userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,lastAccess:e.lastAccess,lastUpdate:e.lastModified});class py{constructor(){this.records=new Map}clear(){this.records.clear()}get(e,t=!1,r=Date.now()){const s=this.records.get(e)??null;if(!s||!t)return s;const n={...s,lastAccess:r};return this.records.set(e,n),n}setAll(e,t=Date.now()){for(const r of e){const e=r.lastModified??t,s=this.records.get(r.profile.userId),n=s?.lastAccess??t;this.records.set(r.profile.userId,{profile:r.profile,lastModified:e,lastAccess:n,source:r.source})}}applyPatch(e,t,r=Date.now()){const s=this.records.get(e.userId),n={userId:e.userId,...t??{},...s?.profile??{}};if(s&&e.lastModified<s.lastModified)return{applied:!1,reason:"stale",record:s};const i={...n,...e.attributes,userId:e.userId};if(s&&e.lastModified===s.lastModified&&(o=s.profile,a=i,uy.every(e=>o[e]===a[e])))return{applied:!1,reason:"duplicate",record:s};var o,a;const c={profile:i,lastModified:e.lastModified,lastAccess:s?.lastAccess??r,source:"subscription"===e.source?"subscription_notify":"contact"===e.source?"contact_notify":"own_notify"};return this.records.set(e.userId,c),{applied:!0,reason:"applied",record:c}}}const gy=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class fy{constructor(e){this.conversationDeletionTimestamps=new Map,this.currentConversation=null,this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.flushTimer=null,this.flushIdleHandle=null,this.activeFlushPromise=null,this.sessionListCommitInProgress=!1,this.mutationRevision=0,this.domainRevisions=new Map,this.pendingDirtyRevisions=new Map,this.userId=e.userId,this.config={schemaVersion:1,ttlSeconds:86400,flushIntervalMs:1e3,maxUserInfoCount:1e3,maxGroupNamecardCount:1e3,maxConversations:e.config?.maxConversations,...e.config};const t="off"===e.cacheEncryptionMode?null:new _f(e.appKey,e.userId);this.store=new Df(t??void 0,e.storageAdapter);const r={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=Uf(r,Tf),this.userInfoKey=Uf(r,Cf),this.groupNamecardKey=Uf(r,Sf),this.sessionListKey=Uf(r,Rf),this.sessionListCheckpointKey=Uf(r,Nf),this.joinedGroupPreviewKey=Uf(r,Of),this.contactRelationKey=Uf(r,Ef),this.contactVersionKey=Uf(r,wf),this.contactMetaKey=Uf(r,Af),this.metadataKey=Uf(r,Mf),this.metadataStore=new Lf(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new $f,this.userInfoCache=new ry,this.groupNamecardCache=new Vf,this.sessionListCache=new ty,this.joinedGroupPreviewCache=new Qf,this.contactCache=new Ff,this.userInfoRuntimeStore=new py,this.loadPromise=this.loadFromStorage()}getConfig(){return this.config}async prepare(){await this.loadPromise}loadConversationSummaries(){return this.conversationCache.getAll()}loadSessionList(){return this.sessionListCache.exportItems()}loadJoinedGroupPreviewSnapshot(){return this.joinedGroupPreviewCache.getSnapshot()}applyJoinedGroupPreviewSnapshot(e){this.joinedGroupPreviewCache.setSnapshot(e),this.scheduleFlush(["joinedGroupPreview"])}async commitJoinedGroupPreviewSnapshot(e){this.activeFlushPromise&&await this.activeFlushPromise;const t=this.getDomainRevision("joinedGroupPreview"),r=new Qf;if(r.setSnapshot(e),await this.store.writeStrictAsync(this.joinedGroupPreviewKey,r.exportRecord()),this.getDomainRevision("joinedGroupPreview")!==t)return this.ensureFlushScheduled(),this.loadJoinedGroupPreviewSnapshot();this.joinedGroupPreviewCache.setSnapshot(e),this.mutationRevision+=1,this.domainRevisions.set("joinedGroupPreview",this.mutationRevision);const s=this.pendingDirtyRevisions.get("joinedGroupPreview");return void 0!==s&&s<=this.mutationRevision&&this.pendingDirtyRevisions.delete("joinedGroupPreview"),await this.metadataStore.touchLastFlush(),this.loadJoinedGroupPreviewSnapshot()}async removeJoinedGroupPreview(e){const t=this.loadJoinedGroupPreviewSnapshot(),r=t.items.filter(t=>t.groupId!==e);return r.length===t.items.length?t:(this.applyJoinedGroupPreviewSnapshot({items:r,meta:{...t.meta}}),await this.flushPending(),this.loadJoinedGroupPreviewSnapshot())}loadSessionListCheckpoint(){return this.sessionListCheckpoint}async flushPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),null!==this.flushIdleHandle&&"undefined"!=typeof cancelIdleCallback&&(cancelIdleCallback(this.flushIdleHandle),this.flushIdleHandle=null),await this.flushNow(),this.activeFlushPromise&&await this.activeFlushPromise,this.pendingDirtyRevisions.size>0&&await this.flushNow()}resetSessionListCheckpoint(){this.sessionListCheckpoint={lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0},this.scheduleFlush(["sessionList"])}loadUserInfoSummaries(){return this.userInfoCache.getAll()}loadGroupNamecards(e){return e?this.groupNamecardCache.getByGroupId(e,Date.now(),!1):this.groupNamecardCache.getAll()}loadContactSnapshot(e="cache"){const t=this.contactCache.buildSnapshot(this.userInfoCache.getAll(),e);return{...t,items:t.items.map(e=>({...e,userInfo:this.userInfoRuntimeStore.get(e.userId,!1)?.profile??e.userInfo}))}}loadContactRelationRecords(){return this.contactCache.getAll()}loadContactVersionState(){return this.contactCache.getVersionState()}loadContactCacheMeta(){return this.contactCache.getMeta()}markConversationAccess(e){const t=Date.now();this.conversationCache.updateLastAccess(e,t)&&this.scheduleFlush(["conversation"])}setCurrentConversation(e){this.currentConversation={conversationId:e.conversationId,type:e.type}}resetCurrentConversation(){this.currentConversation=null}getCurrentConversation(){return this.currentConversation}clearConversationUnreadMessageCount(e){const t=e.readAt??Date.now();let r=!1,s=!1;const n=this.conversationCache.getAll().map(n=>n.conversationId!==e.conversationId||n.type!==e.type?n:(r=!0,0===n.unreadCount?n:(s=!0,{...n,unreadCount:0,lastUpdate:t})));let i=!1;const o=this.sessionListCache.getAll().map(s=>s.conversationId!==e.conversationId||s.conversationType!==e.type?s:(r=!0,0===s.unreadCount&&s.readAt===t?s:(i=!0,{...s,unreadCount:0,readAt:t,updatedAt:t})));return s||i?(s&&this.conversationCache.setAll(n),i&&this.sessionListCache.setAll(o),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0,matched:r}):{items:this.sessionListCache.exportItems(),changed:!1,matched:r}}clearAllConversationUnreadMessageCount(e){const t=e?.readAt??Date.now(),r=this.conversationCache.getAll(),s=r.map(e=>0===e.unreadCount?e:{...e,unreadCount:0,lastUpdate:t}),n=this.sessionListCache.getAll(),i=n.map(e=>0===e.unreadCount&&e.readAt===t?e:{...e,unreadCount:0,readAt:t,updatedAt:t}),o=!this.isConversationListEqual(r,s),a=!this.isSessionListEqual(n,i);return o||a?(o&&this.conversationCache.setAll(s),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationPinnedMutation(e){const t=Date.now(),r=this.conversationCache.getAll(),s=this.conversationCache.getAll().map(r=>r.conversationId!==e.conversationId||r.type!==e.type?r:{...r,isPinned:e.isPinned,pinnedTime:e.isPinned?e.pinnedTime??t:0,lastUpdate:t}),n=this.sessionListCache.getAll(),i=n.map(r=>r.conversationId!==e.conversationId||r.conversationType!==e.type?r:{...r,isPinned:e.isPinned,pinnedTimestamp:e.isPinned?e.pinnedTime??t:0,updatedAt:t}),o=!this.isConversationListEqual(r,s),a=!this.isSessionListEqual(n,i);return o||a?(o&&this.conversationCache.setAll(s),a&&this.sessionListCache.setAll(i),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}deleteConversation(e){const t=this.conversationCache.getAll(),r=this.sessionListCache.getAll();if("number"==typeof e.deletedAt&&this.getConversationLatestUpdate(t,r,e.conversationId,e.type)>e.deletedAt)return{items:this.sessionListCache.exportItems(),changed:!1};if("number"==typeof e.deletedAt){const t=this.buildConversationKey(e.conversationId,e.type),r=this.conversationDeletionTimestamps.get(t)??0;this.conversationDeletionTimestamps.set(t,Math.max(r,e.deletedAt))}const s=t.filter(t=>t.conversationId!==e.conversationId||t.type!==e.type),n=r.filter(t=>t.conversationId!==e.conversationId||t.conversationType!==e.type),i=s.length!==t.length,o=n.length!==r.length;return i||o?(i&&this.conversationCache.setAll(s),o&&this.sessionListCache.setAll(n),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}clearConversations(){const e=this.conversationCache.getAll().length>0,t=this.sessionListCache.getAll().length>0;return e||t?(e&&this.conversationCache.setAll([]),t&&this.sessionListCache.setAll([]),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}applyConversationMarkMutation(e){const t=new Set(e.conversations.filter(e=>e.applied).map(e=>`${e.conversationType}:${e.conversationId}`));if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const r=Date.now(),s=t=>"addMark"===e.operation?t.includes(e.mark)?t:[...t,e.mark]:t.filter(t=>t!==e.mark),n=this.conversationCache.getAll(),i=n.map(e=>{const n=`${e.type}:${e.conversationId}`;if(!t.has(n))return e;const i=s(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,lastUpdate:r}}),o=this.sessionListCache.getAll(),a=o.map(e=>{const n=`${e.conversationType}:${e.conversationId}`;if(!t.has(n))return e;const i=s(e.marks);return this.areConversationMarksEqual(i,e.marks)?e:{...e,marks:i,updatedAt:r}}),c=!this.isConversationListEqual(n,i),d=!this.isSessionListEqual(o,a);return c||d?(c&&this.conversationCache.setAll(i),d&&this.sessionListCache.setAll(a),this.scheduleFlush(["conversation","sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0}):{items:this.sessionListCache.exportItems(),changed:!1}}replaceSessionList(e,t,r){const s=Date.now(),n=e.map(e=>({...e,updatedAt:e.lastMessageAt??s})),i=dy({snapshot:n,existing:this.sessionListCache.getAll(),syncStartedAt:r?.syncStartedAt});this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(i,s)),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}mergeSessionListIncremental(e,t){this.sessionListCache.setAll(this.hydrateSessionListRecordsFromLocalProfiles(this.buildIncrementalSessionListRecords(e))),t&&(this.sessionListCheckpoint={...this.sessionListCheckpoint,...t}),this.scheduleFlush(["sessionList"])}async commitSessionListSync(e){this.activeFlushPromise&&await this.activeFlushPromise,this.sessionListCommitInProgress=!0;let t=[],r=this.getDomainRevision("sessionList");try{let s=!1;for(;!s;){const n=this.getDomainRevision("sessionList");t=this.buildSessionListSyncCandidate(e),await this.writeSessionListStorageRecord(t,e.checkpoint,!0),r=this.getDomainRevision("sessionList"),r===n&&(s=!0)}this.sessionListCache.setAll(t),this.sessionListCheckpoint=e.checkpoint;const n=this.pendingDirtyRevisions.get("sessionList");return void 0!==n&&n<=r&&this.pendingDirtyRevisions.delete("sessionList"),await this.metadataStore.touchLastFlush(),{items:this.sessionListCache.exportItems(),checkpoint:this.sessionListCheckpoint}}finally{this.sessionListCommitInProgress=!1,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}setUserInfoSummaries(e){const t=Date.now();this.userInfoCache.setAll(e,t),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}upsertRuntimeUserInfos(e){0!==e.length&&this.userInfoRuntimeStore.setAll(e)}getRuntimeUserInfo(e,t=!1){return this.userInfoRuntimeStore.get(e,t)?.profile??null}applyUserInfoNotifyPatch(e){const t=this.userInfoCache.getByIds([e.userId],Date.now(),!1)[0],r=t?ly(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,r)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([hy(t)])}getUserInfoSummaries(e,t){const r=Date.now(),s=this.userInfoCache.getByIds(e,r,t);return t&&this.scheduleFlush(["userInfo"]),s}removeUserInfo(e){this.userInfoCache.remove(e),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactMeta"])}getGroupNamecard(e,t,r){const s=this.groupNamecardCache.get(e,t,Date.now(),r);return r&&s&&this.scheduleFlush(["groupNamecard"]),s}setGroupNamecards(e){const t=Date.now();this.groupNamecardCache.setAll(e,t),"number"==typeof this.config.maxGroupNamecardCount&&this.groupNamecardCache.trimMax(this.config.maxGroupNamecardCount),this.scheduleFlush(["groupNamecard"])}removeGroupNamecards(e){this.groupNamecardCache.remove(e),this.scheduleFlush(["groupNamecard"])}setContactVersionState(e){this.contactCache.setVersionState(e),this.scheduleFlush(["contactVersion"])}markContactCacheIncomplete(e){this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:e}),this.scheduleFlush(["contactMeta"])}applyContactSync(e){const t=this.loadContactSnapshot("cache"),r=Date.now();this.userInfoCache.setAll(e.userInfos.map(e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext,lastAccess:r,lastUpdate:r})),r),"full"===e.mode?this.contactCache.replaceAll(e.relations):this.contactCache.upsert(e.relations),this.userInfoCache.trimMax(this.config.maxUserInfoCount),this.contactCache.setVersionState({version:e.version,lastVersionCheckAt:r,lastVersionSource:"sync_page"}),this.contactCache.updateMeta({cacheIntegrity:"complete",lastSyncTs:e.lastSyncTs,lastSuccessfulVersion:e.version,lastSyncMode:e.mode}),this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["userInfo","contactRelation","contactVersion","contactMeta"]);const s=this.loadContactSnapshot("sync");return{snapshot:s,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(s)}}refreshSessionListDisplayFromUserInfos(e){const t=new Map;for(const d of e){if(!d.userId)continue;const e=t.get(d.userId);"number"==typeof e&&"number"==typeof d.lastModified&&e>=d.lastModified||t.set(d.userId,d.lastModified)}if(0===t.size)return{items:this.sessionListCache.exportItems(),changed:!1};const r=Date.now(),s=this.loadContactSnapshot("cache").items,n=new Map(s.map(e=>[e.userId,e])),i=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e])),o=this.sessionListCache.getAll().map(e=>{let s=e;if("singleChat"===e.conversationType&&!this.shouldSkipSessionUserDisplayRefresh(e.conversationId,t,i)){const t=n.get(e.conversationId),o=this.resolveSessionDisplayUserInfo(e.conversationId,i),a=this.buildSingleSessionDisplayFields(e.conversationId,t,o,e.conversationName,e.conversationAvatar);e.conversationName===a.conversationName&&e.conversationAvatar===a.conversationAvatar||(s={...s,conversationName:a.conversationName,conversationAvatar:a.conversationAvatar,updatedAt:r})}const o=s.lastMessage;if(o&&!this.shouldSkipSessionUserDisplayRefresh(o.sender.userId,t,i)){const e=n.get(o.sender.userId),t=this.resolveSessionDisplayUserInfo(o.sender.userId,i),a=this.buildSessionMessageSender(o.sender.userId,o.sender,e,t);this.isSenderEqual(o.sender,a)||(s={...s,lastMessage:{...o,sender:a},updatedAt:r})}return s}),a=this.sessionListCache.getAll(),c=!this.isSessionListEqual(a,o);return c&&(this.sessionListCache.setAll(o),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:c}}refreshSessionListDisplayFromJoinedGroups(e,t){const r=new Map;for(const a of e){const e=a.groupId.trim();e&&r.set(e,a)}if(0===r.size)return{items:this.sessionListCache.exportItems(),changed:!1};const s=Date.now(),n=this.sessionListCache.getAll().map(e=>{if("groupChat"!==e.conversationType)return e;const n=r.get(e.conversationId);if(!n)return e;const i=Boolean(e.conversationName.trim())&&e.conversationName!==e.conversationId;if(t?.onlyWhenNameMissing&&i)return e;const o=n.name?.trim(),a=o||e.conversationName,c=n.avatarUrl??e.conversationAvatar,d=this.mapJoinedGroupRemindTypeToSession(n.remindType),u=void 0!==d&&d!==e.remindType;return a!==e.conversationName||c!==e.conversationAvatar||u?{...e,conversationName:a,conversationAvatar:c,remindType:u?d:e.remindType,updatedAt:s}:e}),i=this.sessionListCache.getAll(),o=!this.isSessionListEqual(i,n);return o&&(this.sessionListCache.setAll(n),this.scheduleFlush(["sessionList"])),{items:this.sessionListCache.exportItems(),changed:o}}removeContact(e){return this.applyContactLocalPatch(()=>this.contactCache.remove(e))}updateContactRemark(e,t){return this.applyContactLocalPatch(()=>this.contactCache.updateRemark(e,t,Date.now()))}applyContactRosterNotice(e){const t=this.loadContactSnapshot("cache"),r=Date.now(),s="add"===e.action?this.contactCache.addByNotice(e.userId,r):this.contactCache.remove(e.userId),n="string"==typeof e.rosterVersion&&e.rosterVersion.trim().length>0&&this.contactCache.updateVersionFromNotice(e.rosterVersion,r);(s||n)&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactVersion","contactMeta"]));const i=this.loadContactSnapshot("cache");return{snapshot:i,changed:this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(i)}}updateConversationsFromServer(e,t){const r=Date.now(),s=this.conversationCache.getAll(),n=this.mergeConversationLists(s,e,r,t?.syncStartedAt),i=!this.isConversationListEqual(s,n);return this.conversationCache.setAll(n),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:n,changed:i}}applyIncomingMessageToConversations(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.conversationCache.getAll(),changed:!1};const r=Date.now(),s=this.conversationCache.getAll(),n=s.findIndex(e=>e.conversationId===t.conversationId&&e.type===t.type),i=n>=0?s[n]:void 0,o=this.buildConversationFromMessage(e,i,r);if(!o)return{items:s,changed:!1};const a=[o,...s.filter((e,t)=>t!==n)];return this.isConversationListEqual(s,a)?{items:s,changed:!1}:(this.conversationCache.setAll(a),this.config.maxConversations&&this.conversationCache.trimMax(this.config.maxConversations),this.scheduleFlush(["conversation"]),{items:this.conversationCache.getAll(),changed:!0})}patchConversationLastMessage(e){const t=this.patchConversationLastMessages([e]);return{items:this.loadSessionList(),changed:t}}patchConversationLastMessages(e){const t=(e,t,r)=>JSON.stringify([t,e,r]),r=new Map;for(const h of e){if(!h.messageId||!h.patch)continue;const e=t(h.conversationId,h.conversationType,h.messageId),s=r.get(e)??[];s.push(h.patch),r.set(e,s)}if(!r.size)return!1;const s=new Map,n=e=>{const t=s.get(e);if(t)return t;const n=r.get(e);if(!n)return;const i=n.map(e=>({...mf(e),...e.type?{type:e.type}:{},...e.body?{body:yf(e.body)}:{},...e.ext?{ext:e.ext}:{},...Object.prototype.hasOwnProperty.call(e,"chatThreadOverview")&&void 0===e.chatThreadOverview?{chatThreadOverview:void 0}:{}}));return s.set(e,i),i},i=(e,t)=>{let r=e;for(const s of t)s.modifiedInfo&&r.modifiedInfo&&s.modifiedInfo.operationCount<r.modifiedInfo.operationCount||(r={...r,...s,...void 0!==s.groupReadCount?{groupReadCount:Math.max(r.groupReadCount??0,s.groupReadCount)}:{}});return gf(e)===gf(r)?e:r},o=this.conversationCache.getAll();let a=!1;const c=o.map(e=>{if(!e.lastMessage)return e;const r=n(t(e.conversationId,e.type,e.lastMessage.msgId));if(!r)return e;const s=i(e.lastMessage,r);return s===e.lastMessage?e:(a=!0,{...e,lastMessage:s})}),d=this.sessionListCache.getAll();let u=!1;const l=d.map(e=>{if(!e.lastMessage)return e;const r=n(t(e.conversationId,e.conversationType,e.lastMessage.msgServerId));if(!r)return e;const s=i(e.lastMessage,r);return s===e.lastMessage?e:(u=!0,{...e,lastMessage:s})});return a&&(this.conversationCache.setAll(c),this.scheduleFlush(["conversation"])),u&&(this.sessionListCache.setAll(l),this.scheduleFlush(["sessionList"])),a||u}applyIncomingMessageToSessionList(e){const t=this.resolveConversationFromMessage(e);if(!t)return{items:this.sessionListCache.exportItems(),changed:!1};const r=this.sessionListCache.getAll(),s=r.find(e=>e.conversationId===t.conversationId&&e.conversationType===t.type),n=this.conversationCache.getAll().find(e=>e.conversationId===t.conversationId&&e.type===t.type)??this.buildConversationFromMessage(e,void 0,Date.now());if(!n)return{items:this.sessionListCache.exportItems(),changed:!1};const i=(e=>{const t=oy(e.nextRecord),r=e.existing.filter(e=>oy(e)!==t);return iy([e.nextRecord,...r])})({existing:r,nextRecord:this.buildSessionListRecordFromConversation(n,e,s,Date.now())});return this.isSessionListEqual(r,i)?{items:this.sessionListCache.exportItems(),changed:!1}:(this.sessionListCache.setAll(i),this.scheduleFlush(["sessionList"]),{items:this.sessionListCache.exportItems(),changed:!0})}async loadFromStorage(){const e=Date.now(),t=await this.readDump(this.conversationKey);this.conversationCache.load(t,e);const r=await this.readDump(this.userInfoKey);this.userInfoCache.load(r,e);const s=await this.readDump(this.groupNamecardKey);this.groupNamecardCache.load(s,e);const n=await this.readValue(this.sessionListKey,null),i=n&&Uu(n)&&Array.isArray(n.items)?n.items:[];this.sessionListCache.load(i,e);const o=(n&&Uu(n)&&Uu(n.checkpoint)?n.checkpoint:null)??await this.readValue(this.sessionListCheckpointKey,null);this.sessionListCheckpoint=this.normalizeSessionListCheckpoint(o);const a=await this.readValue(this.joinedGroupPreviewKey,null);this.joinedGroupPreviewCache.load(a);const c=await this.readDump(this.contactRelationKey),d=await this.readValue(this.contactVersionKey,null),u=await this.readValue(this.contactMetaKey,null);this.contactCache.load(c,d,u),this.refreshContactCacheIntegrity(!1),await this.metadataStore.load()}async readDump(e){const t=await this.store.readAsync(e,{items:[]});return t&&Uu(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&Uu(e)?{lastSyncTime:"number"==typeof e.lastSyncTime?e.lastSyncTime:0,lastSyncFinishedTs:"number"==typeof e.lastSyncFinishedTs?e.lastSyncFinishedTs:0,sessionsLastSyncTs:"number"==typeof e.sessionsLastSyncTs?e.sessionsLastSyncTs:0,lastSuccessfulAt:"number"==typeof e.lastSuccessfulAt?e.lastSuccessfulAt:0}:{lastSyncTime:0,lastSyncFinishedTs:0,sessionsLastSyncTs:0,lastSuccessfulAt:0}}scheduleFlush(e){this.markDirty(e),this.ensureFlushScheduled()}markDirty(e){if(0!==e.length){this.mutationRevision+=1;for(const t of e)this.domainRevisions.set(t,this.mutationRevision),this.pendingDirtyRevisions.set(t,this.mutationRevision)}}getDomainRevision(e){return this.domainRevisions.get(e)??0}ensureFlushScheduled(){null===this.flushTimer&&null===this.flushIdleHandle&&("undefined"==typeof requestIdleCallback?this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flushNow()},this.config.flushIntervalMs):this.flushIdleHandle=requestIdleCallback(()=>{this.flushIdleHandle=null,this.flushNow()},{timeout:this.config.flushIntervalMs}))}takePendingDirtyBatch(){const e=this.pendingDirtyRevisions;return this.pendingDirtyRevisions=new Map,e}restoreDirtyBatch(e){for(const[t,r]of e){const e=this.pendingDirtyRevisions.get(t)??0;this.pendingDirtyRevisions.set(t,Math.max(r,e))}}addQuotaCleanupDomains(e,t){"none"!==t&&(this.mutationRevision+=1,this.domainRevisions.set(t,this.mutationRevision),this.domainRevisions.set("contactMeta",this.mutationRevision),e.set(t,this.mutationRevision),e.set("contactMeta",this.mutationRevision))}async flushNow(){if(this.activeFlushPromise)return void(await this.activeFlushPromise);const e=this.takePendingDirtyBatch();if(this.sessionListCommitInProgress){const t=e.get("sessionList");void 0!==t&&(e.delete("sessionList"),this.restoreDirtyBatch(new Map([["sessionList",t]])))}if(0===e.size)return;const t=this.flushDirtyBatch(e);this.activeFlushPromise=t;try{await t}finally{this.activeFlushPromise=null,this.pendingDirtyRevisions.size>0&&this.ensureFlushScheduled()}}async flushDirtyBatch(e){try{const s=6;for(let n=0;n<=s;n+=1)try{return await this.writeDirtyDomains(e),void(await this.metadataStore.touchLastFlush())}catch(t){if(!Hc(t))return this.restoreDirtyBatch(e),void Ks("Cache flush failed",t);const s=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(e,s),"none"===s)return void Ks("Cache flush failed: no cache entry can be evicted",t);try{await this.writeDomain(s)}catch(r){if(!Hc(r))return this.restoreDirtyBatch(e),void Ks("Cache quota cleanup persistence failed",r)}}Ks("Cache flush failed after quota cleanup attempts")}finally{}}async writeDirtyDomains(e){for(const t of gy)e.has(t)&&await this.writeDomain(t)}async writeDomain(e){switch(e){case"conversation":return void(await this.store.writeAsync(this.conversationKey,{items:this.conversationCache.getAll()}));case"userInfo":return void(await this.store.writeAsync(this.userInfoKey,{items:this.userInfoCache.getAll()}));case"groupNamecard":return void(await this.store.writeAsync(this.groupNamecardKey,{items:this.groupNamecardCache.getAll()}));case"sessionList":return void(await this.writeSessionListStorageRecord());case"joinedGroupPreview":return void(await this.store.writeAsync(this.joinedGroupPreviewKey,this.joinedGroupPreviewCache.exportRecord()));case"contactRelation":return void(await this.store.writeAsync(this.contactRelationKey,{items:this.contactCache.getAll()}));case"contactVersion":return void(await this.store.writeAsync(this.contactVersionKey,this.contactCache.getVersionState()));case"contactMeta":await this.store.writeAsync(this.contactMetaKey,this.contactCache.getMeta())}}async writeSessionListStorageRecord(e=this.sessionListCache.getAll(),t=this.sessionListCheckpoint,r=!1){const s={items:e,checkpoint:t};r?await this.store.writeStrictAsync(this.sessionListKey,s):await this.store.writeAsync(this.sessionListKey,s),await this.store.remove(this.sessionListCheckpointKey)}buildIncrementalSessionListRecords(e){const t=this.sessionListCache.getAll(),r=new Map;for(const n of t)r.set(`${n.conversationType}:${n.conversationId}`,n);const s=Date.now();return(e=>{const t=e.incoming.filter(e=>sy(e)>0),r=new Map;for(const n of e.incoming)r.set(oy(n),n);const s=t.length>0?e.existing.filter(e=>!r.has(oy(e))&&0===sy(e)):e.existing.filter(e=>!r.has(oy(e)));return iy([...s,...e.incoming])})({existing:t,incoming:this.filterItemsAgainstConversationDeletions(e).map(e=>{const t=`${e.conversationType}:${e.conversationId}`;return{...e,updatedAt:e.lastMessageAt??r.get(t)?.updatedAt??s}})})}buildSessionListSyncCandidate(e){const t=Date.now();if("incremental"===e.mode)return this.hydrateSessionListRecordsFromLocalProfiles(this.buildIncrementalSessionListRecords(e.items),t);const r=this.filterItemsAgainstConversationDeletions(e.items).map(e=>({...e,updatedAt:e.lastMessageAt??t}));return this.hydrateSessionListRecordsFromLocalProfiles(dy({snapshot:r,existing:this.sessionListCache.getAll(),syncStartedAt:e.syncStartedAt}),t)}filterItemsAgainstConversationDeletions(e){return e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.conversationType),r=this.conversationDeletionTimestamps.get(t);if(void 0===r)return!0;return Math.max(e.lastMessageAt??0,e.lastMessage?.timestamp??0)>r})}getConversationLatestUpdate(e,t,r,s){const n=e.find(e=>e.conversationId===r&&e.type===s),i=t.find(e=>e.conversationId===r&&e.conversationType===s);return Math.max(n?.lastUpdate??0,n?.lastMessage?.timestamp??0,i?.updatedAt??0,i?.lastMessageAt??0,i?.lastMessage?.timestamp??0)}handleQuotaExceeded(){const e=Date.now(),t=1e3*this.config.ttlSeconds;if(this.groupNamecardCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard";const r=this.groupNamecardCache.getAll().length;if(r>0){const e=this.calculateEvictCount(r,.2);if(this.groupNamecardCache.evictByLru(e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"groupNamecard"}if(this.userInfoCache.removeExpired(t,e))return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),"userInfo";const s=this.evictByPolicy();return this.contactCache.updateMeta({cacheIntegrity:"incomplete",reason:"quota_exceeded"}),this.refreshContactCacheIntegrity(!1),s}evictByPolicy(){const e=this.userInfoCache.getAll().length;if(e>0){const t=this.calculateEvictCount(e,.2);return t>0?(this.userInfoCache.evictByLru(t),"userInfo"):"none"}const t=this.conversationCache.getAll().length,r=this.calculateEvictCount(t,.05);return r>0?(this.conversationCache.evictByLru(r),"conversation"):"none"}calculateEvictCount(e,t){if(e<=0)return 0;const r=Math.floor(e*t);return Math.max(r,1)}mergeConversationLists(e,t,r,s){const n=new Map,i=new Map;for(const d of e){const e=this.buildConversationKey(d.conversationId,d.type);n.set(e,d.lastAccess),i.set(e,d)}const o=[],a=new Set;for(const d of t){const e=this.buildConversationKey(d.conversationId,d.type);a.add(e);const t=n.get(e)??r;o.push({...d,marks:Array.isArray(d.marks)?d.marks:[],lastAccess:t,lastUpdate:r})}const c=e.filter(e=>{const t=this.buildConversationKey(e.conversationId,e.type);return!a.has(t)&&("number"==typeof s&&e.lastUpdate>s)});return[...o,...c]}isConversationListEqual(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){const s=e[r],n=t[r];if(!s||!n)return!1;if(this.buildConversationSignature(s)!==this.buildConversationSignature(n))return!1}return!0}buildConversationSignature(e){const t=e.lastMessage,r=gf(t),s=e.isPinned?"1":"0",n="number"==typeof e.pinnedTime?e.pinnedTime:0,i=e.marks.join(",");return`${e.type}:${e.conversationId}:${e.unreadCount}:${s}:${n}:${i}:${r}`}buildConversationKey(e,t){return`${t}:${e}`}areConversationMarksEqual(e,t){return e.length===t.length&&e.every((e,r)=>e===t[r])}buildConversationFromMessage(e,t,r=Date.now()){const s=this.resolveConversationFromMessage(e);if(!s)return null;const n=e.msgServerId||e.msgLocalId,i=t?.lastMessage?.msgId!==n&&this.shouldIncreaseUnreadForMessage(e)?(t?.unreadCount??0)+1:t?.unreadCount??0,o="SEND"===e.direct?r:t?.lastAccess??r;return{conversationId:s.conversationId,type:s.type,lastMessage:this.buildMessageSnippet(e),unreadCount:i,isPinned:t?.isPinned,pinnedTime:t?.pinnedTime,marks:t?.marks??[],lastAccess:o,lastUpdate:r}}resolveConversationFromMessage(e){if(e.isChatThread||"cmd"===e.type)return null;if("string"!=typeof e.conversationId||!e.conversationId)return null;if("singleChat"===e.conversationType){const t="RECEIVE"===e.direct&&e.from.startsWith(`${this.userId}/`)&&e.sender.userId===this.userId,r="SEND"===e.direct||t?e.conversationId:"string"==typeof e.sender.userId?e.sender.userId:"";return r?{conversationId:r,type:"singleChat"}:null}return"groupChat"===e.conversationType?{conversationId:e.conversationId,type:"groupChat"}:"chatRoom"===e.conversationType?{conversationId:e.conversationId,type:"chatRoom"}:null}buildMessageSnippet(e){const t=(e=>{const t=pl(e);return{userInfoUpdateTime:t?.userInfoUpdateTime,namecardUpdateTime:"groupChat"===e.conversationType?t?.namecardUpdateTime:void 0}})(e),r="multi_body"===e.type&&Array.isArray(e.body)?{body:ff(e.body)}:{body:this.normalizeMessageBody(e.body)};return{...mf(e),msgId:e.msgServerId||e.msgLocalId,from:e.sender.userId||e.from,to:vf({conversationId:e.conversationId,conversationType:e.conversationType,currentUserId:this.userId,from:e.sender.userId||e.from,to:e.to,direct:e.direct}),sender:{...e.sender},direct:e.direct,type:e.type,...r,ext:e.ext,timestamp:e.timestamp,userInfoUpdateTime:t.userInfoUpdateTime,namecardUpdateTime:t.namecardUpdateTime,modifiedInfo:e.modifiedInfo}}normalizeMessageBody(e){return yf(e)}buildSessionListRecordFromConversation(e,t,r,s=Date.now()){const n=new Map(this.loadContactSnapshot("cache").items.map(e=>[e.userId,e])),i=n.get(e.conversationId),o=this.userInfoRuntimeStore.get(e.conversationId,!1)?.profile,a=this.userInfoCache.getByIds([e.conversationId],s,!1)[0],c=o??(a?{userId:a.userId,nickname:a.nickname,avatarUrl:a.avatarUrl,sign:a.sign,ext:a.ext}:null),d=e.lastMessage,u=r?.conversationName,l=r?.conversationAvatar,h="string"==typeof t.sender.userId?t.sender.userId:"",p=this.resolveSessionDisplayUserInfo(h),m=this.buildSessionMessageSender(h,t.sender,n.get(h),p),g=vf({conversationId:e.conversationId,conversationType:e.type,currentUserId:this.userId,from:h,to:t.to,direct:t.direct}),f="singleChat"===e.type?this.buildSingleSessionDisplayFields(e.conversationId,i,c,u,l):"chatRoom"===e.type?this.buildChatRoomSessionDisplayFields(e.conversationId,u,l):this.buildGroupSessionDisplayFields(e.conversationId,u,l);return{conversationId:e.conversationId,conversationType:e.type,unreadCount:this.resolveSessionListUnreadCount(e,t,r),lastMessage:d?{...mf(d),msgServerId:d.msgId,from:h,to:g,sender:m,conversationId:e.conversationId,conversationType:e.type,type:t.type,sendStatus:t.sendStatus,timestamp:d.timestamp,direct:t.direct,body:d.body,ext:d.ext??{}}:null,lastMessageAt:d?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:r?.readAt,remindType:r?.remindType??"DEFAULT",conversationName:f.conversationName,conversationAvatar:f.conversationAvatar,updatedAt:s}}resolveSessionListUnreadCount(e,t,r){const s=r?.unreadCount,n=t.msgServerId||t.msgLocalId;return r?.lastMessage?.msgServerId!==n&&this.shouldIncreaseUnreadForMessage(t)?"number"==typeof s?Math.max(e.unreadCount,s+1):e.unreadCount:"number"==typeof s?Math.max(e.unreadCount,s):e.unreadCount}shouldIncreaseUnreadForMessage(e){if("RECEIVE"!==e.direct||!1===e.isOnline)return!1;const t=this.resolveConversationFromMessage(e);return!t||!this.currentConversation||(this.currentConversation.conversationId!==t.conversationId||this.currentConversation.type!==t.type)}buildSingleSessionDisplayFields(e,t,r,s,n){const i=t?.remark?.trim(),o=t?.userInfo.avatarUrl??r?.avatarUrl??n;if(i)return{conversationName:i,conversationAvatar:o};const a=t?.userInfo.nickname?.trim()||r?.nickname?.trim();return a?{conversationName:a,conversationAvatar:o}:s?{conversationName:s,conversationAvatar:o}:{conversationName:e,conversationAvatar:o}}shouldSkipSessionUserDisplayRefresh(e,t,r){if(!t.has(e))return!0;const s=t.get(e),n=r.get(e);return"number"==typeof s&&"number"==typeof n?.lastUpdate&&n.lastUpdate>s}hydrateSessionListRecordsFromLocalProfiles(e,t=Date.now()){const r=this.loadContactSnapshot("cache").items,s=new Map(r.map(e=>[e.userId,e])),n=new Map(this.userInfoCache.getAll().map(e=>[e.userId,e]));return e.map(e=>{const r=e.lastMessage;if(!r)return e;const i=r.sender.userId,o=s.get(i),a=this.resolveSessionDisplayUserInfo(i,n),c="singleChat"===e.conversationType&&i===e.conversationId?this.buildSingleChatPeerMessageSender(i,r.sender,o,a):this.buildSessionMessageSender(i,r.sender,o,a);return this.isSenderEqual(r.sender,c)?e:{...e,lastMessage:{...r,sender:c},updatedAt:t}})}resolveSessionDisplayUserInfo(e,t){const r=this.userInfoRuntimeStore.get(e,!1)?.profile;if(r)return r;const s=t?.get(e)??this.userInfoCache.getByIds([e],Date.now(),!1)[0];return s?ly(s):null}buildSessionMessageSender(e,t,r,s){const n=r?.remark?.trim();return{userId:e,nickname:n||r?.userInfo.nickname?.trim()||s?.nickname?.trim()||t?.nickname?.trim()||void 0,avatarUrl:r?.userInfo.avatarUrl??s?.avatarUrl??t?.avatarUrl}}buildSingleChatPeerMessageSender(e,t,r,s){const n=this.buildSessionMessageSender(e,void 0,r,s);return{userId:e,nickname:t?.nickname?.trim()||n.nickname,avatarUrl:t?.avatarUrl||n.avatarUrl}}isSenderEqual(e,t){return e.userId===t.userId&&e.nickname===t.nickname&&e.avatarUrl===t.avatarUrl}buildGroupSessionDisplayFields(e,t,r){return t?{conversationName:t,conversationAvatar:r}:{conversationName:e}}mapJoinedGroupRemindTypeToSession(e){if("DEFAULT"===e||"ALL"===e||"AT"===e||"NONE"===e)return e}buildChatRoomSessionDisplayFields(e,t,r){return t?{conversationName:t,conversationAvatar:r}:{conversationName:e}}isSessionListEqual(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){const s=e[r],n=t[r];if(!s||!n)return!1;if(this.buildSessionListSignature(s)!==this.buildSessionListSignature(n))return!1}return!0}buildSessionListSignature(e){const t=e.lastMessage,r=gf(t),s=`${e.conversationName}:${e.conversationAvatar??""}`;return[e.conversationType,e.conversationId,e.unreadCount,e.isPinned?"1":"0",e.pinnedTimestamp??0,e.marks.join(","),e.readAt??0,e.remindType,e.lastMessageAt??0,s,r].join(":")}refreshContactCacheIntegrity(e=!0){const t=this.contactCache.computeIntegrity(this.userInfoCache.getAll());this.contactCache.setMeta(t),e&&this.scheduleFlush(["contactMeta"])}buildContactSnapshotSignature(e){const t=e.items.map(e=>`${e.userId}:${e.userInfo.nickname??""}:${e.userInfo.avatarUrl??""}:${e.userInfo.sign??""}:${e.userInfo.ext??""}:${e.remark}:${e.addTs}`).join("|");return`${e.version}:${e.complete?"1":"0"}:${t}`}applyContactLocalPatch(e){const t=this.loadContactSnapshot("cache"),r=e();return r&&(this.refreshContactCacheIntegrity(!1),this.scheduleFlush(["contactRelation","contactMeta"])),{snapshot:this.loadContactSnapshot("cache"),changed:r&&this.buildContactSnapshotSignature(t)!==this.buildContactSnapshotSignature(this.loadContactSnapshot("cache"))}}}class yy{constructor(){this.handlers=new Map}addEventHandler(e,t){this.handlers.set(e,t)}removeEventHandler(e){this.handlers.delete(e)}dispatch(e,t){const r=[],s=[];for(const i of this.handlers.entries()){const[e]=i;e.startsWith("__internal")?r.push(i):s.push(i)}const n=this.dispatchToHandlers(e,t,r);n?n.then(()=>{this.dispatchToHandlers(e,t,s)}):this.dispatchToHandlers(e,t,s)}dispatchToHandlers(e,t,r){let s=null;for(const[,n]of r){const r=n[e];r&&(s=s?s.then(async()=>{await this.invokeHandler(e,t,r)}):this.invokeHandler(e,t,r))}return s}invokeHandler(e,t,r){try{const s=r(t);return this.isPromiseLike(s)?Promise.resolve(s).then(()=>{}).catch(t=>{this.reportHandlerError(e,t)}):null}catch(s){return this.reportHandlerError(e,s),null}}reportHandlerError(e,t){e!==V.LOG&&zs(`Event handler error for ${e}`,t)}isPromiseLike(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}}const vy={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function Iy(e,t){const r=t.initialDelay*Math.pow(t.backoffMultiplier,e-1),s=Math.min(r,t.maxDelay);if(t.jitter){const e=.2*s,t=(2*Math.random()-1)*e;return Math.max(0,s+t)}return s}function by(e){return new Promise(t=>setTimeout(t,e))}const _y=(e,t)=>JSON.stringify([t,e]),Ty=(e,t,r)=>{const s=e.lastMessage;if(!s)return null;const n=((e,t,r)=>{const s=e.lastMessage,n=r.get(_y(e.conversationId,e.type)),i=s?.msgId&&n?.msgServerId===s.msgId?n:void 0,o=s?.sender?.userId||s?.from||i?.sender?.userId||i?.from||"",a=t.getCurrentUserId?.()??"",c=(i?.sender?.userId||i?.from)===o?i:void 0,d=s?.sender?.userId===o?s.sender:c?.sender,u=s?.direct??c?.direct,l=vf({conversationId:e.conversationId,conversationType:e.type,currentUserId:a,from:o,to:s?.to||c?.to,direct:u});return{...mf(i),...mf(s),from:o,to:l,sender:{...d,userId:o},direct:u,ext:s?.ext??i?.ext??{}}})(e,t,r);return{...mf(n),msgServerId:s.msgId,from:n.from,to:n.to,sender:n.sender,direct:n.direct,conversationId:e.conversationId,conversationType:e.type,type:"string"==typeof s.type&&s.type.length>0?s.type:"text",timestamp:s.timestamp,body:yf(s.body),ext:n.ext}},Cy=async(e,t)=>{const r=(e=>{const t=e.groupManager;return"function"==typeof t?.getGroupInfoList?t:null})(t);if(!r)return new Map;const s=[...new Set(e.filter(e=>"groupChat"===e.type).map(e=>e.conversationId))];if(0===s.length)return new Map;const n=[];for(let a=0;a<s.length;a+=50)n.push(s.slice(a,a+50));const i=new Map;let o=0;return await Promise.all(Array.from({length:Math.min(3,n.length)},async()=>await(async()=>{for(;o<n.length;){const e=o;o+=1;const t=n[e];if(t)try{const e=await r.getGroupInfoList({groupIds:t});for(const t of e)t.groupId&&i.set(t.groupId,t)}catch{}}})())),i},Sy=async(e,t)=>{const r=await Cy(e,t),s=(e=>{const t=new Map,r=e.getCacheManager()?.loadSessionList?.()??[];for(const s of r)s.lastMessage&&t.set(_y(s.conversationId,s.conversationType),s.lastMessage);return t})(t);return e.map(e=>((e,t,r,s)=>{const n=t.getContactSnapshot()?.items.find(t=>t.userId===e.conversationId),i=((e,t)=>{const r=e.getCacheManager();if(!r)return null;const s=r.getRuntimeUserInfo(t,!1);if(s)return s;const n=r.getUserInfoSummaries([t],!1)[0];return n?{userId:n.userId,nickname:n.nickname,avatarUrl:n.avatarUrl,sign:n.sign,ext:n.ext}:null})(t,e.conversationId),o="singleChat"===e.type?((e,t,r)=>{const s=t?.remark?.trim();if(s)return{conversationName:s,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl};const n=t?.userInfo.nickname?.trim()||r?.nickname?.trim();return n?{conversationName:n,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl}:{conversationName:e,conversationAvatar:t?.userInfo.avatarUrl??r?.avatarUrl}})(e.conversationId,n,i):"groupChat"===e.type?(a=e.conversationId,c=r.get(e.conversationId),c?.name?{conversationName:c.name,conversationAvatar:c.avatarUrl}:{conversationName:a}):(e=>({conversationName:e}))(e.conversationId);var a,c;return{conversationId:e.conversationId,conversationType:e.type,unreadCount:e.unreadCount,lastMessage:Ty(e,t,s),lastMessageAt:e.lastMessage?.timestamp??e.lastUpdate,isPinned:e.isPinned,pinnedTimestamp:e.pinnedTime,marks:[],readAt:void 0,remindType:"DEFAULT",conversationName:o.conversationName,conversationAvatar:o.conversationAvatar}})(e,t,r,s))};class Ey{constructor(e=`session-list-${np()}`){this.status="idle",this.seenBatchKeys=new Set,this.itemsByConversation=new Map,this.batchCount=0,this.requestId=e,this.startedAt=Date.now()}getRequestId(){return this.requestId}getStartedAt(){return this.startedAt}start(){"idle"===this.status&&(this.status="connecting")}markSyncing(){if("completed"===this.status||"failed"===this.status||"cancelled"===this.status)throw new ut("Session-list sync session cannot re-enter syncing state after completion",ot.CONTACT_SYNC_CURSOR_INVALID);this.status="syncing"}pushBatch(e){if(e.requestId!==this.requestId)throw new ut("Session-list sync requestId mismatch",ot.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.requestId,received:e.requestId}});if(this.isTerminal())throw new ut("Session-list sync batch received after terminal state",ot.CONTACT_SYNC_CURSOR_INVALID,{details:{requestId:e.requestId,status:this.status}});const t=(r=e.requestId,s=e.batchSequence,`${r}:${s}`);var r,s;if(this.seenBatchKeys.has(t))return{accepted:!1,done:e.isLastBatch};this.markSyncing(),this.seenBatchKeys.add(t);for(const n of e.sessions)this.itemsByConversation.set(`${n.conversationType}:${n.conversationId}`,n);return this.batchCount+=1,e.isLastBatch&&(this.status="completed",this.finishedAt=Date.now()),{accepted:!0,done:e.isLastBatch}}fail(){this.status="failed",this.finishedAt=Date.now()}cancel(){this.status="cancelled",this.finishedAt=Date.now()}getItems(){return[...this.itemsByConversation.values()]}getBatchCount(){return this.batchCount}getStatus(){return this.status}buildSnapshot(){return{requestId:this.requestId,status:this.status,pageCount:this.batchCount,startedAt:this.startedAt,finishedAt:this.finishedAt,seenBatchKeys:[...this.seenBatchKeys]}}isTerminal(){return"completed"===this.status||"failed"===this.status||"cancelled"===this.status}}const wy=0,Ay=5,Ry=10,Ny=11,Oy=1,My=2,Uy=1,Ly=2,ky=3,Dy=e=>e===Oy?"groupChat":e===My?"chatRoom":"singleChat",Py=()=>Wd().lookupType("easemob.pb.MessageBody"),xy=e=>{const t=e.session_id??"",r=(e=>{if(!e)return null;try{const t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{return null}return null})(e.metadata),s="string"==typeof r?.nickname?r.nickname:void 0,n="string"==typeof r?.remark?r.remark:void 0,i="string"==typeof r?.avatarurl?r.avatarurl:"string"==typeof r?.avatarUrl?r.avatarUrl:void 0;return n?{conversationName:n,conversationAvatar:i}:s?{conversationName:s,conversationAvatar:i}:{conversationName:t,conversationAvatar:i}},Fy=e=>{const t={...e};return delete t.type,t},By=(e,t,r)=>{if(!e)return"";const s=`${t}_${r}_`;return e.startsWith(s)?e.slice(s.length):e},Gy=(e,t,r)=>{if(!e)return null;const s=Iu(r.payload?.from,{name:By(e.from?.name,r.org,r.app)}),n=((e,t)=>{if(!e)return{};const r=new vu(t.currentUserId,t.useCustomAttachmentUpload),s=Array.isArray(e.contents)?e.contents.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)):[],n=r.decodeMetadata(e,t.conversationType,t.from===t.currentUserId?"SEND":void 0);n.stream&&s.length>=2&&lu(s,"stream content is not composed into a multi_body message");const i=n.stream?{type:"text",body:{content:n.stream.fullText}}:pu(s,t=>r.decodeContent(t,e.meta)),o={userInfoUpdateTime:Fl(tu(e.userInfoUpdateTime)),namecardUpdateTime:Fl(tu(e.namecardUpdateTime))};return{...n,...i?"multi_body"===i.type&&Array.isArray(i.body)?{type:i.type,body:i.body.map(e=>({...e}))}:{type:i.type,body:{...i.body}}:{},ext:su(e.ext),...o}})(r.payload??null,{currentUserId:r.currentUserId,conversationType:r.conversationType,from:s,useCustomAttachmentUpload:r.useCustomAttachmentUpload}),i={userId:s};return"singleChat"===r.conversationType&&s===r.conversationId&&r.singleChatPeerDisplay&&(r.singleChatPeerDisplay.conversationName!==s&&(i.nickname=r.singleChatPeerDisplay.conversationName),r.singleChatPeerDisplay.conversationAvatar&&(i.avatarUrl=r.singleChatPeerDisplay.conversationAvatar)),{...n,msgServerId:e.id??"",...e.id?{sendStatus:"sent"}:{},from:s,to:vf({conversationId:r.conversationId,conversationType:r.conversationType,from:s,to:Iu(r.payload?.to,void 0),currentUserId:r.currentUserId}),sender:i,conversationId:r.conversationId,conversationType:r.conversationType,type:n.type??(o=t.type,"text"===o||"image"===o||"file"===o||"voice"===o||"video"===o||"location"===o||"custom"===o||"cmd"===o||"combine"===o?o:"text"),timestamp:e.timestamp??0,..."multi_body"===n.type&&Array.isArray(n.body)?{body:n.body}:{body:n.body??Fy(t)},ext:n.ext??r.ext??{}};var o},qy=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[],s=e;for(const n of s){const e="string"==typeof n&&n.startsWith("mark_")?n.slice(5):n,s="number"==typeof e?e:"string"==typeof e?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(s)||s<0||s>19)continue;const i=s;t.has(i)||(t.add(i),r.push(i))}return r},$y=(e,t,r,s,n)=>e.sessions.map(e=>{const i=(e=>{if(!e||0===e.byteLength)return null;try{return Py().toObject(Py().decode(e),{longs:Number,bytes:Uint8Array})}catch{return null}})(e.last_message?.payload),o=e.session_id??"",a=Dy(e.session_type),c=(e=>{const t=e.session_id??"",r=Dy(e.session_type);return"groupChat"===r||"chatRoom"===r?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:xy(e)})(e);return{conversationId:o,conversationType:a,unreadCount:e.unread_count??0,lastMessage:Gy(e.last_message,{},{payload:i,useCustomAttachmentUpload:n?.useCustomAttachmentUpload,conversationId:o,conversationType:a,currentUserId:t,org:r,app:s,singleChatPeerDisplay:"singleChat"===a?c:void 0}),lastMessageAt:e.updated_at,isPinned:"number"==typeof e.pinned_time?e.pinned_time>0:void 0,pinnedTimestamp:e.pinned_time,marks:qy(e.marks),readAt:e.read_receipt,remindType:(d=e.remind_type,d===Uy?"ALL":d===Ly?"AT":d===ky?"NONE":"DEFAULT"),conversationName:c.conversationName,conversationAvatar:c.conversationAvatar};var d}),jy={nested:{easemob:{nested:{sessionlist:{nested:{GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},request_id:{type:"string",id:3},protocol_version:{type:"int32",id:4}}},JID:{fields:{app_key:{type:"string",id:1},name:{type:"string",id:2},domain:{type:"string",id:3},client_resource:{type:"string",id:4}}},Meta:{fields:{id:{type:"uint64",id:1},from:{type:"JID",id:2},timestamp:{type:"uint64",id:4},payload:{type:"bytes",id:6}}},SessionItem:{fields:{session_id:{type:"string",id:1},session_type:{type:"int32",id:2},last_message:{type:"Meta",id:3},updated_at:{type:"int64",id:6},pinned_time:{type:"int64",id:7},unread_count:{type:"uint32",id:8},marks:{rule:"repeated",type:"string",id:9},read_receipt:{type:"int64",id:10},remind_type:{type:"int32",id:11},group_name:{type:"string",id:12},group_avatar:{type:"string",id:13},metadata:{type:"string",id:14}}},GetSessionListRequest:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},last_sync_time:{type:"int64",id:6},need_empty_session:{type:"bool",id:7},need_session_mark:{type:"bool",id:8}}},GetSessionListResponse:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},sessions:{rule:"repeated",type:"SessionItem",id:3},is_last_batch:{type:"bool",id:4},last_sync_finished_ts:{type:"int64",id:5}}},ErrorDetail:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},code:{type:"uint32",id:3},message:{type:"string",id:4}}}}}}}}};let Vy=null,Ky=!1;const zy=()=>Vy||(Ky||(fa.util.Long=Pn,fa.configure(),Ky=!0),Ka(),Vy=fa.Root.fromJSON(jy),Va(Vy),Vy),Hy=e=>zy().lookupType(e),Wy=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}if("bigint"==typeof e)return Number(e);if(e&&"object"==typeof e&&"toString"in e&&"function"==typeof e.toString){const t=Number(e.toString());return Number.isFinite(t)?t:void 0}},Jy=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:Wy(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:Wy(t.protocol_version)??Wy(t.protocolVersion)??0}},Qy=e=>{if(!e||"object"!=typeof e)return;const t=e;return{appKey:"string"==typeof t.app_key?t.app_key:"string"==typeof t.appKey?t.appKey:void 0,name:"string"==typeof t.name?t.name:void 0,domain:"string"==typeof t.domain?t.domain:void 0,clientResource:"string"==typeof t.client_resource?t.client_resource:"string"==typeof t.clientResource?t.clientResource:void 0}},Zy=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==Wy(t.id)?String(Wy(t.id)):void 0,from:Qy(t.from),timestamp:Wy(t.timestamp),payload:t.payload instanceof Uint8Array?t.payload:Array.isArray(t.payload)?Uint8Array.from(t.payload.filter(e=>"number"==typeof e)):void 0}};class Yy{constructor(){this.requestType=Hy("easemob.sessionlist.GetSessionListRequest"),this.responseType=Hy("easemob.sessionlist.GetSessionListResponse"),this.errorType=Hy("easemob.sessionlist.ErrorDetail")}encodeRequest(e){const t=this.requestType.create({type:e.type,header:e.header?{resource:e.header.resource,timestamp:e.header.timestamp,request_id:e.header.requestId,protocol_version:e.header.protocolVersion}:void 0,org:e.org,app:e.app,username:e.username,last_sync_time:e.lastSyncTime??0,need_empty_session:e.includeEmpty??!1,need_session_mark:e.includeMark??!0});return this.requestType.encode(t).finish()}decode(e){const t=this.tryDecodeError(e);if(t)return t;const r=this.tryDecodeResponse(e);if(r)return r;const s=this.tryDecodeRequest(e);return s||{type:wy}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=Wy(t.type);return r!==Ry?null:{type:r,header:Jy(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:Wy(t.last_sync_time)??0,includeEmpty:!0===t.need_empty_session,includeMark:!0===t.need_session_mark}}catch{return null}}tryDecodeResponse(e){try{const t=this.responseType.toObject(this.responseType.decode(e),{longs:String,bytes:Uint8Array}),r=Wy(t.type);return r!==Ny?null:{type:r,header:Jy(t.header),sessions:Array.isArray(t.sessions)?t.sessions.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{session_id:"string"==typeof t.session_id?t.session_id:void 0,session_type:Wy(t.session_type),last_message:Zy(t.last_message),updated_at:Wy(t.updated_at),pinned_time:Wy(t.pinned_time),unread_count:Wy(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:Wy(t.read_receipt),remind_type:Wy(t.remind_type),group_name:"string"==typeof t.group_name?t.group_name:void 0,group_avatar:"string"==typeof t.group_avatar?t.group_avatar:void 0,metadata:"string"==typeof t.metadata?t.metadata:void 0}})(e)):[],isLastBatch:!0===t.is_last_batch,lastSyncFinishedTs:Wy(t.last_sync_finished_ts)}}catch{return null}}tryDecodeError(e){try{const t=this.errorType.toObject(this.errorType.decode(e),{longs:String,bytes:Uint8Array}),r=Wy(t.type);return r!==Ay?null:{type:r,header:Jy(t.header),code:Wy(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const Xy=async e=>{const t=e.client.getCacheManager(),r=e.client.getRestContext(),s=e.client.getSessionListSyncWsUrls();if(!t||0===s.length)throw new ht("session-list sync websocket is unavailable",{code:ot.CONNECTION_WEBSOCKET_ERROR,details:{protocol:"session-list",stage:"socket_connect"}});const[n,i]=r.appKey.split("#");if(!n||!i)throw new mt("session-list appKey is invalid",{code:ot.VALIDATION_INVALID_FORMAT,details:{appKey:r.appKey}});const o=t.loadSessionListCheckpoint(),a=(e=>({type:10,header:{resource:e.resource,timestamp:Date.now(),requestId:e.requestId,protocolVersion:e.protocolVersion??1},org:e.org,app:e.app,username:e.username,lastSyncTime:e.lastSyncTime,includeEmpty:e.params?.includeEmpty??!1,includeMark:!0}))({requestId:e.session.getRequestId(),resource:r.clientResource,org:n,app:i,username:r.userId,lastSyncTime:(c=o.sessionsLastSyncTs,Math.max(0,c-2e4)),params:e.params});var c;const d=new Yy;let u=0,l=o.sessionsLastSyncTs;return await e.client.getSharedSyncWebSocketSession().request({dataType:"conversation",label:"session-list-sync",requestId:e.session.getRequestId(),encode:()=>d.encodeRequest(a),decode:e=>{const t=d.decode(e);return{type:t.type,requestId:"header"in t?t.header?.requestId:void 0,frame:t}},onFrame:t=>{if(5===t.type&&"code"in t&&"message"in t)throw 1002===(s=t).code?new pt(s.message,{code:ot.AUTH_TOKEN_EXPIRED,details:{protocol:"session-list",responseCode:s.code}}):1003===s.code?new ut(s.message,ot.SERVER_BUSY,{details:{protocol:"session-list",responseCode:s.code}}):1501===s.code||1001===s.code?new mt(s.message,{code:ot.VALIDATION_INVALID_FORMAT,details:{protocol:"session-list",responseCode:s.code}}):1503===s.code?new ut(s.message,ot.OPERATION_UNSUPPORTED,{details:{protocol:"session-list",responseCode:s.code}}):(s.code,new ut(s.message,ot.REST_BUSINESS_UNKNOWN,{details:{protocol:"session-list",responseCode:s.code}}));var s;if(11!==t.type)throw new ut("session-list response type is invalid",ot.MESSAGE_DECODE_FAILED,{details:{responseType:t.type}});const o=t,a=o.header?.requestId;if(a&&a!==e.session.getRequestId())return;u+=1,Vs("Decoded session-list sync raw response",{requestId:e.session.getRequestId(),batchSequence:u,response:o});const c=$y(o,r.userId,n,i,e.client.getMessageCreationOptions?.()),d=e.session.pushBatch({requestId:e.session.getRequestId(),batchSequence:u,sessions:c,isLastBatch:!0===o.isLastBatch,lastSyncFinishedTs:o.lastSyncFinishedTs});if("number"==typeof o.lastSyncFinishedTs&&(l=o.lastSyncFinishedTs),!d.done)return;return{done:!0,result:{items:e.session.getItems(),lastSyncFinishedTs:l}}}})},ev=e=>new mt(`${e} must be a local paging cursor returned by SDK`,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:`${e} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),tv=(e,t,r)=>{const s=e+t;return s<r?String(s):""},rv=e=>({...e}),sv=e=>{const t=(e=>e?{...mf(e),msgId:e.msgServerId,from:e.from,to:e.to,sender:{...e.sender},type:e.type??"unknown",body:yf(e.body),ext:e.ext,timestamp:e.timestamp}:null)(e.lastMessage),r=e.lastMessageAt??e.lastMessage?.timestamp??0;return{conversationId:e.conversationId,type:e.conversationType,lastMessage:t,unreadCount:e.unreadCount,isPinned:e.isPinned,pinnedTime:e.pinnedTimestamp,marks:e.marks,lastAccess:r,lastUpdate:r}},nv=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,iv=e=>{if(!Number.isInteger(e.pageSize)||e.pageSize<=0)throw new mt("pageSize must be a positive integer",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"pageSize",message:"pageSize must be a positive integer",rule:"range"}]}});const t=((e,t)=>{if(void 0===e||""===e)return 0;if(!/^\d+$/.test(e))throw ev(t);const r=Number.parseInt(e,10);if(!Number.isSafeInteger(r)||r<0)throw ev(t);return r})(e.cursor,"cursor"),r=[];for(const s of e.items){if("chatRoom"===s.conversationType)continue;const e=nv(s.remindType);e&&r.push({conversationId:s.conversationId,conversationType:s.conversationType,remindType:e})}return{conversations:r.slice(t,t+e.pageSize),cursor:tv(t,e.pageSize,r.length)}},ov=()=>Date.now(),av={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},cv=(e,t)=>({status:e,determinedAt:ov(),reason:t}),dv=e=>e instanceof ut&&(e.code===ot.SERVER_BUSY||1103===e.code),uv=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:dv(e)});class lv{constructor(e){this.running=null,this.currentSession=null,this.activeFinish=null,this.cancelled=!1,this.capabilityState={status:"unknown"},this.client=e}getCapabilityState(){return this.capabilityState}cancel(){this.cancelForTeardown()?.()}cancelForTeardown(){this.cancelled=!0,this.currentSession?.cancel();const e=this.activeFinish;return this.activeFinish=null,e?()=>{e({dataType:"conversation",status:"failed",error:{dataType:"conversation",code:ot.SESSION_LIST_CANCELLED,stage:"cancelled",message:"session-list sync cancelled",retryable:!1}})}:null}refresh(e){return this.cancelled?Promise.resolve([]):(this.running||(this.currentSession=new Ey,this.currentSession.start(),this.running=this.runRefresh(this.currentSession,{includeEmpty:e.includeEmpty,includeMark:!0}),this.running.finally(()=>{this.running=null,this.currentSession=null})),this.running)}async runRefresh(e,t){const r=this.client.getCacheManager();if(!r)return[];let s=!1;const n=e=>{s||(s=!0,this.client.emitSyncDataFinished(e))};this.activeFinish=n;try{this.client.emitSyncDataStart("conversation");const s=await this.tryDirectFallback(r);if(this.cancelled)return[];if(s)return this.client.emitConversationListUpdate("conversation",!0),n({dataType:"conversation",status:"success"}),s;const o=r.loadSessionListCheckpoint().sessionsLastSyncTs>0?"incremental":"full";let a=0;const c=await async function(e,t,r={}){const s={...vy,...r};let n;for(let o=1;o<=s.maxAttempts;o++)try{return await e()}catch(i){if(n=i,!t(i))throw i;if(o>=s.maxAttempts)throw i;const e=Iy(o,s);await by(e)}throw n}(async()=>{if(this.cancelled)throw new ut("session-list sync controller is cancelled");a+=1;const r=1===a?e:this.createRetrySession();r.start();try{return await Xy({client:this.client,session:r,params:t})}catch(s){throw this.cancelled||r.fail(),s}},e=>!this.cancelled&&dv(e),av);if(this.cancelled)return[];const d={result:c,syncStartedAt:e.getStartedAt()},u=d.result.items;this.capabilityState={status:"available",determinedAt:ov()};const l={lastSyncTime:d.result.lastSyncFinishedTs,lastSyncFinishedTs:d.result.lastSyncFinishedTs,sessionsLastSyncTs:d.result.lastSyncFinishedTs,lastSuccessfulAt:ov()};try{if(await r.commitSessionListSync({items:u,mode:o,checkpoint:l,syncStartedAt:d.syncStartedAt}),this.cancelled)return[]}catch(i){if(this.cancelled)return[];e.fail();const t=new yt("Session-list final persistence failed",{details:{cause:i instanceof Error?i.message:String(i)}});return this.client.emitConversationListUpdate("conversation",!0),n({dataType:"conversation",status:"failed",error:uv(t)}),r.loadSessionList()}const h=r.loadSessionList();return r.updateConversationsFromServer(h.map(sv),{syncStartedAt:d.syncStartedAt}),await r.flushPending(),this.cancelled?[]:(this.client.emitConversationListUpdate("conversation","full"===o),n({dataType:"conversation",status:"success"}),h)}catch(i){if(this.cancelled)return[];const t=i instanceof ut?i:new ut(i instanceof Error?i.message:String(i));e.fail();const s=(e=>e.code===ot.OPERATION_UNSUPPORTED||e.code===ot.AUTH_UNAUTHORIZED?{capabilityState:cv("unsupported",e.message),shouldUseFallback:!0}:e.code===ot.AUTH_TOKEN_EXPIRED||e.code===ot.AUTH_BIND_ANOTHER_DEVICE?{shouldUseFallback:!0}:e.code===ot.SERVER_BUSY||1103===e.code?{shouldUseFallback:!0,shouldRetry:!0}:e.code===ot.CONTACT_SYNC_CURSOR_INVALID?{shouldUseFallback:!0,shouldResetCheckpoint:!0}:{shouldUseFallback:!0})(t);s.capabilityState&&(this.capabilityState=s.capabilityState),s.shouldResetCheckpoint&&r.resetSessionListCheckpoint();const o=await this.buildFallbackSessionList(r);return this.cancelled?[]:(s.shouldUseFallback&&r.replaceSessionList(o),this.client.emitConversationListUpdate("conversation",!0),n({dataType:"conversation",status:"failed",error:uv(t)}),o)}finally{this.activeFinish===n&&(this.activeFinish=null)}}async tryDirectFallback(e){if("unsupported"===(t=this.capabilityState).status||"unconfigured"===t.status){const t=await this.buildFallbackSessionList(e);return this.cancelled||e.replaceSessionList(t),t}var t;const r=this.client.hasSessionListSyncWsUrl(),s=this.client.isSessionListDnsProbeAvailable();if(!r&&!s){this.capabilityState=cv("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return this.cancelled||e.replaceSessionList(t),t}return null}createRetrySession(){return new Ey}async buildFallbackSessionList(e){return await(async(e,t)=>await Sy(e,t))(e.loadConversationSummaries(),this.client)}}const hv=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),pv=async e=>{if("string"==typeof e||hv(e)||ArrayBuffer.isView(e))return(e=>"string"==typeof e?(new TextEncoder).encode(e):hv(e)?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength))(e);if((e=>"undefined"!=typeof Blob&&e instanceof Blob&&"function"==typeof e.arrayBuffer||"object"==typeof e&&null!==e&&"function"==typeof e.arrayBuffer)(e))return new Uint8Array(await e.arrayBuffer());throw new ut("sync websocket frame payload type is invalid",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",payloadType:typeof e}})},mv=e=>{const t=Math.max(e-1,0),r=1e3*Math.pow(2,t);return Math.min(r,5e3)},gv=async e=>{await new Promise(t=>{setTimeout(t,e)})},fv=e=>e instanceof Error?e:new Error(String(e));class yv{constructor(e){this.pending=new Map,this.socket=null,this.state="idle",this.connectPromise=null,this.activeUrl="",this.urlIndex=0,this.attempt=0,this.connectTimer=null,this.idleTimer=null,this.retryTimer=null,this.completeCloseTimer=null,this.cancelled=!1,this.getUrls=e.getUrls,this.socketAdapter=e.socketAdapter}async request(e){if(this.cancelled)throw new ut("sync websocket session is cancelled",ot.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",requestId:e.requestId}});if(this.pending.has(e.requestId))throw new ut("sync websocket requestId is duplicated",ot.VALIDATION_INVALID_FORMAT,{details:{stage:"request_send",requestId:e.requestId}});this.clearCompleteCloseTimer();const t=new Promise((t,r)=>{this.pending.set(e.requestId,{...e,resolve:t,reject:r})});t.catch(()=>{});try{await this.ensureConnected(),this.sendPendingRequest(this.pending.get(e.requestId))}catch(r){this.rejectPending(e.requestId,fv(r))}return await t}cancel(e="sync-websocket-cancelled"){this.cancelled=!0;const t=new ut("sync websocket cancelled",ot.CONTACT_SYNC_CANCELLED,{details:{stage:"cancelled",reason:e}});this.rejectAll(t),this.closeSocket(4001,e),this.clearTimers(),this.connectPromise=null,this.state="idle"}close(e="sync-websocket-closed"){this.closeSocket(1e3,e),this.clearTimers(),this.connectPromise=null,this.state="idle",this.attempt=0}async ensureConnected(){if("open"!==this.state||this.socket?.readyState!==hn){if(this.connectPromise)return await this.connectPromise;this.attempt=0,this.connectPromise=this.connectWithRetry();try{await this.connectPromise}finally{this.connectPromise=null}}}async connectWithRetry(){let e=null;for(;!this.cancelled&&this.pending.size>0&&this.attempt<3;){this.attempt+=1,this.attempt>1&&Ks("sync websocket retry started",this.buildLogContext({reason:e?.message}));try{return void(await this.openSocket())}catch(t){if(e=fv(t),this.cancelled||0===this.pending.size)throw e;if(this.attempt>=3)throw Ks("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),e;const r=mv(this.attempt);Ks("sync websocket retry scheduled",this.buildLogContext({delayMs:r,reason:e.message})),await gv(r)}}throw new ht("sync websocket retry exhausted",{code:ot.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect",reason:e?.message??"unknown"}})}async openSocket(){const e=await this.getUrls();if(0===e.length)throw new ht("sync websocket urls are unavailable",{code:ot.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});const t=e[this.urlIndex%e.length];if(this.urlIndex+=1,!t)throw new ht("sync websocket url is invalid",{code:ot.CONTACT_SYNC_SOCKET_FAILED,details:{stage:"socket_connect"}});this.activeUrl=t,this.state="connecting",Ks("sync websocket connect started",this.buildLogContext());const r=Bd(this.socketAdapter);let s=null;try{const e=await Promise.race([r.connect({url:t}),new Promise((e,t)=>{s=setTimeout(()=>{t(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},5e3)})]);s&&clearTimeout(s),this.socket=e,e.onMessage(t=>{this.socket===e&&this.handleMessage(t)}),e.onError(()=>{this.socket===e&&this.handleSocketFailure(this.buildConnectionError("sync websocket runtime error","sync_page"))}),e.onClose(t=>{if(this.socket===e)return"closing"===this.state||0===this.pending.size?(this.clearTimers(),this.socket=null,void(this.state="idle")):void this.handleSocketFailure(this.buildConnectionError("sync websocket socket closed","sync_page",{closeCode:t.code,closeReason:t.reason}))}),this.state="open",this.resetIdleTimer(),Ks("sync websocket connected",this.buildLogContext())}catch(n){if(s&&clearTimeout(s),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),n instanceof ht)throw n;throw this.buildConnectionError("sync websocket socket create failed","socket_connect",{cause:n instanceof Error?n.message:String(n)})}}async handleMessage(e){try{this.resetIdleTimer();const t=await pv(e);if(!(await this.routeFrame(t)))return}catch(t){const e=fv(t);this.rejectAll(e),this.closeSocket(4e3,"sync-websocket-frame-failed"),this.clearTimers(),this.state="idle"}}async routeFrame(e){const t=[];let r=null;for(const n of this.pending.values())try{const t=n.decode(e);if(t.requestId&&t.requestId===n.requestId){try{const e=await n.onFrame(t.frame,this.socket);e?.done&&(this.pending.delete(n.requestId),n.resolve(e.result),this.closeIfComplete())}catch(s){this.pending.delete(n.requestId),n.reject(fv(s)),this.closeIfComplete()}return!0}t.requestId||1!==t.type||r||(r={pending:n,frame:t.frame})}catch(s){t.push(fv(s))}if(r)return await r.pending.onFrame(r.frame,this.socket),!0;if(this.pending.size>0&&t.length===this.pending.size)throw new ut("sync websocket frame decode failed",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:t[0]?.message}});return Ks("sync websocket frame ignored",this.buildLogContext({reason:t[0]?.message??"requestId not matched"})),!1}handleSocketFailure(e){if(this.closeSocket(4e3,"sync-websocket-failed"),this.clearTimers(),this.state="idle",!this.cancelled&&0!==this.pending.size)return this.attempt>=3?(Ks("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),void this.rejectAll(e)):void(this.connectPromise=this.connectWithRetry().then(()=>{this.resendPendingRequests()}).catch(e=>{this.rejectAll(fv(e))}).finally(()=>{this.connectPromise=null}))}resendPendingRequests(){for(const e of this.pending.values())this.sendPendingRequest(e)}sendPendingRequest(e){if(e&&this.socket&&this.socket.readyState===hn)try{this.socket.send(e.encode()).catch(t=>{this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}),Ks("sync websocket request sent",this.buildLogContext({requestId:e.requestId,dataTypes:[e.dataType]})),this.resetIdleTimer()}catch(t){this.rejectPending(e.requestId,this.buildConnectionError("sync websocket request send failed","request_send",{cause:t instanceof Error?t.message:String(t)}))}}rejectPending(e,t){const r=this.pending.get(e);r&&(this.pending.delete(e),r.reject(t),this.closeIfComplete())}rejectAll(e){const t=[...this.pending.values()];this.pending.clear(),t.forEach(t=>{t.reject(e)})}closeIfComplete(){this.pending.size>0||(this.clearCompleteCloseTimer(),this.completeCloseTimer=setTimeout(()=>{this.completeCloseTimer=null,this.pending.size>0||(Ks("sync websocket closed after complete",this.buildLogContext()),this.close("sync-websocket-complete"))},0))}resetIdleTimer(){this.clearIdleTimer(),0!==this.pending.size&&(this.idleTimer=setTimeout(()=>{this.handleSocketFailure(this.buildConnectionError("sync websocket socket idle timeout","sync_page"))},1e4))}clearTimers(){this.clearConnectTimer(),this.clearIdleTimer(),this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.clearCompleteCloseTimer()}clearConnectTimer(){this.connectTimer&&(clearTimeout(this.connectTimer),this.connectTimer=null)}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}clearCompleteCloseTimer(){this.completeCloseTimer&&(clearTimeout(this.completeCloseTimer),this.completeCloseTimer=null)}closeSocket(e,t){const r=this.socket;this.socket=null,!r||r.readyState>=pn||(this.state="closing",r.close(e,t))}buildConnectionError(e,t,r={}){return new ht(e,{code:ot.CONTACT_SYNC_SOCKET_FAILED,details:{stage:t,url:this.activeUrl,...r}})}buildLogContext(e={}){return{attempt:this.attempt,maxAttempts:3,url:ct(this.activeUrl),pendingCount:this.pending.size,dataTypes:[...new Set([...this.pending.values()].map(e=>e.dataType))],...e}}}const vv=(e,t)=>{if(!e.matchField)return!1;const r=t[e.matchField];return void 0!==e.matchPattern?"string"==typeof r&&r.includes(e.matchPattern):void 0===e.matchValue?void 0!==r:r===e.matchValue||!("string"!=typeof r&&"number"!=typeof r||"string"!=typeof e.matchValue&&"number"!=typeof e.matchValue)&&String(r)===String(e.matchValue)};function Iv(e,t,r){if(!e)return;const s=r&&"object"==typeof r?r:{},n="string"==typeof s.error?s.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)(s),o="string"==typeof s.error_description?s.error_description:"string"==typeof s.message?s.message:"string"==typeof s.desc?s.desc:void 0,a=(e,t=!1)=>{const r=(e,r,s)=>({reasonKey:e,entry:r,matchedBy:t?"common":s});if(n&&e[n])return r(n,e[n],"key");for(const[n,i]of Object.entries(e))if(vv(i,s))return r(n,i,"field");if(void 0!==i)for(const[s,n]of Object.entries(e)){if(n.code===i||n.canonicalCode===i)return r(s,n,"code");if(Array.isArray(n.aliases)&&n.aliases.includes(String(i)))return r(s,n,"alias")}if(o)for(const[s,n]of Object.entries(e))if(Array.isArray(n.aliases)&&n.aliases.includes(o))return r(s,n,"alias")},c=t?e.apis[t]:void 0,d=c?a(c.errors):void 0;if(d)return d;for(const u of Object.values(e.common)){const e=a(u.errors,!0);if(e)return e}}function bv(e){const t=e.entry?.code??ot.REST_BUSINESS_UNKNOWN,r=e.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:e.apiName,entry:e.entry,mapped:e.mapped,reasonKey:e.reasonKey});return new It(r,{code:t,details:{api:e.apiName,serverCode:e.serverCode,serverMessage:e.serverMessage,httpStatus:e.httpStatus,mapped:e.mapped??Boolean(e.entry),reasonKey:e.reasonKey,matchedBy:e.matchedBy,retryable:e.entry?.retryable,canonicalCode:e.entry?.canonicalCode??e.entry?.code}})}const _v={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"}},Tv=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase();class Cv{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=jp(t?.requestAdapter),this.includeRequestId=t?.includeRequestId??!1,this.defaultHeaders={Accept:"application/json",...t?.headers}}sanitizeUrl(e){try{const t=new URL(e),r=t.searchParams;for(const e of r.keys())r.set(e,"***");const s=r.toString(),n=s?`?${s}`:"";return`${t.origin}${t.pathname}${n}`}catch{return e.split("?")[0]??e}}setAuthToken(e){this.defaultHeaders.Authorization=`Bearer ${e}`}removeAuthToken(){delete this.defaultHeaders.Authorization}buildHttpStatusFallbackError(e,t,r,s){const n={...t.operation?{api:t.operation}:{},url:t.url,method:t.method,httpStatus:e,serverCode:r,serverMessage:s,mapped:!1};if(400===e)return new mt("Invalid request parameters",{code:ot.VALIDATION_UNKNOWN,details:{...n,canonicalCode:ot.VALIDATION_UNKNOWN}});if(401===e){const e=[r,s].some(e=>"string"==typeof e&&/token[ _-]?(?:has[ _-]?)?expired/i.test(e)),t=e?ot.AUTH_TOKEN_EXPIRED:ot.AUTH_UNAUTHORIZED;return new pt(e?"Authentication token expired":"Authentication failed",{code:t,details:{...n,reasonKey:e?"token_expired":"unauthorized",canonicalCode:t}})}return 403===e?new pt("Access forbidden",{code:ot.AUTH_FORBIDDEN,details:{...n,canonicalCode:ot.AUTH_FORBIDDEN}}):429===e?new It("REST rate limit exceeded",{code:ot.SERVICE_LIMIT_EXCEEDED,details:{...n,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:ot.SERVICE_LIMIT_EXCEEDED}}):e>=500?new It("REST business error: request failed",{code:ot.REST_BUSINESS_UNKNOWN,details:{...n,retryable:!0,reasonKey:"server_unknown_error",canonicalCode:ot.REST_BUSINESS_UNKNOWN}}):void 0}async request(e,t={}){const r=`${this.baseUrl}${e}`,s=t.method??"GET",n=Date.now(),i=this.sanitizeUrl(r);Vs("REST request",{method:s,url:i,operation:t.operation});const o=t.operation?(e=>{const t=_v[e];if(t)return t;const r=(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_${Tv(e)}`,operationType:r}})(t.operation):void 0,a=o?Zh(o):void 0,c=a?.startRequest({requestName:o?.operationName,method:s,url:r});let d=0;const u={...this.defaultHeaders,...t.headers};if(this.includeRequestId&&(u[_u]=bu()),t.body&&"GET"!==s){const e=Object.keys(u).some(e=>"content-type"===e.toLowerCase());"string"==typeof t.body?e||(u["Content-Type"]="application/x-www-form-urlencoded"):e||(u["Content-Type"]="application/json")}else if("GET"===s)for(const h of Object.keys(u))"content-type"===h.toLowerCase()&&delete u[h];try{const e=await this.requestAdapter.request({url:r,method:s,headers:u,body:t.body,timeoutMs:t.timeout??this.timeout});d=e.status;const o=((e,t)=>{if("string"!=typeof e)return e;const r=Object.entries(t).find(([e])=>"content-type"===e.toLowerCase()),s=e.trim();if(!(r?.[1].includes("application/json")||s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]")))return e;try{return JSON.parse(s)}catch{return e}})(e.data,e.headers),l=Date.now()-n;(e.status<200||e.status>=300)&&(Ks("REST response error",{method:s,url:i,status:e.status,duration:l}),this.handleErrorPayload(e.status,e.statusText??"",o,{operation:t.operation,url:r,method:s})),Vs("REST response",{method:s,url:i,status:e.status,duration:l});const h=(e=>{if(Array.isArray(e))return e.length;if(!e||"object"!=typeof e)return;const t=e;for(const r of["entities","data","items","messages","conversations","results"]){const e=t[r];if(Array.isArray(e))return e.length}})(o);return c?.finish({code:e.status,success:!0,resultCount:h}),a?.finish({code:0,success:!0,resultCount:h}),o}catch(l){const e=0!==d?d:l instanceof ut?l.code:-1,n=l instanceof Error?l.message:String(l);if(c?.finish({code:e,success:!1,description:n}),a?.finish({code:e,success:!1,description:n}),l instanceof ut)throw l;const o=(e=>{if(!e||"object"!=typeof e)return;const t=e.details;if(!t||"object"!=typeof t)return;const r=t.reason;return"abort"===r||"network"===r||"timeout"===r?r:void 0})(l);if(l instanceof Error&&"AbortError"===l.name||"timeout"===o)throw Ks("REST request timeout",{method:s,url:i,timeout:t.timeout??this.timeout}),new vt(`Request timeout: ${r}`,{code:ot.REST_TIMEOUT,details:{url:r,method:s,timeout:t.timeout??this.timeout}});throw Ks("REST request failed",{method:s,url:i}),new vt(`Request failed: ${r}`,{code:ot.REST_NETWORK_ERROR,details:{url:r,method:s,...o?{reason:o}:{}}})}}handleErrorPayload(e,t,r,s){const n=r&&"object"==typeof r?r:{},i=((e,t)=>{if(!e.error||"object"!=typeof e.error||Array.isArray(e.error))return;const r=e.error,s=r.code;if("number"!=typeof s&&"string"!=typeof s)return;const n=String(s);return/^\d{7}$/.test(n)&&Number(n.slice(0,3))===t?r:void 0})(n,e),o=i?{...n,code:i.code,message:i.message}:r,a=Iv(this.errorMap,s.operation,o),c="string"==typeof n.error?n.error:void 0,d="number"==typeof n.error_code||"string"==typeof n.error_code?n.error_code:"number"==typeof n.errorCode||"string"==typeof n.errorCode?n.errorCode:"number"==typeof n.code||"string"==typeof n.code?n.code:"string"==typeof n.error?n.error:"number"==typeof i?.code||"string"==typeof i?.code?i.code:void 0,u="string"==typeof n.message?n.message:"string"==typeof n.error_description?n.error_description:"string"==typeof n.desc?n.desc:"string"==typeof i?.message?i.message:void 0,l=!!(401!==e&&403!==e||void 0!==c&&"unauthorized"!==c&&"auth_failed"!==c&&"forbidden"!==c)&&(void 0!==c||"string"==typeof n.error_description||"string"==typeof n.message||"string"==typeof n.desc);if(s.operation&&a)throw bv({apiName:s.operation,entry:a.entry,serverCode:d,serverMessage:u,httpStatus:e,mapped:!0,reasonKey:a.reasonKey,matchedBy:a.matchedBy});const h=this.buildHttpStatusFallbackError(e,s,d,u);if(h)throw h;if(s.operation&&l)throw bv({apiName:s.operation,serverCode:d,serverMessage:u,httpStatus:e,mapped:!1,reasonKey:c});throw new vt(`HTTP ${e}: ${t}`,{code:ot.REST_HTTP_ERROR,details:{url:s.url,method:s.method,httpStatus:e}})}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,r){return this.request(e,{...r,method:"POST",body:t})}put(e,t,r){return this.request(e,{...r,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t})}}const Sv=async(e,t,r)=>{const{orgName:s,appName:n}=fs(e.appKey),i=`/${s}/${n}/user/${encodeURIComponent(e.userId)}/roster/metadata/version`,o=new Cv(e.restBaseUrl,{requestAdapter:r,includeRequestId:!0});o.setAuthToken(e.token);try{return((e,t)=>{const r=Date.now(),s=e=>{const s="string"==typeof e.version?e.version:"string"==typeof e.rosterVersion?e.rosterVersion:"";return{version:s,requiresSync:("boolean"==typeof e.requiresSync?e.requiresSync:"boolean"==typeof e.needSync?e.needSync:"boolean"==typeof e.need_sync?e.need_sync:void 0)??s!==t,checkedAt:"number"==typeof e.checkedAt?e.checkedAt:"number"==typeof e.timestamp?e.timestamp:r}};if(Uu(e))return Uu(e.data)?s(e.data):s(e);throw new mt("Invalid contact metadata response",{code:ot.VALIDATION_INVALID_FORMAT,details:{payload:e}})})(await o.get(i),t)}catch(a){if(a instanceof mt)throw a;const e=a instanceof ut&&a.details?a.details:{};throw new vt("Contact metadata request failed",{code:ot.CONTACT_SYNC_METADATA_FAILED,details:{stage:"metadata",cause:a instanceof Error?a.message:String(a),httpStatus:"number"==typeof e.httpStatus?e.httpStatus:void 0,sourceCode:a instanceof ut?a.code:void 0}})}};class Ev{static validate(e,t){try{return{success:!0,data:e.parse(t)}}catch(r){if(r instanceof _m){const e=r.errors.map(e=>({path:e.path.length>0?e.path.join("."):"root",message:e.message,rule:e.code})),t=`Validation failed: ${e.map(e=>`${e.path}: ${e.message}`).join("; ")}`,s=r.errors.some(e=>"invalid_type"===e.code&&"undefined"===e.received)?ot.VALIDATION_REQUIRED:ot.VALIDATION_INVALID_FORMAT;return{success:!1,error:new mt(t,{code:s,details:{fields:e}})}}return{success:!1,error:new mt("Unknown validation error",{code:ot.VALIDATION_UNKNOWN,details:{fields:[]}})}}}static validateOrThrow(e,t){const r=this.validate(e,t);if(r.success&&void 0!==r.data)return r.data;if(r.error)throw r.error;throw new mt("Unknown validation error",{code:ot.VALIDATION_UNKNOWN,details:{fields:[]}})}static safeParse(e,t){return this.validate(e,t)}}const wv=e=>Qg().regex(/^https?:\/\/\S+$/i,e),Av=rf({appKey:Qg().min(1,"appKey is required").optional(),appId:Qg().min(1,"appId is required").optional(),enableUserInfoSync:Yg().optional(),enableSyncData:tf(of(["conversation","contact","group"])).optional(),enableDeliveryReceipt:Yg().optional(),deleteConversationOnGroupDestroyed:Yg().optional(),syncConversationListConfig:rf({includeEmpty:Yg().optional()}).strict().optional(),useCustomAttachmentUpload:Yg().optional(),useFixedDeviceId:Yg().optional(),deviceId:Qg().min(1,"deviceId is required").optional(),serviceConfig:rf({dnsConfigUrls:tf(wv("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:rf({restApiUrl:wv("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:(Rv="serviceConfig.serverUrls.wsUrl must be a valid URL",Qg().regex(/^wss?:\/\/\S+$/i,Rv)).optional()}).optional()}).optional(),useReplacedMessageContents:Yg().optional(),customDeviceName:Qg().min(1,"customDeviceName is required").optional(),customOSPlatform:Zg().int("customOSPlatform must be an integer").min(1,"customOSPlatform must be between 1 and 100").max(100,"customOSPlatform must be between 1 and 100").optional(),uiKitVersion:Qg().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:Qg().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:tf(Xg()).optional(),platformAdapterOptions:rf({prefer:of(["web","wechat-miniapp","qq-miniapp","toutiao-miniapp","baidu-miniapp","alipay-miniapp","dingtalk-miniapp","lark-miniapp","kuaishou-miniapp","jd-miniapp","360-miniapp","harmony-miniapp","quickapp","uniapp","react-native","electron-renderer","electron-main","unknown"]).optional(),runtimeInput:Hg(e=>"object"==typeof e&&null!==e).optional(),transportAdapter:Hg(e=>"object"==typeof e&&null!==e).optional(),overrides:Hg(e=>"object"==typeof e&&null!==e||"function"==typeof e).optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{const r=Number(void 0!==e.appKey)+Number(void 0!==e.appId);0===r?t.addIssue({code:bm.custom,path:["appKey"],message:"appKey or appId is required"}):r>1&&t.addIssue({code:bm.custom,path:["appId"],message:"appKey and appId cannot be used together"}),"enableMd5Check"in e&&t.addIssue({code:bm.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:bm.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:bm.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:bm.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:bm.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:bm.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:bm.custom,path:["enableAutoSyncContacts"],message:"enableAutoSyncContacts is removed; use enableSyncData: ['contact']"});const s=e.serviceConfig&&"object"==typeof e.serviceConfig?e.serviceConfig:void 0,n=s?.serverUrls&&"object"==typeof s.serverUrls?s.serverUrls:void 0;s?.dnsConfigUrls&&n&&t.addIssue({code:bm.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),n&&(void 0!==e.appId&&t.addIssue({code:bm.custom,path:["serviceConfig","serverUrls"],message:"serviceConfig.serverUrls cannot be used when initialized with appId"}),n?.restApiUrl||t.addIssue({code:bm.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),n?.wsUrl||t.addIssue({code:bm.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))});var Rv;const Nv=rf({userId:Qg().min(1,"userId is required"),token:Qg().min(1,"token is required")}),Ov=rf({timeoutMs:Zg().int("timeoutMs must be an integer").min(5e3,"timeoutMs must be at least 5000").max(Zr,"timeoutMs must be at most 120000").optional()}).strict(),Mv=Qg().trim().min(1,"token is required"),Uv=rf({channelName:Qg().trim().min(1,"channelName is required").optional()}).optional(),Lv=tf(Zg({invalid_type_error:"rtcUid must be a number"}).int("rtcUid must be an integer").min(0,"rtcUid must be greater than or equal to 0").max(Number.MAX_SAFE_INTEGER,"rtcUid must be a safe integer")).nonempty("rtcUids is required").transform(e=>Array.from(new Set(e))),kv=rf({protocol:Qg(),domain:Qg().optional(),ip:Qg().optional(),port:sf([Qg(),Zg()]).optional()}).passthrough(),Dv=rf({app_key:Qg().optional(),rest:rf({hosts:tf(kv).nonempty()}),"msync-wx":rf({hosts:tf(kv).nonempty()}),"sync-ws":rf({hosts:tf(kv).nonempty()}).optional(),enableReportLogs:of(["true","false"]).optional(),reportInterval:Zg().positive().finite().optional(),enableDataReport:of(["true","false"]).optional(),enableMd5Check:of(["true","false"]).optional(),uploadinparts_enable:of(["true","false"]).optional()}).passthrough(),Pv=e=>encodeURIComponent(e).replace(/[!'()~]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g,"+"),xv=e=>"function"==typeof URLSearchParams?new URLSearchParams(e):(e=>{const t=new Map;if(e)for(const[r,s]of Object.entries(e))t.set(r,s);return{set(e,r){t.set(e,r)},toString:()=>Array.from(t,([e,t])=>`${Pv(e)}=${Pv(t)}`).join("&")}})(e),Fv="5.2.0",Bv=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],Gv=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"];function qv(e){return"object"==typeof e&&null!==e}function $v(e){return Array.isArray(e)?{hosts:e}:function(e){return qv(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function jv(e){if(!qv(e))return Ev.validateOrThrow(Dv,e);const t=$v(e.rest),r=function(e,t,r){for(const s of t){const t=$v(e[s]);if(t)return{key:s,section:t}}for(const[s,n]of Object.entries(e)){if(!r(s))continue;const e=$v(n);if(e)return{key:s,section:e}}}(e,Gv,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),s={...e,rest:t??e.rest,"msync-wx":r?.section},n="true"===(i=e.enableReportLogs)||!0===i?"true":"false"===i||!1===i?"false":void 0;var i;n&&(s.enableReportLogs=n);const o=function(e){if("number"!=typeof e&&"string"!=typeof e)return;if("string"==typeof e&&""===e.trim())return;const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}(e.reportInterval);void 0!==o?s.reportInterval=o:delete s.reportInterval;const a=function(e){if("true"===e||"false"===e)return e}(e.enableDataReport);a?s.enableDataReport=a:delete s.enableDataReport;const c=function(e){if("true"===e||"false"===e)return e}(e.enableMd5Check);c?s.enableMd5Check=c:delete s.enableMd5Check;const d=function(e){if("true"===e||"false"===e)return e}(e.uploadinparts_enable);return d?s.uploadinparts_enable=d:delete s.uploadinparts_enable,r&&"msync-wx"!==r.key&&Ks("DNS config websocket section normalized",{sourceKey:r.key}),Ev.validateOrThrow(Dv,s)}function Vv(e,t){const r=e.domain||e.ip;if(!r)throw new mt("DNS host missing domain/ip",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"dns.host",message:"DNS host missing domain/ip",rule:"required"}]}});const s=void 0!==e.port?String(e.port):"";return`${"https"===t?"wss":"ws"}://${s&&"80"!==s&&"443"!==s?`${r}:${s}`:r}/websocket`}function Kv(e,t){return"https"===e?"https":"http"===e?"http":t}function zv(e,t){const r=e.domain||e.ip;if(!r)throw new mt("DNS rest host missing domain/ip",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"dns.rest.host",message:"DNS rest host missing domain/ip",rule:"required"}]}});const s=void 0!==e.port?String(e.port):"";return`${t}://${s&&"80"!==s&&"443"!==s?`${r}:${s}`:r}`}function Hv(e,t){const r=e.filter(e=>e.protocol===t);return r.length>0?r:"http"===t?e.filter(e=>"https"===e.protocol):[]}function Wv(e){const t=function(e){return e.filter(e=>Boolean(e.domain))}(e);return t.length>0?t:e.filter(e=>Boolean(e.domain||e.ip))}async function Jv(e,t,r,s){const n=new Cv(e,{requestAdapter:r,includeRequestId:!0});let i="/easemob/server.json",o=!0;try{const t=new URL(e),r=""!==t.pathname&&"/"!==t.pathname,s=""!==t.search;(r||s)&&(i="",o=!1)}catch{i="/easemob/server.json",o=!0}if(o){i=`${i}?${(void 0!==t.appId?xv({app_id:t.appId,sdk_version:Fv,file_version:"1"}):xv({app_key:t.appKey,_v:String(Date.now())})).toString()}`}return jv(await n.get(i,{timeout:s}))}async function Qv(e){const t=e.baseUrls&&e.baseUrls.length>0?e.baseUrls:Bv;if(0===t.length)throw new mt("DNS_CONFIG list is empty",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"serviceConfig.dnsConfigUrls",message:"DNS_CONFIG list is empty",rule:"required"}]}});const r=e.pageProtocol??("undefined"==typeof window||"https:"===window.location?.protocol?"https":"http");let s;for(const o of t){const t=e.loginDeadline,n=t?.remainingMs();if(t&&void 0!==n&&n<=0)throw t.createTimeoutError();try{const t=void 0!==e.appId?{appId:e.appId}:{appKey:e.appKey},s=void 0===n?void 0:Math.min(15e3,n),i=await Jv(o,t,e.requestAdapter,s),a=void 0!==e.appId?i.app_key:e.appKey;if("string"!=typeof a||0===a.length)throw new mt("DNS app_key is required for appId initialization",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"dns.app_key",message:"DNS app_key is required for appId initialization",rule:"required"}]}});const c=Wv(Hv(i["msync-wx"].hosts,r));if(0===c.length)throw new mt("DNS msync-wx hosts resolution failed",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const d=c[0];if(!d)throw new mt("DNS msync-wx hosts resolution failed",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const u=Hv(i.rest.hosts,r);if(0===u.length)throw new mt("DNS rest hosts resolution failed",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const l=u[0];if(!l)throw new mt("DNS rest hosts resolution failed",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const h=c.map(e=>Vv(e,Kv(e.protocol,r))),p=Vv(d,Kv(d.protocol,r));return{appKey:a,websocketUrl:p,websocketUrls:h,baseUrl:o,restBaseUrl:zv(l,Kv(l.protocol,r)),dnsConfig:i}}catch(i){if(t&&t.remainingMs()<=0)throw t.createTimeoutError();Ks("DNS config candidate failed",{baseUrl:o,reason:i instanceof Error?i.message:String(i),error:i instanceof Error&&"function"==typeof i.toJSON?i.toJSON():i}),s=i}}const n={stage:"dns"};throw s&&(n.reason=s.message,"code"in s&&"number"==typeof s.code&&(n.causeCode=s.code)),new ht("DNS_CONFIG exhausted",{code:ot.CONNECTION_DNSLIST_FAILED,details:n})}const Zv=e=>{const t=(e=>{const t=e.trim(),r=/^(https?):\/\//i.exec(t);if(!r?.[1])throw new mt("REST API URL must use http or https protocol");const s=r[1].toLowerCase(),n=t.slice(r[0].length),i=n.search(/[/?#]/),o=i>=0?n.slice(0,i):n,a=o.lastIndexOf("@"),c=a>=0?o.slice(a+1):o;if(!c)throw new mt("REST API URL host is required");let d,u;if(c.startsWith("[")){const e=c.indexOf("]");if(e<=1)throw new mt("REST API URL IPv6 host is invalid");d=c.slice(0,e+1);const t=c.slice(e+1);if(t){if(!t.startsWith(":"))throw new mt("REST API URL authority is invalid");u=t.slice(1)}}else{const e=c.lastIndexOf(":");if(e>=0){if(c.indexOf(":")!==e)throw new mt("REST API URL IPv6 host must use brackets");d=c.slice(0,e),u=c.slice(e+1)}else d=c}if(!d)throw new mt("REST API URL host is required");if(void 0!==u){const e=Number(u);if(!/^\d+$/.test(u)||e<1||e>65535)throw new mt("REST API URL port is invalid")}return{protocol:s,host:d,port:u}})(e),r="http"===t.protocol&&"80"===t.port||"https"===t.protocol&&"443"===t.port,s="https"===t.protocol?"wss":"ws",n=t.port&&!r?`:${t.port}`:"";return`${s}://${t.host}${n}/ws`},Yv=e=>new mt(e,{code:ot.VALIDATION_INVALID_FORMAT,details:{reason:"invalid_rest_response"}}),Xv=e=>{if(!Uu(e))throw Yv("Invalid REST response");return Uu(e.data)?e.data:e},eI=(e,t)=>{for(const r of t){const t=e[r];if("number"==typeof t&&Number.isFinite(t))return t;if("string"==typeof t&&t.trim().length>0){const e=Number(t);if(Number.isFinite(e))return e}}},tI=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t)return t}},rI=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}`},sI=async(e,t)=>{const r=await e.get((e=>`${rI(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=Xv(e),r=eI(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===r)throw Yv("Invalid token expires response");return r})(r)},nI=async(e,t,r)=>{const s=await e.get(((e,t)=>{const r=xv({channelName:t?.channelName??"*"});return`${rI(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${r.toString()}`})(t,r),{operation:"getRtcTokenInfo"});return(e=>{const t=Xv(e);return{appId:tI(t,["app_id","appId"])??"",rtcToken:tI(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:tI(t,["channel_name","channelName"])??"",rtcUid:eI(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:eI(t,["expires_in","expire","expireAt"])??0}})(s)},iI=async(e,t,r)=>{const s=await e.post((e=>`${rI(e)}/rtc_mapper/batch/get`)(t),{data:r},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=Xv(e),r={};for(const[s,n]of Object.entries(t)){const e=Number(s);!Number.isSafeInteger(e)||e<0||"string"!=typeof n||(r[e]=n)}return r})(s)},oI=async(e,t)=>{const r=await e.get((e=>`${rI(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const r=Uu(e)&&Array.isArray(e.data)?e.data:[],s=[];for(const n of r){if(!Uu(n))continue;const e=tI(n,["res","resource","clientResource"]);e&&e!==t.clientResource&&s.push(`${t.userId}/${e}`)}return s})(r,t)},aI=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}`},cI=e=>{const t=new Uint8Array(fa.util.base64.length(e));return fa.util.base64.decode(e,t,0),t},dI=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),uI=async e=>{try{return await e()}catch(t){if(!(t instanceof It))throw t;const e=(e=>{const t="string"==typeof e.details?.serverMessage?e.details.serverMessage:void 0;switch(e.code){case ot.SERVICE_NOT_ENABLED:case ot.TRANSLATE_SERVICE_NOT_ENABLED:return"Translation service is not enabled";case ot.TRANSLATE_PARAM_INVALID:return t?.includes("too long")?"Translation text is too long":t?.includes("target language")?"Invalid target language":"Invalid translation request";case ot.TRANSLATE_USAGE_LIMIT:return"Translation quota has been reached";case ot.TRANSLATE_FAILED:return"Translation service error";default:return}})(t);if(!e)throw t;throw new It(`REST business error: ${e}`,{code:t.code,details:t.details})}},lI=e=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):"",hI=e=>{if("string"!=typeof e)return"";const t=e.trim();return t&&"undefined"!==t&&"null"!==t?t:""},pI=e=>({userId:e}),mI=(e,t)=>{if(!dI(e)||!dI(e.data))throw bv({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},gI=(e,t)=>{if(!dI(e)||!Array.isArray(e.data))throw bv({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},fI=(e,t)=>Array.isArray(e)?e:gI(e,t),yI=async(e,t,r)=>{const s=await uI(()=>e.post(`${aI(t)}/users/${t.userId}/translate`,{text:r.text,to:[...r.targetLanguages]},{operation:"translateMessage"})),n=fI(s,"translateMessage"),i=dI(n[0])?n[0]:null;if(!i)throw bv({apiName:"translateMessage",message:"translateMessage response data is invalid",mapped:!1});const o=Array.isArray(i.translations)?i.translations:[],a=dI(i.detectedLanguage)?i.detectedLanguage:void 0;return{detectedLanguage:a&&"string"==typeof a.language?{language:a.language,score:"number"==typeof a.score?a.score:Number(a.score??0)}:void 0,translations:o.map(e=>dI(e)&&"string"==typeof e.text&&"string"==typeof e.to?{text:e.text,to:e.to}:null).filter(e=>null!==e)}},vI={txt:"text",img:"image",video:"video",file:"file",loc:"location",custom:"custom",combine:"combine"},II={text:"txt",image:"img",video:"video",file:"file",location:"loc",custom:"custom",combine:"combine"},bI={chat:"singleChat",chatroom:"chatRoom",groupchat:"groupChat",singleChat:"singleChat",chatRoom:"chatRoom",groupChat:"groupChat"},_I=(e,t,r)=>{if(!t)return"";if(t.includes("em-redirect"))return t;const{orgName:s,appName:n}=fs(e.appKey),i=t.indexOf("/chatfiles/"),o=i>=0?t.slice(i):t,a=`${e.restBaseUrl}/${s}/${n}${o}`;return _s(a,r)},TI=e=>{if(!e||"object"!=typeof e)return;if(Array.isArray(e))return e;const t=Object.values(e),r=[];for(const s of t)Array.isArray(s)&&r.push(...s);return r.length>0?r:void 0},CI=(e,t,r)=>{const s=lI(r.contentType??r.type),n=II[s];if(!n)return null;const i=dI(r.content)?r.content:{},o=((e,t)=>{const r=lI(t.conversationType);if("groupchat"===r||"chatroom"===r)return lI(t.receiverId);const s=lI(t.senderId);return s===e?lI(t.receiverId):s})(t,r),a=bI[lI(r.conversationType)]??"singleChat",c={msgServerId:lI(r.messageId),msgLocalId:lI(r.messageId),from:lI(r.senderId),to:lI(r.receiverId),conversationId:o,conversationType:a,type:n,ext:dI(r.ext)?r.ext:{},timestamp:"number"==typeof r.sentTime?r.sentTime:new Date(lI(r.sentTime)).getTime(),sender:{userId:lI(r.senderId)},highlight:TI(r.highlight),text:"string"==typeof r.text?r.text:void 0};let d;const u=lI(i.remotePath??i.url),l=lI(i.secret??i.secretKey);switch(n){case"txt":d={type:"txt",content:lI(i.message??r.text)};break;case"img":{const t=_I(e,u,l);d={type:"img",url:t,thumb:i.thumb?_I(e,lI(i.thumb),lI(i.thumb_secret??i.thumbnailSecretKey)):`${t}&thumbnail=true`,secret:l,width:Number(i.width??(dI(i.size)?i.size.width:0))||0,height:Number(i.height??(dI(i.size)?i.size.height:0))||0,fileLength:Number(i.file_length??i.fileLength??0)};break}case"video":d={type:"video",url:_I(e,u,l),thumb:i.thumb||i.thumbnailRemotePath?_I(e,lI(i.thumb??i.thumbnailRemotePath),lI(i.thumb_secret??i.thumbnailSecretKey)):"",secret:l,filename:lI(i.filename??i.displayName),duration:Number(i.length??i.duration??0),fileLength:Number(i.file_length??i.fileLength??0)};break;case"file":d={type:"file",url:_I(e,u,l),secret:l,filename:lI(i.filename??i.displayName),fileLength:Number(i.file_length??i.fileLength??0)};break;case"loc":d={type:"loc",latitude:Number(i.lat??i.latitude??0),longitude:Number(i.lng??i.longitude??0),address:lI(i.addr??i.address),buildingName:lI(i.buildingName)};break;case"custom":d={type:"custom",customEvent:lI(i.customEvent),customExts:dI(i.customExts)?i.customExts:{}};break;default:return null}return{...c,body:d}},SI=async(e,t,r)=>{const s=`${aI(t)}/users/${t.userId}/messages/search/get`,n=((e,t)=>{const{option:r,pageNum:s=1,pageSize:n=20}=e,i=r.keywordList.map(e=>e.trim()).filter(e=>e.length>0),o={searchMode:"default",highlightEnable:!0,page:s,size:n};return 1===i.length?o.keyword=i[0]:(o.keywords=i,o.keywordMatch="and"===r.keywordListMatchType?"all":"any"),r.conversationId&&("singleChat"===r.conversationType?o.participantPairs=[{userId1:t,userId2:r.conversationId}]:"groupChat"===r.conversationType?o.groupIds=[r.conversationId]:"chatRoom"===r.conversationType&&(o.chatroomIds=[r.conversationId])),r.msgTypes&&r.msgTypes.length>0&&(o.contentType=r.msgTypes.map(e=>vI[e]??e).join(",")),void 0!==r.startTime&&(o.startTime=r.startTime),void 0!==r.endTime&&(o.endTime=r.endTime),r.searchScope&&(o.searchExt=r.searchScope),r.direction&&(o.sort="up"===r.direction?"sentTime:asc":"sentTime:desc"),{data:o}})(r,t.userId),i=await e.post(s,n,{operation:"searchMessages"}),o=dI(i)?i:{},a=dI(o.data)?o.data:o,c=dI(a.data)?a.data:a,d=Array.isArray(c.items)?c.items:Array.isArray(c.list)?c.list:[],u=dI(c.pagination)?c.pagination:c,l=Number(u.pageNum??u.page??r.pageNum??1),h=Number(u.pageSize??u.size??r.pageSize??20),p=Number(u.totalPages??0),m=1===u.isFinished||l>=p,g=[];for(const f of d){if(!dI(f))continue;const e=CI(t,t.userId,f);e&&g.push(e)}return{messages:g,pageNum:l,pageSize:h,totalPages:p,isLast:m}},EI={common:{},apis:{sendMessage:{range:"1,4,100,108,110,202,210,213-215,219-222,300-301,303,305,402,405-406,500-501,505-510,602-603,606-607,1200,1299",localErrors:{sendMessage:{operation_cancelled:{code:1,retryable:!1},upload_invalid_appkey:{code:100,retryable:!1},validation_invalid:{code:110,retryable:!1},not_connected:{code:300,retryable:!0},request_timeout:{code:301,retryable:!0},send_failed:{code:303,retryable:!1},upload_failed:{code:402,retryable:!0},file_too_large:{code:405,retryable:!1},file_content_improper:{code:406,retryable:!1},encode_failed:{code:500,retryable:!1}}},errors:{SERVICE_LIMIT_EXCEEDED:{code:4,retryable:!1},TOKEN_EXPIRED:{code:108,retryable:!1},AUTH_FAILED:{code:202,retryable:!1},PERMISSION_DENIED:{code:210,retryable:!1},BIND_ANOTHER_DEVICE:{code:213,retryable:!1},TOO_MANY_DEVICES:{code:214,retryable:!1},USER_MUTED:{code:215,retryable:!1},USER_MUTED_BY_ADMIN:{code:219,retryable:!1},USER_DEVICE_CHANGED:{code:220,retryable:!1},USER_NOT_ON_ROSTER:{code:221,retryable:!1},BLOCKED_BY_RECIPIENT:{code:222,retryable:!1,aliases:["blocked"]},SERVER_SERVING_DISABLED:{code:305,retryable:!1},MESSAGE_INCLUDE_ILLEGAL_CONTENT:{code:501,retryable:!1},SERVICE_NOT_ENABLED:{code:505,retryable:!1},MESSAGE_EXPIRED:{code:506,retryable:!1},MESSAGE_ILLEGAL_WHITELIST:{code:507,retryable:!1},MESSAGE_EXTERNAL_LOGIC_BLOCKED:{code:508,retryable:!1},MESSAGE_CURRENT_LIMITING:{code:509,retryable:!0},MESSAGE_SIZE_LIMIT:{code:510,retryable:!1},GROUP_NOT_JOINED:{code:602,retryable:!1},GROUP_PERMISSION_DENIED:{code:603,retryable:!1},GROUP_NOT_EXIST:{code:606,retryable:!1},GROUP_DISABLED:{code:607,retryable:!1},MESSAGE_BLOCKED:{code:1200,retryable:!1},THIRD_DEFAULT_FAILED:{code:1299,retryable:!1}}},getHistoryMessages:{range:"4,110,202,505",localErrors:{getHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},page_size_exceeded:{code:110,aliases:["pull number cannot be greater","limit is to large"],retryable:!1}}},removeHistoryMessages:{range:"110,112,202,505",localErrors:{removeHistoryMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},query_param_reaches_limit:{code:112,aliases:["delete msg list limit"],retryable:!1}}},getGroupMessageReadUsers:{range:"4,110,500",localErrors:{getGroupMessageReadUsers:{validation_invalid:{code:110,retryable:!1}}},errors:{message_not_found:{code:500,retryable:!1}}},recallMessage:{range:"110,201,300,504,505",localErrors:{recallMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},recall_time_limit:{code:504,retryable:!1},recall_disabled:{code:505,retryable:!1}}},updateMessage:{range:"110,111,201,210,300,511",localErrors:{modifyMessage:{validation_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1}}},errors:{message_invalid:{code:110,retryable:!1},unsupported_type:{code:111,retryable:!1},not_login:{code:201,retryable:!0},permission_denied:{code:210,retryable:!1},not_connected:{code:300,retryable:!0},edit_failed:{code:511,retryable:!0}}},downloadMessageAttachment:{range:"400,401,403,407",localErrors:{downloadAttachment:{validation_invalid:{code:401,retryable:!1}}},errors:{not_found:{code:400,httpStatus:404,retryable:!1},invalid:{code:401,retryable:!1},download_failed:{code:403,retryable:!0},expired:{code:407,httpStatus:404,retryable:!1}}},downloadAndParseCombineMessage:{range:"110,401,403,500",localErrors:{downloadAndParseCombineMessage:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_param:{code:110,retryable:!1},invalid_type:{code:500,retryable:!1},parse_failed:{code:401,retryable:!0},download_failed:{code:403,retryable:!0}}},addReaction:{range:"110,302,505,600,602,1300-1302",localErrors:{addReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{reaction_already_operated:{code:1301,retryable:!1},reaction_reach_limit:{code:1300,retryable:!1},group_not_joined:{code:602,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1},service_not_enabled:{code:505,retryable:!1},server_busy:{code:302,retryable:!0}}},removeReaction:{range:"110,505,1301,1302",localErrors:{removeReaction:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},getReactionList:{range:"110,505,600",localErrors:{getReactionList:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},group_invalid_id:{code:600,retryable:!1}}},getReactionDetail:{range:"110,505,1302",localErrors:{getReactionDetail:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,retryable:!1},reaction_operation_illegal:{code:1302,retryable:!1}}},pinMessage:{range:"4,110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_limit:{code:4,aliases:["91101"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102"],retryable:!1}}},unpinMessage:{range:"110",errors:{pin_msg_id_illegal:{code:110,retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getPinnedMessageList:{range:"110,111",errors:{operation_unsupported:{code:111,aliases:["15002"],retryable:!1},pin_message_not_found:{code:110,aliases:["91102","user session pin message not exist"],retryable:!1}}},getSupportedTranslationLanguages:{range:"505",errors:{service_not_enabled:{code:505,aliases:["service not open!"],retryable:!1}}},translateMessage:{range:"505,1110-1113",localErrors:{translateMessage:{validation_invalid:{code:1110,retryable:!1}}},errors:{translate_text_too_long:{code:1110,runtimeMessage:"Translation text is too long",retryable:!1},translate_param_invalid:{code:1110,runtimeMessage:"Invalid target language",retryable:!1},service_not_enabled:{code:1111,runtimeMessage:"Translation service is not enabled",aliases:["service not open!"],retryable:!1},translate_usage_limit:{code:1112,runtimeMessage:"Translation quota has been reached",aliases:["The request has reached the maximum limit"],retryable:!1},translate_failed:{code:1113,runtimeMessage:"Translation service error",aliases:["The request failed, please try again later."],retryable:!1}}},voiceMessageToText:{range:"4,110,202,407-411,505",localErrors:{voiceMessageToText:{validation_invalid:{code:407,retryable:!1},file_not_found:{code:410,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},file_not_found:{code:410,retryable:!1,aliases:["4041001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},voiceFileToText:{range:"4,110,202,402,407-411,505",localErrors:{voiceFileToText:{validation_invalid:{code:407,retryable:!1},upload_required:{code:110,retryable:!1}}},errors:{unauthorized:{code:202,retryable:!0},upload_failed:{code:402,retryable:!0,aliases:["5021001"]},file_invalid:{code:407,retryable:!1,aliases:["4001002"]},duration_too_long:{code:408,retryable:!1,aliases:["4001003"]},file_too_large:{code:411,retryable:!1,aliases:["4001001"]},service_not_enabled:{code:505,retryable:!1,aliases:["4031001"]},service_limit_exceeded:{code:4,retryable:!0,aliases:["4031002"]},voice_to_text_failed:{code:409,retryable:!0,aliases:["5021003","5001003"]}}},getConversationList:{range:"110",localErrors:{getConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPinnedConversationList:{range:"110",localErrors:{getPinnedConversationList:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getConversationListByMark:{range:"110",localErrors:{getConversationListByMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},deleteConversation:{range:"110",localErrors:{deleteConversation:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearConversationUnreadMessageCount:{range:"110,201,300,500",localErrors:{clearConversationUnreadMessageCount:{validation_invalid:{code:110,retryable:!1}}},errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},clearAllConversationUnreadMessageCount:{range:"201,300,500",errors:{not_login:{code:201,retryable:!0},not_connected:{code:300,retryable:!0},message_invalid:{code:500,retryable:!1}}},sendMessageReadReceipts:{range:"110,300",localErrors:{sendMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{invalid_direction:{code:110,retryable:!1},not_connected:{code:300,retryable:!0}}},getGroupMessageReadReceipts:{range:"110,202,210,303",localErrors:{getGroupMessageReadReceipts:{validation_invalid:{code:110,retryable:!1}}},errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},auth_bad_access_token:{code:202,httpStatus:401,retryable:!1},forbidden_op:{code:210,httpStatus:403,retryable:!1},unknown_exception_error:{code:303,httpStatus:500,retryable:!0}}},setConversationPinned:{range:"110",localErrors:{setConversationPinned:{validation_invalid:{code:110,retryable:!1}}},errors:{}},addConversationMark:{range:"110",localErrors:{addConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},removeConversationMark:{range:"110",localErrors:{removeConversationMark:{validation_invalid:{code:110,retryable:!1}}},errors:{}},clearAllMessagesAndConversations:{range:"",errors:{}},searchMessages:{range:"110,202,303,505",localErrors:{searchMessages:{validation_invalid:{code:110,retryable:!1}}},errors:{parameter_error:{code:110,httpStatus:400,retryable:!1,aliases:["4000005","4000006"]},token_invalid:{code:202,httpStatus:401,retryable:!1,aliases:["4010101"]},service_not_enabled:{code:505,httpStatus:403,retryable:!1,aliases:["4030204"]},app_not_found:{code:110,httpStatus:404,retryable:!1,aliases:["4040302"]},server_error:{code:303,httpStatus:500,retryable:!0,aliases:["5000701","5020801"]}}}}},wI=async(e,t)=>{if("text"!==e.type)return e;const r=e.body;if(void 0===r.targetLanguages)return e;if(!Array.isArray(r.targetLanguages)||r.targetLanguages.some(e=>"string"!=typeof e||!e.trim())||"string"!=typeof r.content||!r.content.trim())throw new mt("invalid text translation parameters",{code:ot.TRANSLATE_PARAM_INVALID});if(0===r.targetLanguages.length)return e;const s=[...new Set(r.targetLanguages)],n={...e,sender:{...e.sender},body:{...r,targetLanguages:s,translations:r.translations?{...r.translations}:void 0}},i=n.body,o=await t({text:i.content.trim(),targetLanguages:s}),a=Object.fromEntries(o.translations.map(e=>[e.to,e.text]));if(s.some(e=>"string"!=typeof a[e]||!a[e]))throw new ut("Translation response is missing requested languages",ot.TRANSLATE_FAILED);return i.translations={...i.translations,...a},n},AI=(...e)=>{const t={},r={};for(const s of e)Object.assign(t,s.common),Object.assign(r,s.apis);return{common:t,apis:r}},RI={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:{}},NI=e=>({userId:e}),OI=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),MI=e=>e,UI=async(e,t)=>{const r=(e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,OI(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,MI(t))}for(const o of r)s.has(o)||s.set(o,NI(o));return s};class LI{constructor(e){this.options=e,this.pendingGroups=new Map,this.readyGroups=[],this.pendingOrder=[],this.activeGroups=new Set,this.timer=null,this.activeGroupCount=0}enqueue(e,t,r){if(!e||!t)return;const s=this.pendingGroups.get(e)??new Map;this.pendingGroups.has(e)||(this.pendingGroups.set(e,s),this.pendingOrder.push(e));const n=s.get(t);s.set(t,{userId:t,namecardUpdateTime:this.resolveMaxVersion(n?.namecardUpdateTime,r)}),this.schedule()}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingGroups.clear(),this.pendingOrder.length=0,this.readyGroups.length=0,this.activeGroups.clear(),this.activeGroupCount=0}getOptions(){return{windowMs:this.options.windowMs,minWindowMs:this.options.minWindowMs,maxBatchSize:this.options.maxBatchSize,maxConcurrency:this.options.maxConcurrency}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flushWindow()},this.resolveWindowDelay()))}flushWindow(){if(0!==this.pendingOrder.length){for(const e of this.pendingOrder){const t=this.pendingGroups.get(e);if(!t||0===t.size)continue;const r=Array.from(t.values()),s=Math.max(1,this.options.maxBatchSize);for(let n=0;n<r.length;n+=s)this.readyGroups.push({groupId:e,targets:r.slice(n,n+s)})}this.pendingGroups.clear(),this.pendingOrder.length=0,this.runReadyGroups()}}runReadyGroups(){for(;this.activeGroupCount<this.options.maxConcurrency&&this.readyGroups.length>0;){const e=this.readyGroups.findIndex(e=>!this.activeGroups.has(e.groupId));if(e<0)return;const t=this.readyGroups.splice(e,1)[0];if(!t)return;this.activeGroupCount+=1,this.activeGroups.add(t.groupId),Promise.resolve(this.options.onFlushGroup(t)).catch(e=>{Ks("Group namecard hydration queue flush failed",{groupId:t.groupId,userIds:t.targets.map(e=>e.userId),error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.activeGroupCount-=1,this.activeGroups.delete(t.groupId),this.runReadyGroups()})}}resolveWindowDelay(){const e=Math.max(0,Math.min(this.options.minWindowMs,this.options.windowMs)),t=Math.max(e,this.options.windowMs),r=t-e;return r<=0?t:e+Math.floor(Math.random()*(r+1))}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class kI{constructor(e){this.options=e,this.pendingTargets=new Map,this.readyBatches=[],this.timer=null,this.activeCount=0,this.generation=0}enqueue(e,t){e&&(this.mergeWaitingTarget({userId:e,userInfoUpdateTime:t,retryCount:0}),this.pendingTargets.size>=this.options.batchSize?this.flush():this.schedule())}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingTargets.clear(),this.readyBatches.length=0,this.generation+=1}getOptions(){return{windowMs:this.options.windowMs,batchSize:this.options.batchSize,maxConcurrency:this.options.maxConcurrency,maxRetries:this.options.maxRetries}}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.options.windowMs))}flush(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),0===this.pendingTargets.size)return;const e=Array.from(this.pendingTargets.values());this.pendingTargets.clear();const t=Math.max(1,this.options.batchSize);for(let r=0;r<e.length;r+=t)this.readyBatches.push(e.slice(r,r+t));this.runReadyBatches()}runReadyBatches(){const e=Math.max(1,this.options.maxConcurrency);for(;this.activeCount<e&&this.readyBatches.length>0;){const e=this.readyBatches.shift();if(!e)return;const r=this.generation;this.activeCount+=1;const s=e.map(({userId:e,userInfoUpdateTime:t})=>({userId:e,userInfoUpdateTime:t}));let n;try{n=Promise.resolve(this.options.onFlush(s))}catch(t){n=Promise.reject(t instanceof Error?t:new Error(String(t)))}n.catch(t=>{const s=e.filter(e=>e.retryCount<Math.max(0,this.options.maxRetries)).map(e=>({...e,retryCount:e.retryCount+1}));if(Ks("User info hydration queue flush failed",{targets:e.map(e=>e.userId),retrying:s.length>0,error:t instanceof Error?t.message:String(t)}),r===this.generation&&0!==s.length){for(const e of s)this.mergeWaitingTarget(e);this.flush()}}).finally(()=>{this.activeCount-=1,this.runReadyBatches()})}}mergeWaitingTarget(e){for(const r of this.readyBatches){const t=r.findIndex(t=>t.userId===e.userId);if(t>=0){const s=r[t];return void(s&&(r[t]=this.mergeTarget(s,e)))}}const t=this.pendingTargets.get(e.userId);this.pendingTargets.set(e.userId,t?this.mergeTarget(t,e):e)}mergeTarget(e,t){return{userId:e.userId,userInfoUpdateTime:this.resolveMaxVersion(e.userInfoUpdateTime,t.userInfoUpdateTime),retryCount:Math.max(e.retryCount,t.retryCount)}}resolveMaxVersion(e,t){return"number"!=typeof e?t:"number"!=typeof t?e:Math.max(e,t)}}class DI{constructor(e,t,r=Date.now){this.attemptId=e,this.timeoutMs=t,this.now=r,this.timeoutId=null,this.status="active",this.expiresAt=this.now()+t,this.timeoutPromise=new Promise((e,r)=>{this.timeoutId=setTimeout(()=>{"active"===this.status&&(this.status="expired",this.timeoutId=null,r(this.createTimeoutError()))},t)}),this.timeoutPromise.catch(()=>{})}getStatus(){return this.status}remainingMs(){return"expired"===this.status?0:Math.max(0,this.expiresAt-this.now())}clamp(e){return Math.max(0,Math.min(e,this.remainingMs()))}race(e){return"expired"===this.status||0===this.remainingMs()?(e.catch(()=>{}),this.expire(),Promise.reject(this.createTimeoutError())):"active"!==this.status?e:Promise.race([e,this.timeoutPromise])}markProvisionReceived(){return"active"===this.status&&(this.status="provision-received",this.clearTimer(),!0)}expire(){"active"===this.status&&(this.status="expired",this.clearTimer())}dispose(){"active"===this.status&&(this.status="disposed"),this.clearTimer()}createTimeoutError(){return new ht("Login timeout",{code:ot.CONNECTION_LOGIN_TIMEOUT,details:{stage:"login",timeoutMs:this.timeoutMs,attemptId:this.attemptId,retryable:!0}})}clearTimer(){null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}}const PI=0,xI=1,FI=2,BI=3,GI=4,qI=5,$I=0,jI=0,VI=1,KI=1001,zI=1002,HI=1003,WI=1004,JI=1005,QI=1101,ZI=AI(RI,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),YI=class e{constructor(e){this.core=null,this.cacheManager=null,this.cacheUserId=null,this.state=t,this.loginAttempt=0,this.currentUserId=null,this.activeAppKey=null,this.logReportEnabled=!1,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.contactSyncController=null,this.groupSyncController=null,this.syncConversationListConfigController=null,this.syncWebSocketSession=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.conversationListVersion=0,this.conversationListSnapshot=[],this.activeIncomingStreamMessageIds=new Set,this.managerSessionGeneration=0,this.activeManagerSessionContext=null,this.managerSessionEndingPromise=null,this.postLoginTaskContext=null,this.terminalSessionCleanupTask=null,this.config={appKey:e.appKey,appId:e.appId,enableUserInfoSync:e.enableUserInfoSync,enableSyncData:[...e.enableSyncData],enableDeliveryReceipt:e.enableDeliveryReceipt,deleteConversationOnGroupDestroyed:e.deleteConversationOnGroupDestroyed,syncConversationListConfig:{...e.syncConversationListConfig},useCustomAttachmentUpload:e.useCustomAttachmentUpload,enableMd5Check:e.enableMd5Check,serviceConfig:{mode:e.serviceConfig.mode,dnsConfigUrls:[...e.serviceConfig.dnsConfigUrls],hasCustomDnsConfigUrls:e.serviceConfig.hasCustomDnsConfigUrls,serverUrls:e.serviceConfig.serverUrls},useFixedDeviceId:e.useFixedDeviceId,deviceId:e.deviceId,useReplacedMessageContents:e.useReplacedMessageContents,customDeviceName:e.customDeviceName,customOSPlatform:e.customOSPlatform,uiKitVersion:e.uiKitVersion,loginExtensionInfo:e.loginExtensionInfo,cacheEncryptionMode:e.cacheEncryptionMode,profileSync:{...e.profileSync},platformAdapterOptions:e.platformAdapterOptions},this.activeAppKey=this.config.appKey??null,this.config.platformAdapterOptions&&(this.platformAdapter=xd(this.config.platformAdapterOptions)),this.managerRegistry=new Map,this.managerCapabilities=new Map,this.eventHub=new yy,Ds=e=>{this.eventHub.dispatch(V.LOG,e)},this.managerEventContext={addEventHandler:(e,t)=>{this.eventHub.addEventHandler(e,t)},removeEventHandler:e=>{this.eventHub.removeEventHandler(e)},dispatch:(e,t)=>{this.eventHub.dispatch(e,t)}},this.userInfoHydrationQueue=new kI({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:3,maxRetries:1,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new LI({windowMs:this.config.profileSync.groupNamecardWindowMs,minWindowMs:1e3,maxBatchSize:50,maxConcurrency:this.config.profileSync.groupNamecardMaxConcurrency,onFlushGroup:async e=>{await this.flushGroupNamecardHydrationBatch(e)}}),this.eventHub.addEventHandler("__internal:chat-client",{[o]:e=>{this.updateState(e.state)},[a]:e=>{this.updateState(e.state)},[c]:e=>{this.updateState(e.state),this.isTerminalManagerSessionDisconnect(e)&&this.startTerminalSessionCleanup(e)},[d]:e=>{this.updateState(e.state)},[M]:e=>{this.handleIncomingConversationMessage(e),this.handleIncomingMessageProfileSync(e)},[x]:e=>{this.patchConversationLastMessage(e,{...e.message,body:{...e.message.body}})},[k]:e=>{const t=e.flatMap(e=>"singleChat"===e.conversationType?e.messageIds.map(t=>({conversationId:e.conversationId,conversationType:e.conversationType,messageId:t,patch:{isPeerRead:!0}})):e.receiptDetails.map(t=>({conversationId:e.conversationId,conversationType:e.conversationType,messageId:t.messageId,patch:{groupReadCount:t.count}})));this.cacheManager?.patchConversationLastMessages(t)&&this.emitConversationListUpdate("message")},[F]:e=>{this.patchConversationLastMessage(e,{reactions:[...e.reactions]})},[U]:e=>{this.handleIncomingConversationStreamMessage(e)},[I]:e=>{this.handleOutgoingConversationMessage(e)},[G]:e=>{this.handleMultiDeviceContactEvent(e)},[q]:e=>{if("CONVERSATION_DELETED"===e.operation)return this.handleMultiDeviceConversationEvent(e)},[W]:e=>this.handleIncomingContactRosterEvent("add",e),[Q]:e=>this.handleIncomingContactRosterEvent("add",e),[z]:e=>this.handleIncomingContactRosterEvent("none",e),[J]:e=>this.handleIncomingContactRosterEvent("none",e),[H]:e=>this.handleIncomingContactRosterEvent("remove",e),[g]:async e=>{await this.dispatchRawNotifyToCapability("rawNotify:group",{type:"group",payload:e}),e.eventName===ie&&await this.handleGroupDestroyedConversation(e.payload.groupId)},[f]:e=>this.dispatchRawNotifyToCapability("rawNotify:chatroom",{type:"chatroom",payload:e}),[y]:e=>{const t=((e,t,r,s=!1)=>{const n=t.find(t=>"groupChat"===t.conversationType&&t.conversationId===e.muc_parent_id&&t.lastMessage&&(e.msg_parent_id?t.lastMessage.msgServerId===e.msg_parent_id:t.lastMessage.chatThreadOverview?.chatThreadId===e.id)),i=n?.lastMessage;if(!n||!i||!e.id)return null;const o={conversationId:n.conversationId,conversationType:"groupChat",messageId:i.msgServerId};if("delete"===e.operation)return i.chatThreadOverview?.chatThreadId===e.id?{...o,patch:{chatThreadOverview:void 0}}:null;if(!["create","update","update_msg"].includes(e.operation))return null;const a=new vu(r,s).resolveChatThreadOverview({thread_overview:{id:e.id,muc_parent_id:e.muc_parent_id,name:e.name,message_count:e.message_count,update_timestamp:e.timestamp,last_message:e.last_message}});return a?(Object.prototype.hasOwnProperty.call(e,"last_message")||Reflect.deleteProperty(a,"lastMessage"),{...o,patch:{chatThreadOverview:{...i.chatThreadOverview?.chatThreadId===e.id?i.chatThreadOverview:{},...a}}}):null})(e.payload,this.cacheManager?.loadSessionList()??[],this.getCurrentUserId()??"",this.config.useCustomAttachmentUpload);return t&&this.patchConversationLastMessage(t,t.patch),this.dispatchRawNotifyToCapability("rawNotify:chatThread",{type:"chatThread",payload:e})},[v]:e=>this.dispatchRawNotifyToCapability("rawNotify:userInfo",{type:"userInfo",payload:e})})}static init(t){const r=Ev.validateOrThrow(Av,t),s=r.customOSPlatform,n=e.normalizeServiceConfig(r.serviceConfig),i={appKey:r.appKey,appId:r.appId,enableUserInfoSync:r.enableUserInfoSync??!1,enableSyncData:e.normalizeSyncDataTypes(r.enableSyncData??["conversation"]),enableDeliveryReceipt:r.enableDeliveryReceipt??!1,deleteConversationOnGroupDestroyed:r.deleteConversationOnGroupDestroyed??!0,syncConversationListConfig:{includeEmpty:r.syncConversationListConfig?.includeEmpty??!1,includeMark:!0},useCustomAttachmentUpload:r.useCustomAttachmentUpload??!1,enableMd5Check:!1,serviceConfig:n,useFixedDeviceId:r.useFixedDeviceId??!0,deviceId:r.deviceId??"webim",useReplacedMessageContents:r.useReplacedMessageContents??!1,customDeviceName:void 0!==s?r.customDeviceName:void 0,customOSPlatform:s,uiKitVersion:r.uiKitVersion,loginExtensionInfo:r.loginExtensionInfo,cacheEncryptionMode:"auto",profileSync:{userInfoWindowMs:7e3,userInfoBatchSize:20,groupNamecardWindowMs:7e3,groupNamecardMaxConcurrency:5},platformAdapterOptions:r.platformAdapterOptions},o=t.managers??[];if(e.instance){if(!e.isSameConfig(e.instance.config,i))throw new mt("ChatClient already initialized with different config",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"config",message:"ChatClient already initialized with different config",rule:"conflict"}],current:e.instance.config,next:i}});return o.length>0&&e.instance.registerManagers(o),e.instance.validateOptionalCapabilityDependencies(),e.instance}return e.instance=new e(i),o.length>0&&e.instance.registerManagers(o),e.instance.validateOptionalCapabilityDependencies(),e.instance}async login(n,i){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});const o=Ev.validateOrThrow(Nv,n),a=Ev.validateOrThrow(Ov,i??{});if(await this.waitForTerminalSessionCleanup(),this.state===r||this.state===s){const e=this.currentUserId&&this.currentUserId!==o.userId;throw new ht(e?"Another user is already logged in":"ChatClient is already connecting or connected",{code:e?ot.USER_ALREADY_LOGIN_ANOTHER:ot.AUTH_ALREADY_LOGIN,details:{stage:"auth",...e?{currentUserId:this.currentUserId,nextUserId:o.userId}:{}}})}const c=++this.loginAttempt,d=new DI(c,a.timeoutMs??3e4);try{let e=this.config.appKey??null;this.activeAppKey=e,Ks("Login started",{userId:o.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const s=this.platformAdapter??xd(this.config.platformAdapterOptions);this.platformAdapter=s,(e=>{Hh?.reset(),Hh=new zh(e)})({requestAdapter:s.request,onDiagnostic:(e,t)=>{Ks(e,t)}});const n=(e=>Hh?.startSession(e))({appKey:e??"default#appkey",uid:o.userId,sdkVersion:Fv,platform:s.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),i=s.runtime.getNetworkType?.();i&&i.then(e=>{Qh(e)}).catch(()=>{Qh("unknown")});const a=Zh({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:o.userId});let h,p,m;this.updateState(r),this.logReportEnabled=!1,Gs("unknown");let g,f=!1,y=!1,v=!0;if("dns"===this.config.serviceConfig.mode){const r=a?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const t=await d.race(Qv(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:s.request,loginDeadline:d}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:s.request,loginDeadline:d}));e=t.appKey,this.activeAppKey=e,Wh({appKey:e}),Ks("DNS resolved for login",{baseUrl:t.baseUrl,websocketUrl:t.websocketUrl,restBaseUrl:t.restBaseUrl,syncWebSocketSource:"rest"}),h=t.websocketUrl,p=t.websocketUrls;const n=Zv(t.restBaseUrl);this.contactSyncWsUrls=[n],this.syncConversationListConfigWsUrls=[n],this.contactSyncDnsResolved=!0,m=t.restBaseUrl,f="true"===t.dnsConfig.enableReportLogs,g=t.dnsConfig.reportInterval,y="true"===t.dnsConfig.enableMd5Check,v="false"!==t.dnsConfig.uploadinparts_enable,r?.finish({code:200,success:!0}),Jh(t.dnsConfig.enableDataReport),Vs("DNS report switch resolved",{enabled:f})}catch(l){const e=l instanceof ut?l.code:-1,s=l instanceof Error?l.message:String(l);throw r?.finish({code:e,success:!1,description:s}),a?.finish({code:e,success:!1,description:s}),Jh(void 0),Gs("disabled"),this.activeAppKey=this.config.appKey??null,this.updateState(t),d.dispose(),l}}else{const e=this.config.serviceConfig.serverUrls;if(!e?.wsUrl||!e.restApiUrl){const e=new mt("serviceConfig.serverUrls.restApiUrl and serviceConfig.serverUrls.wsUrl are required when serverUrls is configured",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"serviceConfig.serverUrls.restApiUrl",message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured",rule:"required"},{path:"serviceConfig.serverUrls.wsUrl",message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured",rule:"required"}]}});throw a?.finish({code:e.code,success:!1,description:e.message}),Jh(void 0),this.updateState(t),d.dispose(),e}h=e.wsUrl,m=e.restApiUrl;const r=Zv(m);y=this.config.enableMd5Check,this.contactSyncWsUrls=[r],this.syncConversationListConfigWsUrls=[r],this.contactSyncDnsResolved=!1,Jh(void 0)}if(!e){const e=new mt("appKey is unavailable after service discovery",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable after service discovery",rule:"required"}]}});throw this.updateState(t),Yh(),d.dispose(),e}qs({restBaseUrl:m,appKey:e,userId:o.userId,token:o.token,requestAdapter:s.request}),u=g,Rs.updateReportInterval(u),this.logReportEnabled=f,Gs(f?"enabled":"disabled");const I=this.resetCore();if(I?.(),c!==this.loginAttempt){const e=new ht("Login cancelled",{code:ot.CONNECTION_CANCELLED,details:{stage:"auth"}});throw a?.finish({code:ot.CONNECTION_CANCELLED,success:!1,description:e.message}),this.updateState(t),this.activeAppKey=this.config.appKey??null,Yh(),d.dispose(),e}const b=new mm({serverUrl:h,serverUrls:p,userId:o.userId,token:o.token,appKey:e,restBaseUrl:m,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:y,enableMultipartUpload:v,useFixedDeviceId:this.config.useFixedDeviceId,deviceId:this.config.deviceId,customDeviceName:this.config.customDeviceName,customOSPlatform:this.config.customOSPlatform,uiKitVersion:this.config.uiKitVersion,loginExtensionInfo:this.config.loginExtensionInfo,serviceId:n,platformAdapter:s,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub);this.core=b,qs({resource:b.getClientResource()});const _=a?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:h});try{Ks("Connecting core websocket",{serverUrl:h,restBaseUrl:m,userId:o.userId});try{await d.race(b.connect(d))}finally{d.dispose()}this.throwIfLoginSessionCancelled(c,b),_?.finish({code:200,success:!0}),a?.finish({code:0,success:!0}),Ks("Core websocket connected",{userId:o.userId,resource:b.getClientResource()}),this.currentUserId=o.userId,Wh({uid:o.userId}),this.restBaseUrl=m??null,this.authToken=o.token,this.clientResource=b.getClientResource(),await this.initCacheManager(o.userId),this.throwIfLoginSessionCancelled(c,b),Ks("Cache initialized after login",{userId:o.userId}),this.loadCachedConversations(),this.loadCachedUserInfo(),this.notifyManagersSessionReady(o.userId,this.clientResource),this.startPostLoginTasks(o.userId,c)}catch(l){const e=l instanceof ut?l.code:-1,r=l instanceof Error?l.message:String(l);if(_?.finish({code:e,success:!1,description:r}),a?.finish({code:e,success:!1,description:r}),this.core===b){const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(t),Yh()}finally{e?.()}}throw l}}finally{d.dispose()}var u}startPostLoginTasks(e,t){this.cancelPostLoginTasks();const r={attemptId:t,userId:e,cancelled:!1};this.postLoginTaskContext=r,this.runPostLoginTasks(r).catch(e=>{this.isPostLoginTaskActive(r)&&Ks("Unexpected post-login task failure",{userId:r.userId,reason:e instanceof Error?e.message:String(e)})}).finally(()=>{this.postLoginTaskContext===r&&(this.postLoginTaskContext=null)})}cancelPostLoginTasks(){this.postLoginTaskContext&&(this.postLoginTaskContext.cancelled=!0,this.postLoginTaskContext=null)}isPostLoginTaskActive(e){return!e.cancelled&&this.postLoginTaskContext===e&&e.attemptId===this.loginAttempt&&this.currentUserId===e.userId}async runPostLoginTasks(e){if(!this.isPostLoginTaskActive(e))return;if(await this.runPostLoginTask(e,"self-user-info",async()=>{await this.syncSelfUserInfoAfterLogin()}),!this.isPostLoginTaskActive(e))return;if(this.config.enableSyncData.includes("conversation")&&await this.runPostLoginTask(e,"conversation",async()=>{await this.refreshSessionList(this.config.syncConversationListConfig)}),!this.isPostLoginTaskActive(e))return;const t=this.triggerConfiguredSyncDataAfterLogin(e.userId,e),r=this.logReportEnabled?this.runPostLoginTask(e,"log-report",async()=>{await $s()}):Promise.resolve();await Promise.all([t,r])}async runPostLoginTask(e,t,r){if(this.isPostLoginTaskActive(e))try{await r()}catch(s){if(!this.isPostLoginTaskActive(e))return;Ks("Post-login synchronization step failed",{userId:e.userId,task:t,reason:s instanceof Error?s.message:String(s)})}}async logout(){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});for(this.loginAttempt+=1,this.cancelPostLoginTasks();this.terminalSessionCleanupTask;)await this.terminalSessionCleanupTask;if(this.loginAttempt+=1,this.cancelPostLoginTasks(),await this.notifyManagersSessionEnding("logout"),!this.core){const e=this.detachSessionListSyncController();try{this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("logout"),this.syncWebSocketSession=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.resetManagerSessionRuntimes(),Gs("disabled"),js(),Yh()}finally{this.contactSyncController=null,this.groupSyncController=null,this.syncWebSocketSession=null,this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1,this.activeAppKey=this.config.appKey??null,this.updateState(t),this.logReportEnabled=!1,e?.()}return}try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await $s()}catch(r){Ks("Report logs on logout failed",r)}await this.core.disconnect()}finally{const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(t),this.logReportEnabled=!1,Gs("disabled"),js(),Yh()}finally{e?.()}}}getConnectionState(){return this.state}getVersion(){return Fv}getCurrentUserId(){return this.currentUserId}getClientResource(){return this.clientResource??this.core?.getClientResource()??null}getMessageCreationOptions(){return{useCustomAttachmentUpload:this.config.useCustomAttachmentUpload}}getRestContext(){if(!this.restBaseUrl)throw new mt("restBaseUrl is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"restBaseUrl",message:"restBaseUrl is required",rule:"required"}]}});if(!this.authToken)throw new mt("token is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}});if(!this.currentUserId)throw new mt("userId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"userId",message:"userId is required",rule:"required"}]}});const e=this.clientResource??this.core?.getClientResource();if(!e)throw new mt("clientResource is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"clientResource",message:"clientResource is required",rule:"required"}]}});return{restBaseUrl:this.restBaseUrl,appKey:this.requireActiveAppKey(),userId:this.currentUserId,token:this.authToken,clientResource:e}}async renewToken(e){const t=Ev.validateOrThrow(Mv,e);if(!this.core||!this.currentUserId||this.state!==s)throw new ht("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN,details:{stage:"token",state:this.state}});const r=this.getRestContext(),n={...r},i=new Cv(n.restBaseUrl,{errorMap:ZI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});i.setAuthToken(t),Ks("Renew token started",{userId:r.userId});const o=await sI(i,n);if(o<=Date.now())throw new ht("Token is expired",{code:ot.AUTH_TOKEN_EXPIRED,details:{stage:"token"}});const a=this.core.renewToken(t,o);return this.authToken=t,qs({token:t}),Ks("Renew token succeeded",{userId:r.userId,expireAt:o}),a}async getRTCTokenInfo(e){const t=Ev.validateOrThrow(Uv,e),r=this.getRestContext(),s=new Cv(r.restBaseUrl,{errorMap:ZI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),Ks("Get RTC token info started",{userId:r.userId,hasChannelName:Boolean(t?.channelName)}),nI(s,r,t)}async getUserIdsWithRTCUids(e){const t=Ev.validateOrThrow(Lv,e),r=this.getRestContext(),s=new Cv(r.restBaseUrl,{errorMap:ZI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),Ks("Get userIds with RTC UIDs started",{userId:r.userId,count:t.length}),iI(s,r,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new Cv(e.restBaseUrl,{errorMap:ZI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return t.setAuthToken(e.token),Ks("Get self ids on other platform started",{userId:e.userId,clientResource:e.clientResource}),oI(t,e)}getCacheManager(){return this.cacheManager}getManagerByCapability(e){return this.managerCapabilities.get(e)}getUploadAdapter(){return this.platformAdapter?.upload??null}getRequestAdapter(){return this.platformAdapter?.request}addInternalEvent(e,t){this.eventHub.dispatch(e,t)}refreshSessionList(e){return this.cacheManager&&this.currentUserId?this.ensureSessionListSyncController().refresh({includeEmpty:e?.includeEmpty??this.config.syncConversationListConfig.includeEmpty,includeMark:!0}).then(e=>(this.enqueueMissingGroupSessionSenderUserInfos(e),e.map(e=>({...e})))):Promise.resolve([])}getServerUrlsConfig(){return this.config.serviceConfig.serverUrls}getSessionListSyncWsUrls(){return this.buildAuthenticatedSessionListSyncUrls(this.syncConversationListConfigWsUrls)}hasSessionListSyncWsUrl(){return this.syncConversationListConfigWsUrls.length>0}getSharedSyncWebSocketSession(){return this.syncWebSocketSession||(this.syncWebSocketSession=new yv({socketAdapter:this.platformAdapter?.socket,getUrls:async()=>{const e=this.getSessionListSyncWsUrls();return e.length>0?e:await this.resolveContactSyncUrls()}})),this.syncWebSocketSession}isSessionListDnsProbeAvailable(){return"dns"===this.config.serviceConfig.mode}getSessionListSyncCapabilityState(){return this.syncConversationListConfigController?.getCapabilityState()??null}markConversationAccess(e){this.cacheManager?.markConversationAccess(e)}patchConversationLastMessage(e,t){const r=this.cacheManager?.patchConversationLastMessages([{...e,patch:t}]);r&&this.emitConversationListUpdate("message")}handleIncomingConversationMessage(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}handleIncomingConversationStreamMessage(e){if(!this.cacheManager)return;const t=e.msgServerId||e.msgLocalId,r=e.stream.status===nt.START_COMPLETED||e.stream.status===nt.FULL||e.stream.status===nt.COMPLETED||e.stream.status===nt.ERROR;if(!this.activeIncomingStreamMessageIds.has(t))return this.applyIncomingConversationMessagePatch(e),void(r||this.activeIncomingStreamMessageIds.add(t));if(!r)return;this.activeIncomingStreamMessageIds.delete(t);this.cacheManager.loadSessionList().some(e=>e.lastMessage?.msgServerId===t)&&this.applyIncomingConversationMessagePatch(e)}applyIncomingConversationMessagePatch(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}handleOutgoingConversationMessage(e){if(!this.cacheManager)return;this.cacheManager.applyIncomingMessageToConversations(e);this.cacheManager.applyIncomingMessageToSessionList(e).changed&&this.emitConversationListUpdate("message")}async handleMultiDeviceConversationEvent(e){if("CONVERSATION_DELETED"!==e.operation||!this.cacheManager)return;this.cacheManager.deleteConversation({conversationId:e.conversationId,type:e.conversationType??"singleChat",deletedAt:e.timestamp??Date.now()}).changed&&(await this.cacheManager.flushPending(),this.emitConversationListUpdate("local"))}async handleGroupDestroyedConversation(e){if(!this.config.deleteConversationOnGroupDestroyed||!this.cacheManager)return;this.cacheManager.deleteConversation({conversationId:e,type:"groupChat",deletedAt:Date.now()}).changed&&(await this.cacheManager.flushPending(),this.emitConversationListUpdate("local"))}handleMultiDeviceContactEvent(e){if("CONTACT_REMOVE"!==e.operation||!this.cacheManager)return;this.cacheManager.applyContactRosterNotice({action:"remove",userId:e.targetUserId,rosterVersion:e.rosterVersion}).changed&&this.cacheManager.flushPending()}getContactSnapshot(){return this.cacheManager?this.cacheManager.loadContactSnapshot("cache"):null}handleIncomingContactRosterEvent(e,t){const r=this.resolveContactRosterTargetUserId(t);if(r)return this.cacheManager&&this.currentUserId&&"none"!==e&&this.cacheManager.applyContactRosterNotice({action:e,userId:r,rosterVersion:fl(t)}),this.hydrateContactRosterPayload(t,r,"remove"!==e)}resolveContactRosterTargetUserId(e){const t=this.currentUserId;return t?e.from===t&&e.to!==t?e.to:e.to===t&&e.from!==t||e.from&&e.from!==t?e.from:e.to&&e.to!==t?e.to:null:null}async hydrateContactRosterPayload(e,t,r){const s=await(async(e,t)=>((e,t,r)=>({userId:r,nickname:t?.nickname??e?.nickname,avatarUrl:t?.avatarUrl??e?.avatarUrl,mail:t?.mail??e?.mail,phone:t?.phone??e?.phone,gender:t?.gender??e?.gender,sign:t?.sign??e?.sign,birth:t?.birth??e?.birth,ext:t?.ext??e?.ext}))(void 0,(await UI([e],t)).get(e),e))(t,{cacheManager:this.cacheManager,fetchUserInfos:r?async({userIds:e})=>await this.fetchContactEventUserInfos(e):void 0});e.userInfo=s}async fetchContactEventUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoReadCapability();if(!t)return[];try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Ks("Contact roster event user info fetch failed",{userIds:e,error:r}),[]}}isMessageProfileSyncEnabled(){return this.config.enableUserInfoSync}isUserInfoSyncEnabled(){return this.config.enableUserInfoSync}async syncSelfUserInfoAfterLogin(){if(!this.isMessageProfileSyncEnabled()||!this.currentUserId)return;const e=this.getUserInfoReadCapability();if(e)try{0===(await e.getUserInfoByUserId({userIds:[this.currentUserId]})).length&&Ks("Self user info sync returned empty result after login",{userId:this.currentUserId})}catch(t){Ks("Self user info sync failed after login",{userId:this.currentUserId,error:t})}}handleIncomingMessageProfileSync(e){if("RECEIVE"!==e.direct||!this.isMessageProfileSyncEnabled())return;const t=pl(e),r=e.sender.userId;if(!r||!this.cacheManager)return;const s=this.cacheManager.getUserInfoSummaries([r],!1)[0];if(s&&(e.sender={userId:r,nickname:s.nickname??e.sender.nickname,avatarUrl:s.avatarUrl??e.sender.avatarUrl}),"number"==typeof t?.userInfoUpdateTime?this.shouldHydrateUserInfo(s?.userInfoUpdateTime,t.userInfoUpdateTime)&&this.userInfoHydrationQueue.enqueue(r,t.userInfoUpdateTime):s||this.userInfoHydrationQueue.enqueue(r),"groupChat"!==e.conversationType)return;const n=this.cacheManager.getGroupNamecard(e.conversationId,r,!1);"number"==typeof t?.namecardUpdateTime?this.shouldHydrateGroupNamecard(n?.namecardUpdateTime,t.namecardUpdateTime)&&this.groupNamecardHydrationQueue.enqueue(e.conversationId,r,t.namecardUpdateTime):n||this.groupNamecardHydrationQueue.enqueue(e.conversationId,r)}attachOutgoingMessageProfileVersions(e){if(!this.isMessageProfileSyncEnabled())return void(e=>{ll.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};hl(e,t)}resolveCurrentUserInfoUpdateTime(){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getUserInfoSummaries([this.currentUserId],!1)[0]?.userInfoUpdateTime}resolveCurrentGroupNamecardUpdateTime(e){if(this.cacheManager&&this.currentUserId)return this.cacheManager.getGroupNamecard(e,this.currentUserId,!1)?.namecardUpdateTime}shouldHydrateUserInfo(e,t){return"number"!=typeof e||e<t}shouldHydrateGroupNamecard(e,t){return"number"!=typeof e||e<t}async flushUserInfoHydrationTargets(e){const t=this.getUserInfoReadCapability();if(!t||0===e.length)return;const r=e.map(e=>e.userId);let s;try{s=await t.getUserInfoByUserId({userIds:r})}catch(d){throw Ks("User info hydration failed",{userIds:r,error:d}),d}const n=this.currentUserId,i=n?s.find(e=>e.userId===n):void 0,o=s.filter(e=>e.userId!==n);i&&this.dispatchOwnInfoUpdated(i),o.length>0&&this.dispatchUserInfoUpdated(o),s.length>0&&this.refreshConversationDisplayFromUserInfos(s.map(e=>({userId:e.userId})),"profile");const a=new Set(s.map(e=>e.userId)),c=r.filter(e=>!a.has(e));c.length>0&&Ks("User info hydration returned partial result",{requestedUserIds:r,missingUserIds:c})}async flushGroupNamecardHydrationBatch(e){const t=this.getGroupNamecardHydrationCapability();if(t&&0!==e.targets.length)try{await t.hydrateMessageProfileGroupNamecards(e.groupId,e.targets)}catch(r){Ks("Group namecard hydration returned partial result",{groupId:e.groupId,requestedUserIds:e.targets.map(e=>e.userId),error:r})}}async refreshContactSnapshot(){if(!this.cacheManager||!this.currentUserId)return;const e=this.ensureContactSyncController();await e.sync()}addEventHandler(e,t){this.eventHub.addEventHandler(e,t)}removeEventHandler(e){this.eventHub.removeEventHandler(e)}use(t){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});return this.registerManagerConstructor(t),this}async sendMessage(t,r){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!t?.sender?.userId)throw new mt("sender.userId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});if(this.currentUserId&&t.sender.userId!==this.currentUserId)throw new mt("sender.userId does not match current user",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"sender.userId",message:"sender.userId does not match current user",rule:"conflict"}]}});if(it(t))throw new gt("Stream message send is not supported",{code:ot.STREAM_SEND_NOT_SUPPORTED,details:{msgLocalId:t.msgLocalId,retryable:!1}});if(this.core&&this.state!==s&&await this.waitForSendConnectionRecovery(this.core),!this.core||this.state!==s)throw new gt("ChatClient is not connected",{code:ot.MESSAGE_NOT_CONNECTED,details:{msgLocalId:t.msgLocalId,state:this.state,retryable:!0}});return"text"===t.type&&"targetLanguages"in t.body?this.sendTranslatedMessage(this.core,t,r):(this.attachOutgoingMessageProfileVersions(t),this.core.sendMessage(t,r))}async sendTranslatedMessage(e,t,r){const n=this.loginAttempt;let i;try{if(i=await wI(t,async e=>{const t=this.getRestContext(),r=new Cv(t.restBaseUrl,{errorMap:AI(RI,EI),requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return r.setAuthToken(t.token),yI(r,t,e)}),this.core!==e||this.loginAttempt!==n||this.state!==s)throw new gt("Connection changed before message send",{code:ot.MESSAGE_NOT_CONNECTED})}catch(o){const e=o instanceof vt?new lt(o.message,{code:o.code,details:o.details}):o instanceof Error?o:new ut(String(o),ot.UNKNOWN);throw r?.onFailed?.({...t,sendStatus:"failed"},e),e}return this.attachOutgoingMessageProfileVersions(i),e.sendMessage(i,r)}async waitForSendConnectionRecovery(e){let t=null;const r=e.recoverConnectionForSend().then(()=>!0).catch(e=>(Ks("Send connection recovery failed",{error:e instanceof Error?e.message:String(e)}),!1)),s=new Promise(e=>{t=setTimeout(()=>{e(!1)},1e4)}),n=await Promise.race([r,s]);t&&clearTimeout(t),n||Ks("Send connection recovery wait timed out",{timeoutMs:1e4,state:this.state})}dispatchOwnInfoUpdated(e){this.eventHub.dispatch("onOwnInfoUpdated",e)}dispatchUserInfoUpdated(e){0!==e.length&&this.eventHub.dispatch("onUserInfoUpdated",[...e])}refreshConversationDisplayFromUserInfos(e,t="profile"){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromUserInfos(e).changed&&this.emitConversationListUpdate(t)}refreshConversationDisplayFromJoinedGroups(e,t="profile",r){if(!this.cacheManager||0===e.length)return;this.cacheManager.refreshSessionListDisplayFromJoinedGroups(e.map(e=>({groupId:e.groupId,name:e.name,avatarUrl:e.avatarUrl,remindType:e.remindType})),r).changed&&this.emitConversationListUpdate(t)}enqueueMissingGroupSessionSenderUserInfos(e){if(!this.isMessageProfileSyncEnabled()||!this.cacheManager||0===e.length)return;const t=new Set;for(const n of e){const e="groupChat"===n.conversationType?n.lastMessage?.sender:null;!e?.userId||e.nickname&&e.avatarUrl||t.add(e.userId)}if(0===t.size)return;const r=this.cacheManager.getUserInfoSummaries([...t],!1),s=new Set(r.map(e=>e.userId));for(const n of t)s.has(n)||this.userInfoHydrationQueue.enqueue(n)}dispatchUserGroupNamecardUpdated(e,t,r){e&&t&&this.eventHub.dispatch(Ce,{groupId:e,userId:t,namecard:r})}async downloadAndParseCombinePayload(t){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN,details:{fields:[{path:"core",message:"ChatClient is not connected",rule:"state"}]}});return this.core.downloadAndParseCombineMessage(t)}async sendMessageAction(t,r){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED});if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN});return this.core.sendMessageAction(t,r)}async sendChatRoomOperation(t,r){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED});if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN});return this.core.sendChatRoomOperation(t,r)}async downloadAttachment(t){if(e.instance!==this)throw new mt("ChatClient is not initialized",{code:ot.VALIDATION_REQUIRED});if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN});return this.core.downloadAttachment(t)}decodeServerMessageMeta(e){if(!this.core)throw new mt("ChatClient is not connected",{code:ot.AUTH_NOT_LOGIN});return this.core.decodeServerMessageMeta(e)}registerManagers(e){if(0===e.length)return;const t=new Set;for(const r of e){const e=this.resolveManagerKey(r);if(t.has(e))throw this.buildManagerValidationError(`Manager key duplicated: ${e}`,ot.VALIDATION_INVALID_FORMAT,"managers.key","conflict",{managerKey:e});t.add(e)}for(const r of e)this.registerManagerInput(r)}registerManagerInput(t){return e.isManagerConstructor(t)?this.registerManagerConstructor(t):this.registerManagerInstance(t)}registerManagerConstructor(e){const t=this.getManagerKeyFromConstructor(e),r=this.managerRegistry.get(t);if(r){if(r.constructor===e)return r;throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromConstructor(e),"constructor-mismatch")}const s=new e;return s.bind(this,this.managerEventContext),this.managerRegistry.set(t,s),this.registerManagerCapabilities(s),this.attachManager(t,s),this.notifyManagerSessionReady(s),s}registerManagerInstance(e){const t=this.getManagerKeyFromInstance(e),r=this.managerRegistry.get(t);if(r){if(r===e)return e;if(r.constructor===e.constructor)throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromInstance(e),"instance-conflict");throw this.buildManagerConflictError(t,this.getManagerNameFromInstance(r),this.getManagerNameFromInstance(e),"constructor-mismatch")}return e.bind(this,this.managerEventContext),this.managerRegistry.set(t,e),this.registerManagerCapabilities(e),this.attachManager(t,e),this.notifyManagerSessionReady(e),e}registerManagerCapabilities(e){for(const t of e.capabilities??[])this.managerCapabilities.set(t,e)}dispatchRawNotifyToCapability(e,t){const r=this.getManagerByCapability(e);return r?.handleRawNotify?.(t)}getUserInfoReadCapability(){const e=this.getManagerByCapability("userInfo:read");return e&&this.hasUserInfoReadCapability(e)?e:null}getGroupNamecardHydrationCapability(){const e=this.getManagerByCapability("group:namecard");return e&&this.hasGroupNamecardHydrationCapability(e)?e:null}validateOptionalCapabilityDependencies(){if(this.config.enableUserInfoSync&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","userInfo:read",["UserInfoManager"]);if(this.config.enableUserInfoSync&&!this.getGroupNamecardHydrationCapability())throw this.buildMissingCapabilityError("enableUserInfoSync","group:namecard",["GroupManager"]);if(this.config.enableSyncData.includes("contact")&&!this.getUserInfoReadCapability())throw this.buildMissingCapabilityError("enableSyncData: ['contact']","userInfo:read",["UserInfoManager"]);if(this.config.enableSyncData.includes("group")&&!this.managerRegistry.has("groupManager"))throw this.buildMissingCapabilityError("enableSyncData: ['group']","rawNotify:group",["GroupManager"])}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}hasGroupNamecardHydrationCapability(e){return"function"==typeof e.hydrateMessageProfileGroupNamecards}buildMissingCapabilityError(e,t,r){return new mt(`${e} requires explicit manager capability: ${t}`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} requires explicit manager capability: ${t}`,rule:"dependency"}],capability:t,requiredManagers:r}})}resolveManagerKey(t){if(e.isManagerConstructor(t))return this.getManagerKeyFromConstructor(t);if("object"!=typeof t||null===t)throw this.buildManagerValidationError("Manager must be constructor or instance",ot.VALIDATION_INVALID_FORMAT,"managers","type",{receivedType:typeof t});return this.getManagerKeyFromInstance(t)}getManagerKeyFromConstructor(e){const t=e.key;if(!this.isValidManagerKey(t))throw this.buildManagerValidationError("Manager key is required",ot.VALIDATION_REQUIRED,"managers.key","required",{managerType:"constructor",managerName:this.getManagerNameFromConstructor(e)});return t}getManagerKeyFromInstance(e){const t=e.constructor.key;if(!this.isValidManagerKey(t))throw this.buildManagerValidationError("Manager key is required",ot.VALIDATION_REQUIRED,"managers.key","required",{managerType:"instance",managerName:this.getManagerNameFromInstance(e)});return t}attachManager(e,t){Object.prototype.hasOwnProperty.call(this,e)||Object.defineProperty(this,e,{value:t,writable:!1,enumerable:!0})}isValidManagerKey(e){return"string"==typeof e&&e.trim().length>0}getManagerNameFromConstructor(e){return"string"==typeof e.name&&e.name.length>0?e.name:"AnonymousManager"}getManagerNameFromInstance(e){const t=e.constructor;return"string"==typeof t.name&&t.name.length>0?t.name:"AnonymousManager"}buildManagerValidationError(e,t,r,s,n){return new mt(e,{code:t,details:{fields:[{path:r,message:e,rule:s}],...n}})}buildManagerConflictError(e,t,r,s){return this.buildManagerValidationError("Manager key conflict",ot.VALIDATION_INVALID_FORMAT,"managers.key","conflict",{managerKey:e,existingName:t,incomingName:r,reason:s})}static isManagerConstructor(e){return"function"==typeof e}updateState(e){this.state!==e&&(this.state=e)}throwIfLoginSessionCancelled(e,t){if(e!==this.loginAttempt||this.core!==t)throw new ht("Login cancelled",{code:ot.CONNECTION_CANCELLED,details:{stage:"auth"}})}async initCacheManager(e){this.cacheManager&&this.cacheUserId===e||(this.cacheManager=new fy({appKey:this.requireActiveAppKey(),userId:e,cacheEncryptionMode:this.config.cacheEncryptionMode,storageAdapter:this.platformAdapter?.storage}),this.cacheUserId=e),await this.cacheManager.prepare()}loadCachedConversations(){this.cacheManager&&this.emitConversationListUpdate("conversation",!0)}loadCachedUserInfo(){this.cacheManager&&this.cacheManager.loadUserInfoSummaries()}emitConversationListUpdate(e,t=!1){if(!this.cacheManager)return;const r=this.cacheManager.loadSessionList().map(rv),s=this.buildConversationListPatch(this.conversationListSnapshot,r,t);(s.reset||0!==s.upserted.length||0!==s.removed.length||s.orderChanged)&&(this.conversationListVersion+=1,this.conversationListSnapshot=r,this.eventHub.dispatch(L,{version:this.conversationListVersion,items:r,reason:e,patch:s}))}buildConversationListPatch(e,t,r){const s=new Map(e.map(e=>[this.buildConversationListKey(e),e])),n=new Map(t.map(e=>[this.buildConversationListKey(e),e])),i=new Set,o=[],a=[];for(const d of t){const e=this.buildConversationListKey(d),t=s.get(e);t&&this.isConversationListItemEqual(t,d)||(o.push(d),i.add(e))}for(const d of e){const e=this.buildConversationListKey(d);n.has(e)||(a.push({conversationId:d.conversationId,conversationType:d.conversationType}),i.add(e))}const c=e.map(e=>this.buildConversationListKey(e)).join("\n")!==t.map(e=>this.buildConversationListKey(e)).join("\n");if(c)for(const d of t)i.add(this.buildConversationListKey(d));return{reset:r,upserted:o,removed:a,affectedKeys:[...i],orderChanged:c}}buildConversationListKey(e){return`${e.conversationType}:${e.conversationId}`}isConversationListItemEqual(e,t){return e.conversationId===t.conversationId&&e.conversationType===t.conversationType&&e.unreadCount===t.unreadCount&&e.lastMessageAt===t.lastMessageAt&&e.isPinned===t.isPinned&&e.pinnedTimestamp===t.pinnedTimestamp&&e.readAt===t.readAt&&e.remindType===t.remindType&&e.conversationName===t.conversationName&&e.conversationAvatar===t.conversationAvatar&&e.marks.length===t.marks.length&&e.marks.every((e,r)=>e===t.marks[r])&&JSON.stringify(e.lastMessage)===JSON.stringify(t.lastMessage)}async triggerContactSync(){this.config.enableSyncData.includes("contact")&&await this.refreshContactSnapshot()}async triggerConfiguredSyncDataAfterLogin(e,t){const r=[];this.config.enableSyncData.includes("contact")&&(Ks("Triggering automatic contact sync after login",{userId:e}),r.push(this.runPostLoginTask(t,"contact",async()=>{await this.triggerContactSync()}))),this.config.enableSyncData.includes("group")&&(Ks("Triggering automatic group sync after login",{userId:e}),r.push(this.runPostLoginTask(t,"group",async()=>{await this.triggerGroupSync()}))),await Promise.all(r)}async triggerGroupSync(){if(!this.config.enableSyncData.includes("group"))return;const e=this.ensureGroupSyncController();await e.sync()}ensureSessionListSyncController(){return this.syncConversationListConfigController||(this.syncConversationListConfigController=new lv(this)),this.syncConversationListConfigController}ensureContactSyncController(){if(this.contactSyncController)return this.contactSyncController;const e=this.managerRegistry.get("contactManager");if(!e?.createSyncController)throw new mt("ContactManager is required for contact sync",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"contactManager",message:"ContactManager must be registered for enableSyncData: ['contact']",rule:"required"}]}});return this.contactSyncController=e.createSyncController({getContextState:()=>{const e=this.requireCacheManager();return{cacheMeta:e.loadContactCacheMeta(),versionState:e.loadContactVersionState(),cachedSnapshot:e.loadContactSnapshot("cache")}},queryMetadata:async e=>await Sv(this.getRestContext(),e,this.platformAdapter?.request),getSyncUrls:async()=>await this.resolveContactSyncUrls(),getSharedSyncSession:()=>this.getSharedSyncWebSocketSession(),buildRosterRequest:({version:e})=>this.buildContactRosterRequest(e),applySyncResult:e=>{const t=this.requireCacheManager().applyContactSync(e);return this.refreshConversationDisplayFromUserInfos(t.snapshot.items.map(e=>({userId:e.userId})),"profile"),t},onStart:()=>{this.emitSyncDataStart("contact")},onFinish:e=>{this.emitSyncDataFinished({dataType:"contact",status:e?.error?"failed":"success",error:e?.error?{dataType:"contact",code:e.error.code,stage:e.error.stage,message:e.error.message,retryable:e.error.retryable}:void 0})}}),this.contactSyncController}ensureGroupSyncController(){if(this.groupSyncController)return this.groupSyncController;const e=this.managerRegistry.get("groupManager");if(!e?.createSyncController)throw new mt("GroupManager is required for group sync",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"groupManager",message:"GroupManager must be registered for enableSyncData: ['group']",rule:"required"}]}});return this.groupSyncController=e.createSyncController({getRestContext:()=>this.getRestContext(),getSyncUrls:async()=>await this.resolveContactSyncUrls(),getSharedSyncSession:()=>this.getSharedSyncWebSocketSession(),getCacheManager:()=>this.requireCacheManager(),applyRuntimeSnapshot:e=>{const t=this.managerRegistry.get("groupManager");t?.applyJoinedGroupSnapshot?.(e),this.refreshConversationDisplayFromJoinedGroups(e.items,"profile")},getRuntimeSnapshot:()=>{const e=this.managerRegistry.get("groupManager");return e?.getJoinedGroupSnapshotForSync?.()??null},onStart:()=>{this.emitSyncDataStart("group")},onFinish:e=>{this.emitSyncDataFinished({dataType:"group",status:e.status,error:e.error})}}),this.groupSyncController}emitSyncDataStart(e){this.eventHub.dispatch($,{dataType:e})}emitSyncDataFinished(e){this.eventHub.dispatch(j,e)}requireCacheManager(){if(!this.cacheManager)throw new mt("cacheManager is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"cacheManager",message:"cacheManager is required",rule:"required"}]}});return this.cacheManager}async resolveContactSyncUrls(){if(this.contactSyncWsUrls.length>0)return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls);if(this.contactSyncDnsResolved)throw Ks("Derived contact sync websocket is unavailable after DNS precheck",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new ut("Contact sync websocket urls are unavailable",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});if("dns"!==this.config.serviceConfig.mode)throw Ks("Derived contact sync websocket is unavailable for fixed service config",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new ut("Contact sync websocket urls are unavailable",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect"}});try{const e=await Qv(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:this.platformAdapter?.request});this.contactSyncWsUrls=[Zv(e.restBaseUrl)],this.contactSyncDnsResolved=!0}catch(e){throw Ks("Automatic contact sync REST endpoint DNS resolve failed",{userId:this.currentUserId,reason:e instanceof Error?e.message:String(e)}),new ut("Contact sync websocket dns resolve failed",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",cause:e instanceof Error?e.message:String(e)}})}return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls)}buildAuthenticatedContactSyncUrls(e){const t=this.requireContactSyncToken();return this.shuffleContactSyncUrls(e.map(e=>this.buildContactSyncSocketUrl(e,t)))}buildAuthenticatedSessionListSyncUrls(e){if(0===e.length)return[];const t=this.requireContactSyncToken();return e.map(e=>this.buildContactSyncSocketUrl(e,t))}requireContactSyncToken(){if(this.authToken)return this.authToken;throw new mt("token is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}})}buildContactSyncSocketUrl(e,t){const r=e.trim();if(!/^wss?:\/\/[^/?#]+/i.test(r))throw new mt("sync websocket URL must use ws or wss protocol");const s=r.indexOf("#"),n=s>=0?r.slice(s):"",i=s>=0?r.slice(0,s):r,o=i.indexOf("?"),a=o>=0?i.slice(0,o):i,c=o>=0?i.slice(o+1):"",d=a.indexOf("://")+3,u=a.indexOf("/",d),l=u<0||"/"===a.slice(u)?`${a}/ws`:a,h=c.split("&").filter(e=>e.length>0&&"token"!==e.split("=",1)[0]),p=encodeURIComponent(t).replace(/%20/g,"+");return h.push(`token=${p}`),`${l}?${h.join("&")}${n}`}shuffleContactSyncUrls(e){const t=[...e];for(let r=t.length-1;r>0;r-=1){const e=Math.floor(Math.random()*(r+1)),s=t[r],n=t[e];s&&n&&(t[r]=n,t[e]=s)}return t}buildContactRosterRequest(e){const t=this.getRestContext(),{orgName:r,appName:s}=fs(t.appKey);return{type:BI,header:{resource:t.clientResource,timestamp:Date.now(),requestId:`contact-sync-${Date.now()}`,protocolVersion:1},org:r,app:s,username:t.userId,version:e,cursor:0}}detachSessionListSyncController(){const e=this.syncConversationListConfigController;return this.syncConversationListConfigController=null,e?.cancelForTeardown()??null}resetCore(){const e=this.detachSessionListSyncController();try{return this.cancelPostLoginTasks(),this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("reset-core"),this.syncWebSocketSession=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.core?(this.core.destroy(),this.clearCoreSessionState(),this.resetManagerSessionRuntimes(),e):e}catch(r){throw this.clearCoreSessionState(),this.updateState(t),e?.(),r}}clearCoreSessionState(){this.core=null,this.currentUserId=null,this.restBaseUrl=null,this.authToken=null,this.clientResource=null,this.platformAdapter=null,this.cacheManager=null,this.cacheUserId=null,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=[],this.contactSyncDnsResolved=!1}requireConfiguredAppKey(){if(this.config.appKey)return this.config.appKey;throw new mt("appKey is unavailable before DNSConfig resolution",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable before DNSConfig resolution",rule:"required"}]}})}requireActiveAppKey(){if(this.activeAppKey)return this.activeAppKey;throw new mt("appKey is unavailable for the current session",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"appKey",message:"appKey is unavailable for the current session",rule:"required"}]}})}resetManagerSessionRuntimes(){for(const t of this.managerRegistry.values())try{t.resetSessionRuntime?.()}catch(e){Ks("Manager session runtime reset failed",{manager:this.getManagerNameFromInstance(t),error:e instanceof Error?e.message:"unknown"})}this.activeManagerSessionContext=null,this.managerSessionEndingPromise=null}notifyManagersSessionReady(e,t){const r={generation:++this.managerSessionGeneration,userId:e,clientResource:t};this.activeManagerSessionContext=r,this.managerSessionEndingPromise=null;for(const s of this.managerRegistry.values())this.notifyManagerSessionReady(s)}notifyManagerSessionReady(e){const t=this.activeManagerSessionContext;if(t&&e.onSessionReady)try{e.onSessionReady(t)}catch(r){Ks("Manager session ready hook failed",{manager:this.getManagerNameFromInstance(e),error:r instanceof Error?r.message:"unknown"})}}notifyManagersSessionEnding(e){const t=this.activeManagerSessionContext;if(!t)return Promise.resolve();if(this.managerSessionEndingPromise)return this.managerSessionEndingPromise;const r={...t,reason:e},s=Array.from(this.managerRegistry.values(),e=>{if(!e.onSessionEnding)return Promise.resolve();try{return Promise.resolve(e.onSessionEnding(r)).catch(t=>{Ks("Manager session ending hook failed",{manager:this.getManagerNameFromInstance(e),error:t instanceof Error?t.message:"unknown"})})}catch(t){return Ks("Manager session ending hook failed",{manager:this.getManagerNameFromInstance(e),error:t instanceof Error?t.message:"unknown"}),Promise.resolve()}}),n=Promise.all(s).then(()=>{});let i=null;const o=new Promise(t=>{i=setTimeout(()=>{Ks("Manager session ending hooks timed out",{timeoutMs:6e3,reason:e}),t()},6e3)});return this.managerSessionEndingPromise=Promise.race([n,o]).then(()=>{null!==i&&clearTimeout(i),this.activeManagerSessionContext?.generation===t.generation&&(this.activeManagerSessionContext=null)}),this.managerSessionEndingPromise}isTerminalManagerSessionDisconnect(e){return e.reason===O||[ot.AUTH_TOKEN_EXPIRED,ot.AUTH_BIND_ANOTHER_DEVICE,ot.AUTH_LOGIN_TOO_MANY_DEVICES,ot.USER_LOGIN_ANOTHER_DEVICE,ot.USER_REMOVED,ot.USER_KICKED_BY_CHANGE_PASSWORD,ot.USER_KICKED_BY_OTHER_DEVICE].includes(e.errorCode??-1)}startTerminalSessionCleanup(e){if(this.terminalSessionCleanupTask)return;Ks("Terminal session cleanup started",{errorCode:e.errorCode,errorMessage:e.errorMessage,reason:e.reason});const t=this.finishTerminalSessionCleanup().catch(e=>{zs("Terminal session cleanup failed",e instanceof Error?e:new Error(String(e)))}).finally(()=>{this.terminalSessionCleanupTask===t&&(this.terminalSessionCleanupTask=null)});this.terminalSessionCleanupTask=t}async waitForTerminalSessionCleanup(){await(this.terminalSessionCleanupTask??Promise.resolve())}async finishTerminalSessionCleanup(){this.loginAttempt+=1,this.cancelPostLoginTasks(),await this.notifyManagersSessionEnding("terminal-disconnect");try{try{await(this.cacheManager?.flushPending())}catch(e){Ks("Cache flush on terminal disconnect failed",{error:e instanceof Error?e.message:String(e)})}if(this.logReportEnabled)try{await $s()}catch(e){Ks("Report logs on terminal disconnect failed",e)}}finally{const e=this.resetCore();try{this.activeAppKey=this.config.appKey??null,this.updateState(t),this.logReportEnabled=!1,Gs("disabled"),js(),Yh()}finally{e?.()}}Ks("Terminal session cleanup finished")}static isSameConfig(t,r){return t.appKey===r.appKey&&(t.appId===r.appId&&(!!e.isSameStringArray(t.enableSyncData,r.enableSyncData)&&(t.useCustomAttachmentUpload===r.useCustomAttachmentUpload&&(t.enableMd5Check===r.enableMd5Check&&(!!e.isSameServiceConfig(t.serviceConfig,r.serviceConfig)&&(t.useFixedDeviceId===r.useFixedDeviceId&&(t.deviceId===r.deviceId&&(t.useReplacedMessageContents===r.useReplacedMessageContents&&(t.customDeviceName===r.customDeviceName&&(t.customOSPlatform===r.customOSPlatform&&(t.platformAdapterOptions?.prefer===r.platformAdapterOptions?.prefer&&(t.platformAdapterOptions?.runtimeInput===r.platformAdapterOptions?.runtimeInput&&(t.platformAdapterOptions?.transportAdapter===r.platformAdapterOptions?.transportAdapter&&(t.platformAdapterOptions?.overrides===r.platformAdapterOptions?.overrides&&(t.uiKitVersion===r.uiKitVersion&&(t.cacheEncryptionMode===r.cacheEncryptionMode&&(t.enableUserInfoSync===r.enableUserInfoSync&&(t.deleteConversationOnGroupDestroyed===r.deleteConversationOnGroupDestroyed&&(t.syncConversationListConfig.includeEmpty===r.syncConversationListConfig.includeEmpty&&(t.profileSync.userInfoWindowMs===r.profileSync.userInfoWindowMs&&t.profileSync.userInfoBatchSize===r.profileSync.userInfoBatchSize&&t.profileSync.groupNamecardWindowMs===r.profileSync.groupNamecardWindowMs&&t.profileSync.groupNamecardMaxConcurrency===r.profileSync.groupNamecardMaxConcurrency))))))))))))))))))))}static normalizeServiceConfig(t){const r=t?.serverUrls;return{mode:r?"fixed":"dns",dnsConfigUrls:t?.dnsConfigUrls??Bv,hasCustomDnsConfigUrls:Boolean(t?.dnsConfigUrls?.length),serverUrls:r?{restApiUrl:r.restApiUrl,wsUrl:r.wsUrl?e.normalizeFixedWebSocketUrl(r.wsUrl):void 0}:void 0}}static normalizeFixedWebSocketUrl(e){const t=e.search(/[?#]/),r=-1===t?e:e.slice(0,t),s=-1===t?"":e.slice(t),n=r.indexOf("://")+3,i=r.indexOf("/",n);if(-1===i)return`${r}/websocket${s}`;const o=r.slice(i);return/^\/+$/u.test(o)?`${r.slice(0,i)}/websocket${s}`:e}static normalizeSyncDataTypes(e){const t=[];for(const r of e)t.includes(r)||t.push(r);return t}static isSameStringArray(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}static isSameServiceConfig(t,r){if(t.mode!==r.mode)return!1;if(t.dnsConfigUrls.length!==r.dnsConfigUrls.length)return!1;for(let e=0;e<t.dnsConfigUrls.length;e+=1)if(t.dnsConfigUrls[e]!==r.dnsConfigUrls[e])return!1;return e.isSameServerUrls(t.serverUrls,r.serverUrls)}static isSameServerUrls(e,t){return!e&&!t||!(!e||!t)&&(e.restApiUrl===t.restApiUrl&&e.wsUrl===t.wsUrl)}};YI.instance=null;let XI=YI;const eb=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),tb=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw(e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}))(t);return e.trim()},rb=e=>`mark_${String(e)}`,sb=(e,t)=>{if("singleChat"===e||"groupChat"===e||"chatRoom"===e)return e;throw eb(t,`${t} must be one of singleChat, groupChat, chatRoom`)},nb=e=>"singleChat"===e?"chat":"groupChat"===e?"groupchat":"chatroom",ib=e=>"string"==typeof e&&e.length>0?e:void 0,ob=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}},ab=e=>Uu(e)?e:void 0,cb=e=>{const t=ab(e);if(!t)return;const r=ib(t.operatorId)??ib(t.operator),s=ob(t.operationCount)??ob(t.count),n=ob(t.operationTime)??ob(t.edit_time);return r&&void 0!==s&&void 0!==n?{operatorId:r,operationCount:s,operationTime:n}:void 0},db=e=>"txt"===e||"text"===e?"text":"custom"===e?"custom":"cmd"===e?"cmd":"img"===e?"image":"audio"===e?"voice":"loc"===e?"location":"image"===e||"file"===e||"voice"===e||"video"===e||"location"===e||"combine"===e?e:null,ub=(e,t)=>{if("text"===e)return{content:ib(t.msg)??ib(t.content)??""};if("custom"===e){const e=ab(t.customExts)??ab(t.params)??{},r={};for(const[t,s]of Object.entries(e))"string"==typeof s&&(r[t]=s);return{event:ib(t.customEvent)??ib(t.event)??"",params:r}}if("cmd"===e)return{action:ib(t.action)??""};if("image"===e){const e=ib(t.url)??ib(t.remotePath)??"";return{localUrl:"",filename:ib(t.filename)??ib(t.displayName),filetype:ib(t.filetype)??"application/octet-stream",width:ob(t.width),height:ob(t.height),isGif:!0===t.isGif||1===t.subType,isOriginalImage:!0===t.isOriginalImage,originalImageUrl:e,bigImageUrl:ib(t.bigImageUrl),thumbnailUrl:ib(t.thumbnailUrl)??ib(t.thumbnailRemotePath),secret:ib(t.secret)??ib(t.secretKey),fileLength:ob(t.fileLength)}}return"file"===e?{url:ib(t.url)??ib(t.remotePath),filename:ib(t.filename)??ib(t.displayName),filetype:ib(t.filetype)??"application/octet-stream",fileSize:ob(t.fileSize),fileLength:ob(t.fileLength),secret:ib(t.secret)??ib(t.secretKey)}:"voice"===e?{url:ib(t.url)??ib(t.remotePath),filename:ib(t.filename)??ib(t.displayName),filetype:ib(t.filetype)??"application/octet-stream",duration:ob(t.duration)??0,fileLength:ob(t.fileLength),secret:ib(t.secret)??ib(t.secretKey)}:"video"===e?{url:ib(t.url)??ib(t.remotePath),filename:ib(t.filename)??ib(t.displayName),filetype:ib(t.filetype)??"application/octet-stream",duration:ob(t.duration)??0,width:ob(t.width),height:ob(t.height),fileLength:ob(t.fileLength),secret:ib(t.secret)??ib(t.secretKey),thumbnailUrl:ib(t.thumbnailUrl)??ib(t.thumbnailRemotePath)}:"location"===e?{latitude:ob(t.latitude)??0,longitude:ob(t.longitude)??0,address:ib(t.address),buildingName:ib(t.buildingName)}:null},lb=(e,t)=>{const r=ab(e);if(!r)return;const s=(e=>"string"==typeof e?Lu(e,{}):ab(e)??{})(r.payload),n=Array.isArray(s.bodies)?s.bodies:[],i=n.length>=2?hu(n.map(e=>{const t=ab(e);if(!t)return null;if(du(t))return{type:"combine",body:{title:ib(t.title)??"",summary:ib(t.summary)??"",filename:ib(t.filename)??ib(t.displayName)??"combine",filetype:"application/octet-stream",url:ib(t.url)??ib(t.remotePath),secret:ib(t.secret)??ib(t.secretKey),fileLength:ob(t.fileLength)??ob(t.file_length),combineLevel:ob(t.combineLevel)??0}};const r=db(t.type);if(!r)return null;const s=ub(r,t);return s?{type:r,body:s}:null})):null,o=ab(n[0])??ab(s.body),a=i?.type??db(o?.type??s.type);if("multi_body"===i?.type&&Array.isArray(i.body)){const e=ib(s.from)??ib(r.from)??"",n=ib(s.to)??t.conversationId,o=ab(s.sender),a={userId:ib(o?.userId)??e,nickname:ib(o?.nickname),avatarUrl:ib(o?.avatarUrl)},c=ab(s.ext)??{},d=cb(s.modifiedInfo??ab(s.meta)?.edit_msg);return{msgServerId:ib(r.id)??t.messageId,msgLocalId:ib(r.msgLocalId)??"",from:e,to:n,sender:a,conversationId:t.conversationId,conversationType:t.conversationType,type:"multi_body",sendStatus:"sent",ext:c,timestamp:ob(r.timestamp)??t.timestamp,body:i.body,direct:e===t.currentUserId?"SEND":"RECEIVE",...d?{modifiedInfo:d}:{}}}const c="multi_body"===i?.type?null:i?.body??(a&&o?ub(a,o):null);if(!a||!c)return;const d=ib(s.from)??ib(r.from)??"",u=ib(s.to)??t.conversationId,l=ab(s.sender),h={userId:ib(l?.userId)??d,nickname:ib(l?.nickname),avatarUrl:ib(l?.avatarUrl)},p=ab(s.ext)??{},m=cb(s.modifiedInfo??ab(s.meta)?.edit_msg);return{msgServerId:ib(r.id)??t.messageId,msgLocalId:ib(r.msgLocalId)??"",from:d,to:u,sender:h,conversationId:t.conversationId,conversationType:t.conversationType,type:a,sendStatus:"sent",ext:p,timestamp:ob(r.timestamp)??t.timestamp,body:c,direct:d===t.currentUserId?"SEND":"RECEIVE",...m?{modifiedInfo:m}:{}}},hb=e=>`${e.conversationType}:${e.conversationId}`,pb=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},mb=async(e,t,r,s)=>{const n=pb(t),i=(e=>{const t=e,r=t.conversations;if(void 0!==r){if(!Array.isArray(r)||0===r.length)throw eb("params.conversations","params.conversations must be a non-empty array");return r.map((e,t)=>{if(!Uu(e))throw eb(`params.conversations.${String(t)}`,`params.conversations.${String(t)} must be an object`);return{conversationId:tb(e.conversationId,`params.conversations.${String(t)}.conversationId`),conversationType:sb(e.conversationType,`params.conversations.${String(t)}.conversationType`)}})}return[{conversationId:tb(t.conversationId,"params.conversationId"),conversationType:sb(t.conversationType,"params.conversationType")}]})(r),o=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0||e>19)throw eb(t,`${t} must be an integer between 0 and 19`);return e})(r.mark,"params.mark"),a=await e.request(`/${n.orgName}/${n.appName}/sdk/user/${n.encodedUserId}/user_channels/mark?resource=${n.encodedResource}`,{method:s?"POST":"DELETE",body:{mark:rb(o),targets:i.map(e=>({to:e.conversationId,type:nb(e.conversationType)}))},operation:s?"addConversationMark":"removeConversationMark"}),c=(e=>{if(!Array.isArray(e))return new Set;const t=new Set;return e.forEach(e=>{if(!Uu(e))return;const r="string"==typeof e.to?e.to.trim():"",s=(e=>"chat"===e||"singleChat"===e?"singleChat":"groupchat"===e||"groupChat"===e?"groupChat":"chatroom"===e||"chatRoom"===e?"chatRoom":null)(e.type);r&&s&&t.add(hb({conversationId:r,conversationType:s}))}),t})((Uu(a)&&Uu(a.data)?a.data:{}).ignore),d=[],u=[];for(const l of i){const e={conversationId:l.conversationId,conversationType:l.conversationType};c.has(hb(l))?u.push({...e,reason:"ignored_by_server"}):d.push(e)}return{succeeded:d,failed:u,mark:o,operation:s?"addMark":"removeMark"}},gb=async(e,t,r,s)=>{const n=pb(t),i=tb(r.conversationId,"params.conversationId"),o=sb(r.conversationType,"params.conversationType"),a=tb(r.messageId,"params.messageId");return await e.request(`/${n.orgName}/${n.appName}/sdk/user/${n.encodedUserId}/user_channel/pin?resource=${n.encodedResource}`,{method:s?"POST":"DELETE",body:{to:i,type:nb(o),pin_msg_id:a},operation:s?"pinMessage":"unpinMessage"}),{conversationId:i,conversationType:o,messageId:a,operation:s?"pin":"unpin"}},fb=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],yb=(e,t)=>`${e}\0${t}`,vb=(e,t,r)=>{const s={userId:e};for(const n of fb){const e=r?.[n]??t?.[n];void 0!==e&&(s[n]=e)}return s},Ib=e=>vb(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),bb=(e,t,r)=>{const s=new Map;if(!e?.getGroupNamecard||!r)return s;for(const n of t){const t=e.getGroupNamecard(n.groupId,n.user.userId,!1);t&&s.set(yb(n.groupId,n.user.userId),t.namecard)}return s},_b=async(e,t)=>{if(0===e.length||!t)return[];try{return await t({userIds:e})}catch(r){return Ks("Group user info hydration failed",{userIds:e,error:r}),[]}},Tb=async(e,t)=>{t&&0!==e.size&&await Promise.all([...e.entries()].map(async([e,r])=>{try{await t(e,r)}catch(s){Ks("Group namecard hydration failed",{groupId:e,userIds:r,error:s})}}))},Cb=async e=>{const t=(e=>{const t=[],r=new Set;for(const s of e){const e=s.groupId.trim(),n=s.user.userId.trim();if(!e||!n)continue;const i=yb(e,n);r.has(i)||(r.add(i),t.push({groupId:e,user:{...s.user,userId:n}}))}return t})(e.contexts),r=(e=>{const t=[],r=new Set;for(const s of e)r.has(s.user.userId)||(r.add(s.user.userId),t.push(s.user.userId));return t})(t),s=((e,t)=>{const r=new Map;if(!e)return r;for(const n of t){const t=e.getRuntimeUserInfo?.(n,!1)??null;t&&r.set(n,t)}const s=t.filter(e=>!r.has(e));for(const n of e.getUserInfoSummaries?.(s,!1)??[])r.set(n.userId,Ib(n));return r})(e.cacheManager,r),n=r.filter(e=>!s.has(e)),i=new Set(n),o=bb(e.cacheManager,t,e.includeNameCard),a=e.includeNameCard?((e,t,r)=>{const s=new Map;for(const n of e){const e=n.user.userId,i=yb(n.groupId,e);if(!t.has(e)||r.has(i))continue;const o=s.get(n.groupId)??[];o.includes(e)||o.push(e),s.set(n.groupId,o)}return s})(t,i,o):new Map,[c]=await Promise.all([_b(n,e.fetchUserInfos),Tb(a,e.hydrateGroupNamecards)]),d=new Map(c.map(e=>[e.userId,e])),u=bb(e.cacheManager,t,e.includeNameCard),l=new Map;for(const h of t){const e=h.user.userId,t=yb(h.groupId,e),r=vb(e,h.user,d.get(e)??s.get(e)),n=u.get(t)??o.get(t);l.set(t,void 0!==n?{...r,nameCard:n}:r)}return{usersByContextKey:l,fetchedUserInfos:c,missingUserIds:n.filter(e=>!d.has(e))}},Sb=async e=>{const t=await Cb({...e,contexts:e.users.map(t=>({groupId:e.groupId,user:t}))}),r=new Map;for(const s of e.users){const n=s.userId.trim();if(!n||r.has(n))continue;const i=t.usersByContextKey.get(yb(e.groupId.trim(),n));i&&r.set(n,i)}return{usersById:r,fetchedUserInfos:t.fetchedUserInfos,missingUserIds:t.missingUserIds}},Eb=of(["singleChat","groupChat","chatRoom"]),wb=nf(Xg()).refine(e=>(e=>"object"==typeof e&&null!==e&&!Array.isArray(e))(e),"ext must be an object").refine(e=>(e=>{try{return JSON.stringify(e),!0}catch{return!1}})(e),"ext must be JSON serializable"),Ab=rf({path:Qg().min(1,"data.path is required"),size:Zg().optional(),name:Qg().optional(),type:Qg().optional()}),Rb=rf({uri:Qg().min(1,"data.uri is required"),size:Zg().optional(),name:Qg().optional(),type:Qg().optional()}),Nb=sf(["undefined"!=typeof File?((e,t={message:`Input not instance of ${e.name}`})=>Hg(t=>t instanceof e,t))(File):ef(),Ab,Rb]),Ob=rf({conversationId:Qg().min(1,"conversationId is required"),conversationType:Eb,ext:wb.optional(),timestamp:Zg().int().positive("timestamp must be a positive integer").optional(),receiverList:tf(Qg().min(1,"receiverList item is required")).nonempty("receiverList must not be empty").optional(),deliverOnlineOnly:Yg().optional(),webhookEnv:Qg().optional(),priority:of(["high","normal","low"]).optional(),needReadReceipt:Yg().optional(),isChatThread:Yg().optional()}),Mb=rf({type:Qg().min(1,"messageList.type is required"),sender:rf({userId:Qg().min(1,"messageList.sender.userId is required"),nickname:Qg().optional(),avatarUrl:Qg().optional()}),conversationId:Qg().min(1,"messageList.conversationId is required"),conversationType:Eb,timestamp:Zg().int().positive("messageList.timestamp must be positive"),body:sf([nf(Xg()),tf(nf(Xg())).min(2)]),combineLevel:Zg().int().min(0).max(10).optional()}).passthrough(),Ub=e=>e.superRefine((e,t)=>{e.receiverList&&"singleChat"===e.conversationType&&t.addIssue({code:bm.custom,message:"receiverList is only allowed for group or chat room conversation",path:["receiverList"]}),e.isChatThread&&"groupChat"!==e.conversationType&&t.addIssue({code:bm.custom,message:"isChatThread is only allowed for group conversation",path:["isChatThread"]}),e.needReadReceipt&&"chatRoom"===e.conversationType&&t.addIssue({code:bm.custom,message:"needReadReceipt is not allowed for chatRoom conversation",path:["needReadReceipt"]})}),Lb=Ub(Ob.extend({content:Qg().min(1,"content is required"),targetLanguages:tf(Qg().min(1)).optional()})),kb=Ub(Ob.extend({originalUrl:Qg().min(1,"originalUrl is required").optional(),filename:Qg().min(1,"filename is required").optional(),filetype:Qg().min(1,"filetype is required").optional(),width:Zg().positive("width must be positive").optional(),height:Zg().positive("height must be positive").optional(),isGif:Yg().optional(),isOriginalImage:Yg().optional(),fileLength:Zg().positive("fileLength must be positive").optional(),data:Nb.optional(),thumbnailUrl:Qg().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),Db=Ub(Ob.extend({originalUrl:Qg().min(1,"originalUrl is required").optional(),filename:Qg().min(1,"filename is required").optional(),filetype:Qg().min(1,"filetype is required").optional(),fileSize:Zg().positive("fileSize must be positive").optional(),fileLength:Zg().positive("fileLength must be positive").optional(),data:Nb.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),Pb=Ub(Ob.extend({originalUrl:Qg().min(1,"originalUrl is required").optional(),filename:Qg().min(1,"filename is required").optional(),filetype:Qg().min(1,"filetype is required").optional(),duration:Zg().positive("duration must be positive"),fileLength:Zg().positive("fileLength must be positive").optional(),data:Nb.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),xb=Ub(Ob.extend({originalUrl:Qg().min(1,"originalUrl is required").optional(),filename:Qg().min(1,"filename is required").optional(),filetype:Qg().min(1,"filetype is required").optional(),duration:Zg().positive("duration must be positive"),width:Zg().positive("width must be positive").optional(),height:Zg().positive("height must be positive").optional(),fileLength:Zg().positive("fileLength must be positive").optional(),thumbnailUrl:Qg().min(1).optional(),data:Nb.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),Fb=Ub(Ob.extend({latitude:Zg(),longitude:Zg(),address:Qg().min(1).optional(),buildingName:Qg().min(1).optional()})),Bb=Ub(Ob.extend({action:Qg().min(1,"action is required")})),Gb=Ub(Ob.extend({event:Qg().min(1,"event is required"),params:nf(Qg()).optional()})),qb=Ub(Ob),$b=Ub(Ob.extend({title:Qg().min(1,"title is required"),summary:Qg().min(1,"summary is required"),compatibleText:Qg().min(1).optional(),messageList:tf(Mb).min(1,"messageList must not be empty").max(300,"messageList max length is 300")})),jb=e=>{const t=e?.userId?.trim();if(!t)throw new mt("sender.userId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});return{userId:t,nickname:e?.nickname,avatarUrl:e?.avatarUrl}},Vb=()=>np(),Kb=(e,t)=>{if(e)return e;if(!t)throw new mt("url or data is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"url",message:"url or data is required",rule:"required"}]}});const r=sp(t);if(!r)throw new mt("Failed to resolve local url",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"url",message:"Failed to resolve local url",rule:"invalid_format"}]}});return r},zb=e=>!!e.isGif||(e.isOriginalImage??!1),Hb=(e,t,r,s,n)=>({msgServerId:"",msgLocalId:n??np(),from:t.userId,to:e.conversationId,sender:t,conversationId:e.conversationId,conversationType:e.conversationType,type:r,sendStatus:"sending",ext:e.ext??{},timestamp:e.timestamp??Date.now(),body:s,direct:"SEND",isOnline:!0,receiverList:e.receiverList,deliverOnlineOnly:e.deliverOnlineOnly,webhookEnv:e.webhookEnv,priority:e.priority,needReadReceipt:e.needReadReceipt,isPeerRead:"singleChat"!==e.conversationType&&void 0,isChatThread:e.isChatThread}),Wb=(e,t)=>{const r=Ev.validateOrThrow($b,e),s=r.messageList,n=jb(t);Mp(s);const i=Up(s);Lp(i);const o={title:r.title,summary:r.summary,messageList:s,filename:"combine",filetype:"application/octet-stream",combineLevel:i},a=Hb(r,n,"combine",o);return((e,t)=>{t&&yl.set(e,t)})(a,r.compatibleText),a},Jb=Hg(e=>{if("undefined"!=typeof File&&e instanceof File)return!0;if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.path&&t.path.length>0||"string"==typeof t.uri&&t.uri.length>0},{message:"data is invalid"}),Qb=rf({content:Qg().min(1,"content is required"),targetLanguages:tf(Qg().min(1)).optional()}),Zb=rf({originalUrl:Qg().min(1).optional(),filename:Qg().min(1).optional(),filetype:Qg().min(1).optional(),width:Zg().positive().optional(),height:Zg().positive().optional(),isGif:Yg().optional(),isOriginalImage:Yg().optional(),fileLength:Zg().positive().optional(),data:Jb.optional(),thumbnailUrl:Qg().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]}),Yb=rf({originalUrl:Qg().min(1).optional(),filename:Qg().min(1).optional(),filetype:Qg().min(1).optional(),fileSize:Zg().positive().optional(),fileLength:Zg().positive().optional(),data:Jb.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]}),Xb=rf({originalUrl:Qg().min(1).optional(),filename:Qg().min(1).optional(),filetype:Qg().min(1).optional(),duration:Zg().positive("duration must be positive"),fileLength:Zg().positive().optional(),data:Jb.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]}),e_=rf({originalUrl:Qg().min(1).optional(),filename:Qg().min(1).optional(),filetype:Qg().min(1).optional(),duration:Zg().positive("duration must be positive"),width:Zg().positive().optional(),height:Zg().positive().optional(),fileLength:Zg().positive().optional(),data:Jb.optional(),thumbnailUrl:Qg().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]}),t_=rf({latitude:Zg(),longitude:Zg(),address:Qg().optional(),buildingName:Qg().optional()}),r_=rf({event:Qg().min(1,"event is required"),params:nf(Qg()).optional()}),s_=(e,t)=>new mt(t,{code:ot.VALIDATION_UNKNOWN,details:{fields:[{path:e,message:t,rule:"invalid"}]}}),n_=e=>"string"==typeof e&&e.length>0,i_=(e,t)=>{const r=`bodies.${t}`;if("object"!=typeof(s=e)||null===s||Array.isArray(s)||"string"!=typeof e.type)throw s_(r,"segment is not allowed in a multi_body message");var s;if("stream"in e||"cmd"===e.type||"combine"===e.type||"multi_body"===e.type)throw s_(r,"segment cannot be command, combine, multi_body, or stream");if("text"===e.type&&!n_(e.content))throw s_(`${r}.content`,"content is required");if("image"===e.type){const t=n_(e.originalImageUrl)||n_(e.localUrl);if("boolean"!=typeof e.isGif||"boolean"!=typeof e.isOriginalImage||!t)throw s_(r,"image segment is invalid")}if(("file"===e.type||"voice"===e.type||"video"===e.type)&&!n_(e.url))throw s_(`${r}.url`,"url is required");if(("voice"===e.type||"video"===e.type)&&"number"!=typeof e.duration)throw s_(`${r}.duration`,"duration is required");if("location"===e.type&&("number"!=typeof e.latitude||"number"!=typeof e.longitude))throw s_(r,"location segment is invalid");if("custom"===e.type&&!n_(e.event))throw s_(`${r}.event`,"event is required");if("text"!==e.type&&"image"!==e.type&&"file"!==e.type&&"voice"!==e.type&&"video"!==e.type&&"location"!==e.type&&"custom"!==e.type)throw s_(r,"segment is not allowed in a multi_body message")};const o_=(e,t)=>{t&&((e,t)=>{ou.set(e,t)})(e,t)},a_=(e,t)=>{const{bodies:r,...s}=e,n=Ev.validateOrThrow(qb,s);!function(e){if(!Array.isArray(e)||e.length<2)throw s_("bodies","bodies must contain at least 2 segments");if(e.length>20)throw s_("bodies","bodies must contain at most 20 segments");e.forEach((e,t)=>{i_(e,t)})}(r);const i=jb(t),o=np(),a=[];r.forEach((e,t)=>{const r=(e=>{const t=ou.get(e);return t&&ou.delete(e),t})(e);r&&(a.push(t),rp.set(cu(o,t),r))});const c=((e,t,r,s)=>({msgServerId:"",msgLocalId:s??np(),from:t.userId,to:e.conversationId,sender:t,conversationId:e.conversationId,conversationType:e.conversationType,type:"multi_body",sendStatus:"sending",ext:e.ext??{},timestamp:e.timestamp??Date.now(),body:r,direct:"SEND",isOnline:!0,receiverList:e.receiverList,deliverOnlineOnly:e.deliverOnlineOnly,webhookEnv:e.webhookEnv,priority:e.priority,needReadReceipt:e.needReadReceipt,isPeerRead:"singleChat"!==e.conversationType&&void 0,isChatThread:e.isChatThread}))(n,i,r,o);return Vs("MultiBody message created",{operation:"message.multibody.create",msgLocalId:c.msgLocalId,segmentCount:r.length,segmentTypes:r.map(e=>e.type),fileIndexes:a}),c},c_=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/api/sdk/v1/${t}/${r}`},d_=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),u_=e=>d_(e)&&"string"==typeof e.path&&e.path.trim().length>0,l_=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||u_(e),h_=e=>{if(!d_(e))return;return{data:d_(e.data)?e.data:void 0,error:d_(e.error)?e.error:void 0}},p_=(e,t)=>{const r=h_(e),s=r?.data?.text;if("string"!=typeof s)throw new ut(`${t} response data is invalid`,ot.REST_BUSINESS_UNKNOWN,{details:{api:t,response:e}});return s},m_=(e,t,r,s="sdk")=>"auth"===s?new pt(e,{code:t,details:r}):"validation"===s?new mt(e,{code:t,details:r}):new ut(e,t,{details:r}),g_=e=>!(void 0===e||d_(e)&&!Array.isArray(e))||(void 0!==e?.format&&"string"!=typeof e.format||(void 0!==e?.sampleRate&&"number"!=typeof e.sampleRate||(void 0!==e?.bitsPerSample&&"number"!=typeof e.bitsPerSample||void 0!==e?.channels&&"number"!=typeof e.channels))),f_=e=>{if(!e)return;const t=(e.split("#")[0]?.split("?")[0]??"").split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0},y_=e=>{const{serviceCode:t,serviceMessage:r}=(e=>{const t=e instanceof ut&&d_(e.details)?e.details:void 0,r=h_(t?.rawResponse??t?.response??e),s=t?.serverCode??r?.error?.code,n=t?.serverMessage??r?.error?.message;return{serviceCode:"string"==typeof s||"number"==typeof s?String(s):void 0,serviceMessage:"string"==typeof n?n:void 0}})(e);if(e instanceof bt)return m_("File upload failed",ot.UPLOAD_REQUEST_FAILED,{cause:e.details});if(e instanceof ut&&!t)return e;if(t)switch(t){case"4041001":return m_("File not found",ot.VOICE_TO_TEXT_FILE_NOT_FOUND,{serviceCode:t,serviceMessage:r});case"4001002":return m_("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{serviceCode:t,serviceMessage:r},"validation");case"5021001":return m_("File upload failed",ot.UPLOAD_REQUEST_FAILED,{serviceCode:t,serviceMessage:r});case"4001003":return m_("Voice duration exceeds 60 seconds",ot.VOICE_TO_TEXT_FILE_DURATION_TOO_LONG,{serviceCode:t,serviceMessage:r},"validation");case"4031001":return m_("Voice-to-text service is not enabled",ot.SERVICE_NOT_ENABLED,{serviceCode:t,serviceMessage:r});case"4031002":return m_("Beta service usage limit exceeded",ot.SERVICE_LIMIT_EXCEEDED,{serviceCode:t,serviceMessage:r});case"4001001":return(e=>"string"==typeof e&&e.toLowerCase().includes("uploaded file exceeds"))(r)?m_("File too large",ot.VOICE_TO_TEXT_FILE_TOO_LARGE,{serviceCode:t,serviceMessage:r}):m_(r||"Missing or invalid request parameter",ot.VALIDATION_REQUIRED,{serviceCode:t,serviceMessage:r},"validation");case"5021003":case"5001003":return m_("Voice-to-text failed",ot.VOICE_TO_TEXT_FAILED,{serviceCode:t,serviceMessage:r});case"4011001":return m_(r||"Unauthorized or invalid token",ot.AUTH_UNAUTHORIZED,{serviceCode:t,serviceMessage:r},"auth");default:return m_(r||(e instanceof Error?e.message:"Voice-to-text failed"),ot.VOICE_TO_TEXT_FAILED,{serviceCode:t,serviceMessage:r})}return e instanceof ut?m_(e.message,e.code,e.details):m_(e instanceof Error?e.message:"Voice-to-text failed",ot.VOICE_TO_TEXT_FAILED)},v_=(e,t)=>{if(!d_(r=e)||"string"!=typeof r.filename||"string"!=typeof r.filetype||"number"!=typeof r.duration||"type"in r&&void 0!==r.type&&"voice"!==r.type)throw m_("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody"},"validation");var r;if(g_(t))throw m_("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!e.url)throw m_("File not found",ot.VOICE_TO_TEXT_FILE_NOT_FOUND,{path:"voiceMessageBody.url"});if(!f_(e.url))throw m_("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody.url"},"validation");return e},I_=(e,t)=>{if(g_(t))throw m_("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!l_(e))throw m_("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"file"},"validation");return e},b_=async(e,t,r,s)=>{const n=v_(r,s),i=f_(n.url);if(!i)throw((e,t,r,s="invalid")=>new mt(e,{code:t,details:{fields:[{path:r,message:e,rule:s}]}}))("File not found",ot.VOICE_TO_TEXT_FILE_NOT_FOUND,"voiceMessageBody.url");try{const r=await e.post(`${c_(t)}/speech/transcriptions`,{data:{fileId:i,username:t.userId,...s?{audio:s}:{}}},{operation:"voiceMessageToText"});return{text:p_(r,"voiceMessageToText")}}catch(o){throw y_(o)}},__=rf({keywordList:tf(Qg()).min(1,"keywordList must not be empty").max(5,"keywordList must have at most 5 keywords").refine(e=>e.map(e=>e.trim()).filter(e=>e.length>0).length>0,"keywordList must contain at least one non-empty keyword"),keywordListMatchType:of(["or","and"]).optional(),conversationId:Qg().min(1).optional(),conversationType:of(["singleChat","groupChat","chatRoom"]).optional(),msgTypes:tf(of(["txt","img","video","file","loc","custom","combine"])).optional(),startTime:Zg().optional(),endTime:Zg().optional(),searchScope:of(["none","with","only"]).optional(),direction:of(["up","down"]).optional()}).refine(e=>void 0!==e.conversationId===(void 0!==e.conversationType),{message:"conversationId and conversationType must be provided together"}).refine(e=>void 0!==e.startTime===(void 0!==e.endTime),{message:"startTime and endTime must be provided together"}).refine(e=>void 0===e.startTime||void 0===e.endTime||e.endTime>=e.startTime,{message:"endTime must be >= startTime"}),T_=rf({option:__,pageNum:Zg().int().min(1).default(1),pageSize:Zg().int().min(1).max(100).default(20)}),C_=AI(RI,EI),S_=new Set(["image","voice","video","file","location","combine"]),E_=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}async sendMessage(e,t){return this.getClientOrThrow().sendMessage(e,t)}createTextMessage(e){return((e,t)=>{const r=Ev.validateOrThrow(Lb,e),s=jb(t),n=Vb(),i={content:r.content};return r.targetLanguages&&(i.targetLanguages=r.targetLanguages),Hb(r,s,"text",i,n)})(e,this.buildMessageSenderOrThrow())}createImageMessage(e){return((e,t,r)=>{const s=Ev.validateOrThrow(kb,e),n=jb(t),i=Vb(),o=s.data?Kb(void 0,s.data):"",a=s.originalUrl?Cs(s.originalUrl,{deriveVariants:!r?.useCustomAttachmentUpload}):void 0;s.data&&rp.set(i,s.data);const c=s.isGif??!1,d={localUrl:o,filename:s.filename,filetype:s.filetype,width:s.width,height:s.height,isGif:c,isOriginalImage:zb({isGif:c,isOriginalImage:s.isOriginalImage})};return a?.originalImageUrl&&(d.originalImageUrl=a.originalImageUrl,d.bigImageUrl=a.bigImageUrl,d.thumbnailUrl=a.thumbnailUrl),void 0!==s.fileLength&&(d.fileLength=s.fileLength),s.thumbnailUrl&&(d.thumbnailUrl=s.thumbnailUrl),Hb(s,n,"image",d,i)})(e,this.buildMessageSenderOrThrow(),this.getClientOrThrow().getMessageCreationOptions())}createFileMessage(e){return((e,t)=>{const r=Ev.validateOrThrow(Db,e),s=jb(t),n=Vb(),i=Kb(r.originalUrl,r.data);r.data&&rp.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype};return void 0!==r.fileSize&&(o.fileSize=r.fileSize),void 0!==r.fileLength&&(o.fileLength=r.fileLength),Hb(r,s,"file",o,n)})(e,this.buildMessageSenderOrThrow())}createVoiceMessage(e){return((e,t)=>{const r=Ev.validateOrThrow(Pb,e),s=jb(t),n=Vb(),i=Kb(r.originalUrl,r.data);r.data&&rp.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.fileLength&&(o.fileLength=r.fileLength),Hb(r,s,"voice",o,n)})(e,this.buildMessageSenderOrThrow())}createVideoMessage(e){return((e,t)=>{const r=Ev.validateOrThrow(xb,e),s=jb(t),n=Vb(),i=Kb(r.originalUrl,r.data);r.data&&rp.set(n,r.data);const o={url:i,filename:r.filename,filetype:r.filetype,duration:r.duration};return void 0!==r.width&&(o.width=r.width),void 0!==r.height&&(o.height=r.height),void 0!==r.fileLength&&(o.fileLength=r.fileLength),r.thumbnailUrl&&(o.thumbnailUrl=r.thumbnailUrl),Hb(r,s,"video",o,n)})(e,this.buildMessageSenderOrThrow())}createLocationMessage(e){return((e,t)=>{const r=Ev.validateOrThrow(Fb,e),s=jb(t),n={latitude:r.latitude,longitude:r.longitude};return r.address&&(n.address=r.address),r.buildingName&&(n.buildingName=r.buildingName),Hb(r,s,"location",n)})(e,this.buildMessageSenderOrThrow())}createCmdMessage(e){return((e,t)=>{const r=Ev.validateOrThrow(Bb,e),s=jb(t),n={action:r.action};return void 0!==r.deliverOnlineOnly&&(n.deliverOnlineOnly=r.deliverOnlineOnly),Hb(r,s,"cmd",n)})(e,this.buildMessageSenderOrThrow())}createCustomMessage(e){return((e,t)=>{const r=Ev.validateOrThrow(Gb,e),s=jb(t),n={event:r.event};return r.params&&(n.params=r.params),Hb(r,s,"custom",n)})(e,this.buildMessageSenderOrThrow())}createCombineMessage(e){return Wb(e,this.buildMessageSenderOrThrow())}createTextMessageBody(e){return(e=>{const t=Ev.validateOrThrow(Qb,e);return{type:"text",content:t.content,...t.targetLanguages?{targetLanguages:t.targetLanguages}:{}}})(e)}createImageMessageBody(e){return((e,t)=>{const r=Ev.validateOrThrow(Zb,e),s=r.isGif??!1,n=r.originalUrl?Cs(r.originalUrl,{deriveVariants:!t?.useCustomAttachmentUpload}):void 0,i={type:"image",localUrl:r.data?Kb(void 0,r.data):"",filename:r.filename,filetype:r.filetype,width:r.width,height:r.height,isGif:s,isOriginalImage:!!s||(r.isOriginalImage??!1)};return n?.originalImageUrl&&(i.originalImageUrl=n.originalImageUrl,i.bigImageUrl=n.bigImageUrl,i.thumbnailUrl=n.thumbnailUrl),r.thumbnailUrl&&(i.thumbnailUrl=r.thumbnailUrl),void 0!==r.fileLength&&(i.fileLength=r.fileLength),o_(i,r.data),i})(e,this.getClientOrThrow().getMessageCreationOptions())}createFileMessageBody(e){return(e=>{const t=Ev.validateOrThrow(Yb,e),r={type:"file",url:Kb(t.originalUrl,t.data),filename:t.filename,filetype:t.filetype,...void 0!==t.fileSize?{fileSize:t.fileSize}:{},...void 0!==t.fileLength?{fileLength:t.fileLength}:{}};return o_(r,t.data),r})(e)}createVoiceMessageBody(e){return(e=>{const t=Ev.validateOrThrow(Xb,e),r={type:"voice",url:Kb(t.originalUrl,t.data),filename:t.filename,filetype:t.filetype,duration:t.duration,...void 0!==t.fileLength?{fileLength:t.fileLength}:{}};return o_(r,t.data),r})(e)}createVideoMessageBody(e){return(e=>{const t=Ev.validateOrThrow(e_,e),r={type:"video",url:Kb(t.originalUrl,t.data),filename:t.filename,filetype:t.filetype,duration:t.duration,...void 0!==t.width?{width:t.width}:{},...void 0!==t.height?{height:t.height}:{},...void 0!==t.fileLength?{fileLength:t.fileLength}:{},...t.thumbnailUrl?{thumbnailUrl:t.thumbnailUrl}:{}};return o_(r,t.data),r})(e)}createLocationMessageBody(e){return(e=>{const t=Ev.validateOrThrow(t_,e);return{type:"location",latitude:t.latitude,longitude:t.longitude,...void 0!==t.address?{address:t.address}:{},...void 0!==t.buildingName?{buildingName:t.buildingName}:{}}})(e)}createCustomMessageBody(e){return(e=>{const t=Ev.validateOrThrow(r_,e);return{type:"custom",event:t.event,...t.params?{params:t.params}:{}}})(e)}createMultiBodyMessage(e){return a_(e,this.buildMessageSenderOrThrow())}getConversationList(e){if(void 0!==e?.mark&&(!Number.isInteger(e.mark)||e.mark<0||e.mark>19))throw new mt("filter.mark must be an integer between 0 and 19",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"filter.mark",message:"filter.mark must be an integer between 0 and 19",rule:"invalid_format"}]}});const t=(this.getClientOrThrow().getCacheManager()?.loadSessionList()??[]).filter(t=>null!==t.lastMessage&&((void 0===e?.isPinned||t.isPinned===e.isPinned)&&!(void 0!==e?.mark&&!((e,t)=>e.marks.includes(t))(t,e.mark)))).map(rv);return this.getClientOrThrow().markConversationAccess(t.map(e=>({conversationId:e.conversationId,type:e.conversationType}))),t}setCurrentConversation(e){this.validateConversationLocator(e),this.getClientOrThrow().getCacheManager()?.setCurrentConversation({conversationId:e.conversationId,type:e.conversationType})}resetCurrentConversation(){this.getClientOrThrow().getCacheManager()?.resetCurrentConversation()}getCurrentConversation(){const e=this.getClientOrThrow().getCacheManager()?.getCurrentConversation()??null;return e?{conversationId:e.conversationId,conversationType:e.type}:null}refreshSessionList(e){return this.getClientOrThrow().refreshSessionList(e)}async deleteConversation(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=pb(t),n=tb(r.conversationId,"params.conversationId"),i=sb(r.conversationType,"params.conversationType"),o=r.deleteRoamingMessages??!1;if("boolean"!=typeof o)throw eb("params.deleteRoamingMessages","params.deleteRoamingMessages must be a boolean");return await e.request(`/${s.orgName}/${s.appName}/user/${s.encodedUserId}/user_channel?resource=${s.encodedResource}`,{method:"DELETE",body:{channel:n,type:"groupChat"===i?"groupChat":nb(i),delete_roam:o},operation:"deleteConversation"}),{conversationId:n,conversationType:i,operation:"delete"}})(this.getRestClient(t),t,e),s=this.getClientOrThrow(),n=s.getCacheManager()?.deleteConversation({conversationId:r.conversationId,type:r.conversationType});return n?.changed&&s.emitConversationListUpdate("local"),r}async setConversationPinned(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=pb(t),n=tb(r.conversationId,"params.conversationId"),i=sb(r.conversationType,"params.conversationType");if("boolean"!=typeof r.pinned)throw eb("params.pinned","params.pinned must be a boolean");const o="groupChat"===i?"groupChat":nb(i),a=r.pinned?await e.post(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/top?resource=${s.encodedResource}`,{type:o,to:n},{operation:"setConversationPinned"}):await e.delete(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/top?type=${encodeURIComponent(o)}&to=${encodeURIComponent(n)}&resource=${s.encodedResource}`,{operation:"setConversationPinned"}),c=Uu(a)&&Uu(a.data)?a.data:{};return{conversationId:n,conversationType:i,operation:"setPinned",isPinned:"boolean"==typeof c.is_top?c.is_top:r.pinned,pinnedTime:"number"==typeof c.update_top_status_time?c.update_top_status_time:r.pinned?Date.now():0}})(this.getRestClient(t),t,e),s=this.getClientOrThrow().getCacheManager(),n=s?.applyConversationPinnedMutation({conversationId:r.conversationId,type:r.conversationType,isPinned:r.isPinned??e.pinned,pinnedTime:r.pinnedTime});return n?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async addConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>mb(e,t,r,!0))(this.getRestClient(t),t,e),s=this.getClientOrThrow().getCacheManager(),n=s?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return n?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async removeConversationMark(e){const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>mb(e,t,r,!1))(this.getRestClient(t),t,e),s=this.getClientOrThrow().getCacheManager(),n=s?.applyConversationMarkMutation({conversations:[...r.succeeded.map(e=>({...e,applied:!0})),...r.failed.map(e=>({...e,applied:!1}))],mark:r.mark,operation:r.operation});return n?.changed&&this.getClientOrThrow().emitConversationListUpdate("local"),r}async clearAllMessagesAndConversations(){const e=this.getRestContextOrThrow();await(async(e,t)=>{const r=pb(t);await e.post(`/${r.orgName}/${r.appName}/sdk/message/roaming/user/${r.encodedUserId}/delete/all?resource=${r.encodedResource}`,void 0,{operation:"clearAllMessagesAndConversations"})})(this.getRestClient(e),e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversations();r?.changed&&t.emitConversationListUpdate("local")}async pinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>gb(e,t,r,!0))(this.getRestClient(t),t,e))}async unpinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>gb(e,t,r,!1))(this.getRestClient(t),t,e))}async getPinnedMessageList(e){const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=pb(t),n=tb(r.conversationId,"params.conversationId"),i=sb(r.conversationType,"params.conversationType"),o=await e.get(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/pin?to=${encodeURIComponent(n)}&type=${encodeURIComponent(nb(i))}&limit=${String(20)}`,{operation:"getPinnedMessageList"}),a=Uu(o)&&Uu(o.data)?o.data:{},c=(Array.isArray(a.msg_infos)?a.msg_infos:[]).reduce((e,r)=>{if(!Uu(r))return e;const s="string"==typeof r.pin_msg_id?r.pin_msg_id:Uu(r.message)&&"string"==typeof r.message.id?r.message.id:"";if(!s)return e;const o="number"==typeof r.pin_opt_at?r.pin_opt_at:0,a=lb(r.message,{messageId:s,conversationId:n,conversationType:i,currentUserId:t.userId,timestamp:o});return a?(e.push({messageId:s,conversationId:n,conversationType:i,operatorId:"string"==typeof r.pin_operator?r.pin_operator:void 0,pinnedAt:o,message:a}),e):e},[]);return{items:c}})(this.getRestClient(t),t,e))}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async clearConversationUnreadMessageCount(e){this.validateUnreadConversationLocator(e);const t=this.getClientOrThrow(),r=t.getCacheManager()?.clearConversationUnreadMessageCount({conversationId:e.conversationId,type:e.conversationType});r?.changed&&t.emitConversationListUpdate("local");try{await this.requireConnectedClient().sendMessageAction({kind:"clearConversationUnreadMessageCount",conversationId:e.conversationId,conversationType:e.conversationType,sendToPeer:!1},(e,t)=>this.buildActionError(e,t))}catch(s){if(!r?.matched)throw s;Ks("Conversation unread remote sync failed after local clear",{conversationId:e.conversationId,conversationType:e.conversationType,error:s})}}async sendMessageReadReceipts(e){this.validateSendMessageReadReceiptsParams(e),await this.requireConnectedClient().sendMessageAction({kind:"sendMessageReadReceipts",conversationId:e.conversationId,conversationType:e.conversationType,messageIds:e.messageIds},(e,t)=>this.buildActionError(e,t))}async clearAllConversationUnreadMessageCount(){await this.requireConnectedClient().sendMessageAction({kind:"clearAllConversationUnreadMessageCount",conversationId:this.getCurrentUserIdOrThrow(),conversationType:"singleChat",sendToPeer:!1,clearAllUnreadMessageCount:!0},(e,t)=>this.buildActionError(e,t));const e=this.getClientOrThrow(),t=e.getCacheManager()?.clearAllConversationUnreadMessageCount();t?.changed&&e.emitConversationListUpdate("local")}async recallMessage(e){this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId"),await this.requireConnectedClient().sendMessageAction({kind:"recall",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,ext:e.ext},(e,t)=>this.buildActionError(e,t));return{messageId:e.messageId,conversationId:e.conversationId,conversationType:e.conversationType,timestamp:Date.now()}}async modifyMessage(e){this.validateConversationLocator(e),this.requireNonEmptyString(e.messageId,"messageId");const t=(e=>{if("cmd"===e.type||"multi_body"===e.type)throw new mt("command and multi_body messages are not editable",{code:ot.OPERATION_UNSUPPORTED});if("text"===e.type){const t=e.body;return{messageType:"text",body:{content:t.content,...void 0!==t.targetLanguages?{targetLanguages:t.targetLanguages}:{},...void 0!==t.translations?{translations:{...t.translations}}:{}},ext:e.ext,updatesLocalBody:!0}}if("custom"===e.type){const t=e.body;return{messageType:"custom",body:{event:t.event,...void 0!==t.params?{params:t.params}:{}},ext:e.ext,updatesLocalBody:!0}}if(S_.has(e.type))return{messageType:e.type,body:e.body,ext:e.ext,updatesLocalBody:!1};throw new mt("command and multi_body messages are not editable",{code:ot.OPERATION_UNSUPPORTED})})(e.message),r=this.requireConnectedClient(),s=this.getCurrentUserIdOrThrow();if("text"===t.messageType){const r=t.body;void 0!==r.targetLanguages&&(t.body=await this.prepareEditedTextBody(r,s,e))}await r.sendMessageAction({kind:"update",conversationId:e.conversationId,conversationType:e.conversationType,messageId:e.messageId,body:t.body,messageType:t.messageType,ext:t.ext},(e,t)=>this.buildActionError(e,t));const n=Date.now(),i=r.getCurrentUserId()===s?r.getCacheManager():null,o=i?.loadSessionList().find(t=>t.conversationId===e.conversationId&&t.conversationType===e.conversationType&&t.lastMessage?.msgServerId===e.messageId)?.lastMessage,a=o?.modifiedInfo??i?.loadConversationSummaries().find(t=>t.conversationId===e.conversationId&&t.type===e.conversationType&&t.lastMessage?.msgId===e.messageId)?.lastMessage?.modifiedInfo,c={operatorId:s,operationCount:(a?.operationCount??0)+1,operationTime:n},d={msgServerId:e.messageId,msgLocalId:"",from:s,to:e.conversationId,sender:{userId:s},conversationId:e.conversationId,conversationType:e.conversationType,type:t.messageType,sendStatus:"sent",ext:t.ext??{},timestamp:n,body:t.body,direct:"SEND",modifiedInfo:c};return r.getCurrentUserId()===s&&r.patchConversationLastMessage(e,{type:d.type,...t.updatesLocalBody?{body:{...t.body}}:{},ext:d.ext,modifiedInfo:c}),d}async getHistoryMessages(e){if(this.validateConversationLocator(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r,s)=>{const n=`${aI(t)}/users/${t.userId}/messageroaming`,i=await e.post(n,{queue:"singleChat"===r.conversationType?`${r.conversationId}@easemob.com`:`${r.conversationId}@conference.easemob.com`,start:r.cursor&&r.cursor.length>0?r.cursor:-1,pull_number:r.pageSize??20,is_positive:"down"===r.searchDirection,msgType:(r.messageTypes??[]).join(","),end:-1,startTime:r.startTime??null,endTime:r.endTime??null,userIds:"singleChat"===r.conversationType?null:r.senderIds&&r.senderIds.length>0?r.senderIds:null},{operation:"getHistoryMessages"}),o=mI(i,"getHistoryMessages"),a=Array.isArray(o.msgs)?o.msgs:[],c=[];for(const d of a){if(!dI(d)||"string"!=typeof d.msg||0===d.msg.length)continue;const e=s(cI(d.msg));e&&c.push(e)}return{items:c,cursor:hI(o.next_key),hasMore:!0!==o.is_last&&c.length>0}})(this.getRestClient(t),t,e,e=>this.getClientOrThrow().decodeServerMessageMeta(e)))}async searchMessages(e){const t=Ev.validateOrThrow(T_,e),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>SI(this.getRestClient(r),r,t))}async downloadAttachment(e){return this.getClientOrThrow().downloadAttachment(e.message)}async downloadAndParseCombineMessage(e){return this.getClientOrThrow().downloadAndParseCombinePayload(this.resolveDownloadCombineMessageParams(e))}async removeHistoryMessages(e){if(this.validateConversationLocator(e),!e.messageIds&&!e.beforeTimestamp)throw this.buildValidationError("messageIds or beforeTimestamp is required","removeHistoryMessages");if(e.messageIds&&0===e.messageIds.length)throw this.buildValidationError("messageIds cannot be empty","messageIds");if(void 0!==e.beforeTimestamp&&(!Number.isInteger(e.beforeTimestamp)||e.beforeTimestamp<=0))throw this.buildValidationError("beforeTimestamp must be a positive integer","beforeTimestamp");const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const s="singleChat"===r.conversationType?"userId":"groupId",n="singleChat"===r.conversationType?"chat":"group",i=encodeURIComponent(t.clientResource),o=r.messageIds?`${aI(t)}/sdk/message/roaming/${n}/user/${t.userId}?${s}=${encodeURIComponent(r.conversationId)}&msgIdList=${encodeURIComponent(r.messageIds.join(","))}&resource=${i}`:`${aI(t)}/sdk/message/roaming/${n}/user/${t.userId}/time?${s}=${encodeURIComponent(r.conversationId)}&delTime=${r.beforeTimestamp}&resource=${i}`;await e.delete(o,{operation:"removeHistoryMessages"})})(this.getRestClient(t),t,e))}async getGroupMessageReadUsers(e){if(this.requireNonEmptyString(e.groupId,"groupId"),this.requireNonEmptyString(e.messageId,"messageId"),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow(),r=await this.executeRestOperation(()=>(async(e,t,r)=>{const s=xv();s.set("limit",String(r.pageSize??10)),r.cursor&&s.set("key",r.cursor);const n=`${aI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/${encodeURIComponent(r.messageId)}?${s.toString()}`,i=await e.get(n,{operation:"getGroupMessageReadUsers"}),o=mI(i,"getGroupMessageReadUsers"),a=dI(o.group_ack)?o.group_ack:o,c=(Array.isArray(a.userlist)?a.userlist:[]).map(e=>dI(e)&&"string"==typeof e.username?{userId:e.username,user:pI(e.username),ackId:"string"==typeof e.meta_id?e.meta_id:void 0,timestamp:"number"==typeof e.timestamp?e.timestamp:void 0,ackContent:"string"==typeof e.ack_content?e.ack_content:void 0}:null).filter(e=>null!==e);return{groupId:r.groupId,messageId:"string"==typeof o.ackmid?o.ackmid:r.messageId,users:c,count:"number"==typeof a.total?a.total:c.length,cursor:hI(a.next_key),hasMore:!0!==a.is_last&&c.length>0}})(this.getRestClient(t),t,e));return await this.hydrateGroupMessageReadUsers(e.groupId,r)}async getGroupMessageReadReceipts(e){this.requireNonEmptyString(e.groupId,"groupId");const t=this.validateMessageIdList(e.messageIds,"messageIds"),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=`${aI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/batch`,n=await e.post(s,{messageIds:r.messageIds},{operation:"getGroupMessageReadReceipts"});return gI(n,"getGroupMessageReadReceipts").map(e=>dI(e)&&"string"==typeof e.ackmid&&"number"==typeof e.total?{messageId:e.ackmid,count:e.total}:null).filter(e=>null!==e)})(this.getRestClient(r),r,{groupId:e.groupId.trim(),messageIds:t}))}async addReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{await e.post(`${aI(t)}/reaction/user/${t.userId}`,{msgId:r.messageId,message:r.reaction},{operation:"addReaction"})})(this.getRestClient(t),t,e))}async removeReaction(e){this.validateReactionParams(e);const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>{const s=`${aI(t)}/reaction/user/${t.userId}?msgId=${encodeURIComponent(r.messageId)}&message=${encodeURIComponent(r.reaction)}`;await e.delete(s,{operation:"removeReaction"})})(this.getRestClient(t),t,e))}async getReactionList(e){if(!e.messageId||Array.isArray(e.messageId)&&0===e.messageId.length)throw this.buildValidationError("messageId is required","messageId");"groupChat"===e.conversationType&&this.requireNonEmptyString(e.groupId??"","groupId");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=xv(),n="string"==typeof r.messageId?r.messageId:[...r.messageId].join(",");s.set("msgIdList",n),s.set("msgType","groupChat"===r.conversationType?"group":"chat"),r.groupId&&s.set("groupId",r.groupId);const i=await e.get(`${aI(t)}/reaction/user/${t.userId}?${s.toString()}`,{operation:"getReactionList"});return gI(i,"getReactionList").map(e=>{if(!dI(e)||"string"!=typeof e.msgId)return null;const t=Array.isArray(e.reactionList)?e.reactionList:[];return{messageId:e.msgId,reactions:t.map(e=>dI(e)&&"string"==typeof e.reaction?{reaction:e.reaction,count:"number"==typeof e.count?e.count:0,isAddedBySelf:!0===e.state,userIds:Array.isArray(e.userList)?e.userList.filter(e=>"string"==typeof e):[]}:null).filter(e=>null!==e)}}).filter(e=>null!==e)})(this.getRestClient(t),t,e))}async getReactionDetail(e){if(this.validateReactionParams(e),void 0!==e.pageSize&&(!Number.isInteger(e.pageSize)||e.pageSize<=0))throw this.buildValidationError("pageSize must be a positive integer","pageSize");const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t,r)=>{const s=xv();s.set("msgId",r.messageId),s.set("message",r.reaction),s.set("cursor",r.cursor??""),s.set("limit",String(r.pageSize??20));const n=await e.get(`${aI(t)}/reaction/user/${t.userId}/detail?${s.toString()}`,{operation:"getReactionDetail"}),i=mI(n,"getReactionDetail"),o=Array.isArray(i.reactionUserList)?i.reactionUserList.map(e=>dI(e)&&"string"==typeof e.userId?{userId:e.userId,user:pI(e.userId),createdAt:"string"==typeof e.createdAt?e.createdAt:void 0}:null).filter(e=>null!==e):[],a=Array.isArray(i.userList)?i.userList.filter(e=>"string"==typeof e).map(e=>({userId:e,user:pI(e)})):[],c=o.length>0?o:a;return{reaction:"string"==typeof i.reaction?i.reaction:r.reaction,count:"number"==typeof i.count?i.count:c.length,isAddedBySelf:!0===i.state,reactionUsers:c,cursor:hI(i.cursor),hasMore:hI(i.cursor).length>0,createdAt:"string"==typeof i.createdAt?i.createdAt:void 0}})(this.getRestClient(t),t,e))}async getSupportedTranslationLanguages(){const e=this.getRestContextOrThrow();return this.executeRestOperation(()=>(async(e,t)=>{const r=await uI(()=>e.get(`${aI(t)}/users/${t.userId}/translate/support/language`,{operation:"getSupportedTranslationLanguages"}));return fI(r,"getSupportedTranslationLanguages").map(e=>dI(e)&&"string"==typeof e.code?{code:e.code,name:"string"==typeof e.name?e.name:e.code,nativeName:"string"==typeof e.nativeName?e.nativeName:e.code}:null).filter(e=>null!==e)})(this.getRestClient(e),e))}async translateMessage(e){if("text"!==e.message.type)throw new mt("only text messages can be translated",{code:ot.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"message.type",message:"must be text",rule:"message_type"}]}});const t=e.message.body.content.trim();if(0===t.length)throw new mt("message text is required",{code:ot.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"message.body.content",message:"is required",rule:"required"}]}});if(!Array.isArray(e.targetLanguages)||0===e.targetLanguages.length)throw new mt("targetLanguages is required",{code:ot.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"targetLanguages",message:"is required",rule:"required"}]}});if(e.targetLanguages.some(e=>"string"!=typeof e||0===e.trim().length))throw new mt("targetLanguages contains invalid language code",{code:ot.TRANSLATE_PARAM_INVALID,details:{fields:[{path:"targetLanguages",message:"contains invalid language code",rule:"language_code"}]}});const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>yI(this.getRestClient(r),r,{text:t,targetLanguages:e.targetLanguages}))}async voiceMessageToText(e,t){v_(e,t);const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>b_(this.getRestClient(r),r,e,t))}async voiceFileToText(e,t){I_(e,t);const r=this.getRestContextOrThrow(),s=this.getClientOrThrow().getUploadAdapter();if(!s)throw new ut("Upload capability is missing for current platform",ot.UPLOAD_REQUIRED_FIELD_MISSING);return this.executeRestOperation(()=>(async(e,t,r,s)=>{const n=I_(r,s),i=os({file:n,fallbackName:u_(n)?"voice.amr":void 0,fallbackMimeType:"audio/amr"});try{const r=await e.upload({url:`${t.restBaseUrl}${c_(t)}/speech/recognitions`,headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json",[_u]:bu()},source:i.source,fields:{username:t.userId,...s?.format?{format:s.format}:{},...void 0!==s?.sampleRate?{sampleRate:String(s.sampleRate)}:{},...void 0!==s?.bitsPerSample?{bitsPerSample:String(s.bitsPerSample)}:{},...void 0!==s?.channels?{channels:String(s.channels)}:{}}});let n=r.body;try{n=JSON.parse(r.body)}catch{n=r.body}if(r.status<200||r.status>=300)throw new ut("Voice-to-text failed",ot.VOICE_TO_TEXT_FAILED,{details:{httpStatus:r.status,rawResponse:n}});return{text:p_(n,"voiceFileToText")}}catch(o){if(o instanceof ut)throw y_(o);throw y_(Fd(o))}})(s,r,e,t))}validateConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType&&"chatRoom"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType")}validateUnreadConversationLocator(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType must be singleChat or groupChat","conversationType")}validateSendMessageReadReceiptsParams(e){if(this.requireNonEmptyString(e.conversationId,"conversationId"),"singleChat"!==e.conversationType&&"groupChat"!==e.conversationType)throw this.buildValidationError("conversationType is invalid","conversationType");if(e.messageIds.length>50)throw this.buildValidationError("messageIds cannot contain more than 50 items","messageIds");return this.validateMessageIdList(e.messageIds,"messageIds")}validateMessageIdList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError(`${t} cannot be empty`,t);return e.map((e,r)=>{if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t}.${r} is invalid`,`${t}.${r}`);return e.trim()})}resolveDownloadCombineMessageParams(e){if("message"in e){if("combine"!==e.message.type)throw new mt("message must be a combine message",{code:ot.VALIDATION_INVALID_FORMAT});const t=e.message.body;return{url:t.url??"",secret:t.secret,timeoutMs:e.timeoutMs,maxItems:e.maxItems}}return{url:e.url,secret:e.secret,timeoutMs:e.timeoutMs,maxItems:e.maxItems}}validateReactionParams(e){this.requireNonEmptyString(e.messageId,"messageId"),this.requireNonEmptyString(e.reaction,"reaction")}buildActionError(e,t){return e===ot.AUTH_NOT_LOGIN||e===ot.AUTH_UNAUTHORIZED?new pt(t??"authentication failed",{code:e}):e===ot.CONNECTION_WEBSOCKET_ERROR||e===ot.CONNECTION_TIMEOUT?new ht(t??"connection unavailable",{code:e}):107===e||110===e||205===e||500===e||e===ot.VALIDATION_REQUIRED||e===ot.VALIDATION_INVALID_FORMAT?new mt(t??"invalid parameter",{code:e}):e===ot.MESSAGE_RECALL_TIME_LIMIT?new ut(t??"message recall time limit reached",e):e===ot.MESSAGE_EDIT_FAILED?new ut(t??"message update failed",e):e===ot.OPERATION_UNSUPPORTED?new mt(t??"operation unsupported",{code:e}):new ut(t??"message action failed",e)}requireNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} is required`,t)}buildValidationError(e,t){return new mt(e,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:e,rule:"required"}]}})}getEventContextOrThrow(){if(!this.eventContext)throw new mt("ChatManager is not bound to event context",{code:ot.VALIDATION_REQUIRED});return this.eventContext}getClientOrThrow(){if(!this.client)throw new mt("ChatManager is not bound to client",{code:ot.VALIDATION_REQUIRED});return this.client}async prepareEditedTextBody(e,t,r){return(await wI({msgServerId:"",msgLocalId:"",from:t,to:r.conversationId,sender:{userId:t},conversationId:r.conversationId,conversationType:r.conversationType,type:"text",sendStatus:"sending",ext:{},timestamp:0,body:e},e=>{const t=this.getRestContextOrThrow();return this.executeRestOperation(()=>yI(this.getRestClient(t),t,e))})).body}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Cv(e.restBaseUrl,{errorMap:C_,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireConnectedClient(){const e=this.getClientOrThrow();if(e.getConnectionState()!==s)throw new ht("client is not connected",{code:ot.CONNECTION_WEBSOCKET_ERROR});return e}getCurrentUserIdOrThrow(){const e=this.getClientOrThrow().getCurrentUserId();if(!e)throw new pt("user is not logged in",{code:ot.AUTH_NOT_LOGIN});return e}buildMessageSenderOrThrow(){const e=this.getClientOrThrow(),t=this.getCurrentUserIdOrThrow(),r=e.getCacheManager()?.getUserInfoSummaries([t],!1)[0];return{userId:t,nickname:r?.nickname,avatarUrl:r?.avatarUrl}}async hydrateGroupMessageReadUsers(e,t){const r=this.getClientOrThrow();if(!r.isUserInfoSyncEnabled()||0===t.users.length)return t;const s=r.getCacheManager(),n=await Sb({groupId:e,users:t.users.map(e=>e.user),includeNameCard:!0,cacheManager:s,fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoReadCapability(r);return t?await t.getUserInfoByUserId({userIds:e}):[]},hydrateGroupNamecards:async(e,t)=>{const s=this.getGroupNamecardHydrationCapability(r);s&&await s.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))}});return this.dispatchFetchedUserInfoUpdates(r,n.fetchedUserInfos),{...t,users:t.users.map(e=>{const t=n.usersById.get(e.userId)??e.user;return{...e,user:t}})}}getUserInfoReadCapability(e){const t=e.getManagerByCapability("userInfo:read");return t&&"function"==typeof t.getUserInfoByUserId?t:null}getGroupNamecardHydrationCapability(e){const t=e.getManagerByCapability("group:namecard");return t&&"function"==typeof t.hydrateMessageProfileGroupNamecards?t:null}dispatchFetchedUserInfoUpdates(e,t){if(0===t.length)return;const r=e.getCurrentUserId(),s=t.find(e=>e.userId===r),n=t.filter(e=>e.userId!==r);s&&e.dispatchOwnInfoUpdated(s),e.dispatchUserInfoUpdated(n),t.length>0&&e.refreshConversationDisplayFromUserInfos(t.map(e=>({userId:e.userId})),"profile")}async executeRestOperation(e){try{return await e()}catch(t){throw this.mapRestError(t)}}mapRestError(e){return e instanceof mt||e instanceof pt||e instanceof ht||e instanceof lt?e:e instanceof vt?new lt(e.message,{code:e.code,details:e.details}):e instanceof It||e instanceof ut?e:new ut(String(e),ot.UNKNOWN)}};E_.key="chatManager";let w_=E_;class A_{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 R_=e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),N_=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),O_=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw R_(t);return e.trim()},M_=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw N_(t,`${t} must be a string`);return e},U_=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw N_(t,`${t} must be an integer between 1 and 50`);return e},L_=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},k_=e=>Uu(e)?e:null,D_=e=>{const t=k_(e);return t?.data??e},P_=e=>{const t=k_(e);if(Array.isArray(t?.entities))return t.entities;const r=D_(e);if(Array.isArray(r))return r;const s=k_(r);return Array.isArray(s?.entities)?s.entities:Array.isArray(s?.affiliations)?s.affiliations:[]},x_=e=>{const t=k_(e),r=k_(t?.data),s=k_(t?.properties);return("string"==typeof r?.cursor?r.cursor:void 0)??("string"==typeof s?.cursor?s.cursor:void 0)??("string"==typeof t?.cursor?t.cursor:void 0)??""},F_=e=>{const t=k_(e);if(!t)return null;const r=("string"==typeof t.id?t.id:void 0)??("string"==typeof t.msgId?t.msgId:void 0);if(!r)return null;const s="number"==typeof t.timestamp?t.timestamp:0,n=t.payload,i="string"==typeof n?Lu(n,{}):k_(n)??{},o=Array.isArray(i.bodies)?i.bodies:[];if(o.length>=2){const e=new vu("").composeThreadBodies(o);if("multi_body"===e?.type&&Array.isArray(e.body))return{msgId:r,type:"multi_body",body:e.body.map(e=>({...e})),timestamp:s}}const a=k_(o[0])??{};return{msgId:r,type:("string"==typeof a.type?a.type:void 0)??("string"==typeof i.type?i.type:void 0)??"",body:a,timestamp:s}},B_=e=>{const t=k_(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),s=("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),n="string"==typeof t.name?t.name:"";return r&&s&&n?{chatThreadId:r,parentId:s,name:n,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:F_(t.lastMessage??t.last_message)}:null},G_=e=>({items:P_(e).map(e=>B_(e)).filter(e=>null!==e),cursor:x_(e)}),q_=async(e,t,r)=>{const s=L_(t),n=O_(r,"chatThreadId");return(e=>{const t=D_(e),r=Array.isArray(t)?t[0]:t,s=B_(r);if(!s)throw N_("response.data","response.data is invalid");return s})(await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}`,{operation:"getChatThreadInfo"}))},$_=async(e,t,r)=>{const s=L_(t),n=O_(r.chatThreadId,"params.chatThreadId"),i=U_(r.pageSize,"params.pageSize"),o=M_(r.cursor,"params.cursor"),a=xv({limit:String(i),cursor:o}),c=await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users?${a.toString()}`,{operation:"getChatThreadMemberList"});return{items:P_(d=c).map(e=>{if("string"==typeof e)return{memberId:e};const t=k_(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:x_(d)};var d},j_=async(e,t,r)=>{const s=L_(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw R_("params.chatThreadIds");if(r.chatThreadIds.length>20)throw N_("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const n=r.chatThreadIds.map((e,t)=>O_(e,`params.chatThreadIds[${t}]`)),i=await e.post(`/${s.orgName}/${s.appName}/thread/message`,{threadIds:n},{operation:"getChatThreadLastMessageList"});return{items:P_(i).map(e=>{const t=k_(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:F_(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},V_=AI(RI,{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"]}}}}}),K_=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(e){const t=e.trim();if(0===t.length)throw new mt("chatThreadId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadId",message:"chatThreadId is required",rule:"required"}]}});const r=this.registry.get(t);if(r)return r;const s=new A_(t,this);return this.registry.set(t,s),s}async createChatThread(e){return this.runOperation("createChatThread",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=L_(t),n=O_(r.parentId,"params.parentId"),i=O_(r.name,"params.name"),o=O_(r.messageId,"params.messageId"),a=await e.post(`/${s.orgName}/${s.appName}/thread?resource=${s.encodedResource}`,{name:i,msg_id:o,group_id:n,owner:t.userId},{operation:"createChatThread"}),c=k_(D_(a)),d="string"==typeof c?.thread_id?c.thread_id:void 0;if(!d)throw N_("response.data.thread_id","response.data.thread_id is invalid");return{chatThreadId:d}})(this.getRestClient(t),t,e)})}async getChatThreadList(e){return this.runOperation("getChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=L_(t),n=O_(r.parentId,"params.parentId"),i=U_(r.pageSize,"params.pageSize"),o=M_(r.cursor,"params.cursor"),a=xv({limit:String(i),cursor:o}),c=await e.get(`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(n)}?${a.toString()}`,{operation:"getChatThreadList"});return G_(c)})(this.getRestClient(t),t,e)})}async getJoinedChatThreadList(e={}){return this.runOperation("getJoinedChatThreadList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r={})=>{const s=L_(t),n=U_(r.pageSize,"params.pageSize"),i=M_(r.cursor,"params.cursor"),o=xv({limit:String(n),cursor:i}),a="string"==typeof r.parentId&&r.parentId.trim().length>0?`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(r.parentId.trim())}/user/${s.encodedUserId}?${o.toString()}`:`/${s.orgName}/${s.appName}/threads/user/${s.encodedUserId}?${o.toString()}`,c=await e.get(a,{operation:"getJoinedChatThreadList"});return G_(c)})(this.getRestClient(t),t,e)})}async getChatThreadInfo(e){return this.runOperation("getChatThreadInfo",async()=>{const t=this.getRestContextOrThrow();return q_(this.getRestClient(t),t,e.chatThreadId)})}async joinChatThread(e){return this.runOperation("joinChatThread",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=L_(t),n=O_(r,"chatThreadId");await e.post(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/user/${s.encodedUserId}/join?resource=${s.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 s=L_(t),n=O_(r,"chatThreadId");await e.delete(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/user/${s.encodedUserId}/quit?resource=${s.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 s=L_(t),n=O_(r,"chatThreadId");await e.delete(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}?resource=${s.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 s=L_(t),n=O_(r.chatThreadId,"params.chatThreadId"),i=O_(r.name,"params.name");await e.put(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}?resource=${s.encodedResource}`,{name:i},{operation:"updateChatThreadName"})})(this.getRestClient(t),t,e)})}async getChatThreadMemberList(e){return this.runOperation("getChatThreadMemberList",async()=>{const t=this.getRestContextOrThrow();return $_(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=L_(t),n=O_(r.chatThreadId,"params.chatThreadId"),i=O_(r.memberId,"params.memberId");await e.delete(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users/${encodeURIComponent(i)}?resource=${s.encodedResource}`,{operation:"removeChatThreadMember"})})(this.getRestClient(t),t,e)})}async getChatThreadLastMessageList(e){return this.runOperation("getChatThreadLastMessageList",async()=>{const t=this.getRestContextOrThrow();return j_(this.getRestClient(t),t,e)})}getClientOrThrow(){if(!this.client)throw new mt("ChatThreadManager is not bound to client",{code:ot.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 mt("ChatThreadManager is not bound to event context",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"chatThreadManager.eventContext",message:"ChatThreadManager is not bound to event context",rule:"required"}]}});return this.eventContext}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Cv(e.restBaseUrl,{errorMap:V_,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}async runOperation(e,t){try{return await t()}catch(r){if(r instanceof ut)throw r;const t=r instanceof Error?r.message:String(r);throw new ut(`ChatThreadManager ${e} failed: ${t}`,ot.UNKNOWN)}}buildChatThreadPublicEvent(e){const t=e.payload,r="string"==typeof t.id?t.id:"",s="string"==typeof t.muc_parent_id?t.muc_parent_id:"";if(!r||!s)return null;const n="string"==typeof t.msg_parent_id?t.msg_parent_id:void 0,i="string"==typeof t.name?t.name:void 0,o="number"==typeof t.message_count?t.message_count:void 0,a=t.last_message&&"object"==typeof t.last_message?this.tryBuildThreadMessageSnippet(t.last_message):void 0,c="number"==typeof t.timestamp?t.timestamp:0,d="string"==typeof t.from?t.from:void 0,u={chatThreadId:r,parentId:s,name:i??"",messageId:n,messageCount:o,lastMessage:a};switch(t.operation){case"create":return{eventName:"onChatThreadCreated",payload:{chatThreadId:r,parentId:s,operatorId:d,chatThreadName:i,messageId:n,thread:u,timestamp:c}};case"update":case"update_msg":return{eventName:"onChatThreadUpdated",payload:{chatThreadId:r,parentId:s,operatorId:d,chatThreadName:i,messageId:n,messageCount:o,lastMessage:a,thread:u,timestamp:c}};case"delete":return{eventName:"onChatThreadDestroyed",payload:{chatThreadId:r,parentId:s,operatorId:d,timestamp:c}};case"kick":return{eventName:"onChatThreadUserRemoved",payload:{chatThreadId:r,parentId:s,operatorId:d,memberId:t.userIds?.[0],timestamp:c}};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}}};K_.key="chatThreadManager";let z_=K_;class H_{constructor(e,t){this.chatRoomId=e,this.manager=t}getInfo(){return this.manager.getChatRoomInfo({chatRoomId:this.chatRoomId})}refresh(){return this.getInfo()}updateInfo(e){return this.manager.updateChatRoomInfo({chatRoomId:this.chatRoomId,...e})}leaveChatRoom(){return this.manager.leaveChatRoom(this.toTarget())}getMembers(e={}){return this.manager.getMemberList({chatRoomId:this.chatRoomId,...e})}removeMembers(e){return this.manager.removeMembers(this.toUserBatchParams(e))}getAdminList(){return this.manager.getAdminList(this.toTarget())}addAdmin(e){return this.manager.addAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}removeAdmin(e){return this.manager.removeAdmin({chatRoomId:this.chatRoomId,userId:e.userId})}getMuteList(e){return this.manager.getMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteMembers({chatRoomId:this.chatRoomId,userIds:e.userIds,duration:e.duration})}unmuteMembers(e){return this.manager.unmuteMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllMembers(this.toTarget())}checkIfInMuteList(){return this.manager.checkIfInMuteList(this.toTarget())}getBlocklist(e){return this.manager.getBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInAllowList(this.toTarget())}getAnnouncement(){return this.manager.getAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateAnnouncement({chatRoomId:this.chatRoomId,announcement:e.announcement})}getAttributes(e={}){return this.manager.getAttributes({chatRoomId:this.chatRoomId,keys:e.keys})}setAttributes(e){return this.manager.setAttributes({chatRoomId:this.chatRoomId,attributes:e.attributes,autoDelete:e.autoDelete,isForced:e.isForced})}removeAttributes(e){return this.manager.removeAttributes({chatRoomId:this.chatRoomId,keys:e.keys,isForced:e.isForced})}toTarget(){return{chatRoomId:this.chatRoomId}}toUserBatchParams(e){return{chatRoomId:this.chatRoomId,userIds:e.userIds}}}const W_=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],J_=e=>{const t=[],r=new Set;for(const s of e){const e=s.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t},Q_=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Z_=e=>({userId:e}),Y_=(e,t,r)=>{const s={userId:r};for(const n of W_){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},X_=async(e,t)=>{const r=J_(e),s=new Map;if(0===r.length)return s;const n=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const o of n)s.set(o.userId,Q_(o));const i=r.filter(e=>!s.has(e));if(i.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:i});for(const t of e)s.set(t.userId,t)}for(const o of r)s.has(o)||s.set(o,Z_(o));return s},eT=e=>Uu(e)?e:null,tT=e=>"string"==typeof e?e:void 0,rT=e=>{const t=tT(e)?.trim();return t||void 0},sT=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&""!==e.trim()){const t=Number(e);return Number.isFinite(t)?t:void 0}},nT=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},iT=e=>{const t=eT(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},oT=e=>{const t=eT(e);return t?eT(t.data)?t.data:t:null},aT=(e,t)=>{const r=eT(e),s=r&&eT(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return sT(n[0])},cT=e=>rT(e.chatRoomId)??rT(e.chatroomid)??rT(e.id)??"",dT=e=>tT(e.name)??tT(e.title)??tT(e.groupname)??"",uT=e=>Z_(e),lT=(e,t)=>{const r=(e=>{const t=tT(e);return"owner"===t||"admin"===t||"member"===t||"none"===t?t:void 0})(e.permission);if(void 0!==r)return r;if(!t)return;if(rT(e.owner)===t)return"owner";const s=Array.isArray(e.affiliations)?e.affiliations:[];for(const n of s){const e=eT(n);if(e){if(rT(e.owner)===t)return"owner";if(rT(e.admin)===t)return"admin";if(rT(e.member)===t)return"member"}}},hT=(e,t)=>{const r=eT(e);if(!r)return null;const s=cT(r);if(!s)return null;const n=t?.stripOwnerAppKeyPrefix?(e=>{if(!e)return;const t=e.indexOf("_");return t<0?e:e.slice(t+1)})(rT(r.owner)):rT(r.owner);return{chatRoomId:s,name:dT(r),owner:n?uT(n):void 0,memberCount:sT(r.memberCount)??sT(r.affiliations_count),disabled:nT(r.disabled)}},pT=(e,t)=>{const r=(e=>{const t=eT(e);return t?sT(t.count):void 0})(e),s=iT(e).map(e=>hT(e,t)).filter(e=>null!==e),n=aT(e,"pagenum"),i=aT(e,"pagesize");return{items:s,pageNum:n,pageSize:i,total:r,hasMore:void 0!==r&&void 0!==n&&void 0!==i?n*i<r:void 0}},mT=e=>iT(e).map(e=>rT(e)).filter(e=>Boolean(e)).map(e=>uT(e)),gT=(e,t)=>{const r=oT(e)??{},s=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],n=eT(r.errorKeys)??{},i={};for(const[o,a]of Object.entries(n))"string"==typeof a&&(i[o]={code:yT(a),message:a});return{chatRoomId:t,appliedKeys:s,failedKeys:i}},fT=e=>{const t=eT(e),r=t?.data,s=Array.isArray(r)?r:void 0!==r?[r]:[],n=[],i=[];return s.forEach(e=>{const t=eT(e),r=(e=>{const t=eT(e);if(!t)return null;const r=rT(t.user),s=rT(t.chatRoomId)??rT(t.chatroomid)??rT(t.id),n=tT(t.action),i=nT(t.result);return r&&s&&void 0!==n&&void 0!==i?{chatRoomId:s,user:uT(r),action:n,reason:tT(t.reason),...i?{}:{reason:tT(t.reason)??"failed"}}:null})(e);if(!r||!t)return;nT(t.result)?n.push(r):i.push(r)}),{succeeded:n,failed:i}},yT=e=>e.includes("is exceeding maximum limit")||e.includes("size of metadata")&&e.includes("exceeds")?ot.SERVICE_LIMIT_EXCEEDED:e.includes("is not part of you")?ot.CHATROOM_PERMISSION_DENIED:e.includes("is not Legal")||e.includes("is not exist")?ot.VALIDATION_REQUIRED:ot.REST_BUSINESS_UNKNOWN,vT=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},IT=e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),bT=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),_T=(e,t)=>`/${e.orgName}/${e.appName}${t}`,TT=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw bT(t,`${t} must be a string`);return e}},CT=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw bT(t,`${t} must be a number`);return e}},ST=(e,t)=>{const r=xv();"number"==typeof e?.pageNum&&r.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&r.set("pagesize",String(e.pageSize));const s=r.toString();return s?`?${s}`:""},ET=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw IT(t);return e.trim()},wT=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw IT(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw bT(`${t}[${n}]`,`${t}[${n}] must be a string`);const i=e.trim();i&&!s.has(i)&&(s.add(i),r.push(i))}),0===r.length)throw IT(t);return r},AT=(e,t)=>wT(e,t),RT=async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=_T(s,`/chatrooms/${encodeURIComponent(n)}?joined_time=true&version=v3`);return((e,t)=>{const r=iT(e),s=eT(r[0])??oT(e)??{},n=hT(s)??{chatRoomId:cT(s),name:dT(s)},i=lT(s,t);return{...n,description:tT(s.description),maxMembers:sT(s.maxMembers)??sT(s.maxusers)??sT(s.max_users),createdAt:sT(s.createdAt)??sT(s.created),ext:tT(s.ext)??tT(s.custom),muteAllMembers:nT(s.mute),permissionType:i}})(await e.get(i,{operation:"getChatRoomInfo"}),t.userId)},NT=async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i={},o=TT(r.name,"params.name"),a=TT(r.description,"params.description"),c=CT(r.maxMembers,"params.maxMembers");if(void 0!==o&&(i.groupname=o),void 0!==a&&(i.description=a),void 0!==c&&(i.maxusers=c),0===Object.keys(i).length)throw IT("params");const d=_T(s,`/chatrooms/${encodeURIComponent(n)}?resource=${s.encodedResource}`);return(e=>{const t=oT(e)??{};return{nameUpdated:nT(t.groupname),descriptionUpdated:nT(t.description),maxMembersUpdated:nT(t.maxusers)}})(await e.put(d,i,{operation:"updateChatRoomInfo"}))},OT=async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=_T(s,`/chatrooms/${encodeURIComponent(n)}/users${(e=>{const t=xv();"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor);const r=t.toString();return r?`?${r}`:""})(r)}`);return(e=>{const t=[];for(const n of iT(e)){const e=eT(n);if(!e)continue;const r=rT(e.owner),s=rT(e.admin),i=rT(e.member),o=r??s??i;o&&t.push({user:uT(o),role:r?"owner":s?"admin":"member",joinedAt:sT(e.joinedAt)??sT(e.joined_time)})}const r=eT(e),s=r?rT(r.cursor):void 0;return{items:t,cursor:s,hasMore:"string"==typeof s&&s.length>0}})(await e.get(i,{operation:"getChatRoomMemberList"}))},MT=async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=_T(s,`/chatrooms/${encodeURIComponent(n)}/admin`),o=await e.get(i,{operation:"getChatRoomAdminList"});return mT(o)},UT=async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=xv();i.set("version","v3"),"number"==typeof r.pageNum&&i.set("pagenum",String(r.pageNum)),"number"==typeof r.pageSize&&i.set("pagesize",String(r.pageSize));const o=_T(s,`/chatrooms/${encodeURIComponent(n)}/mute?${i.toString()}`);return(e=>{const t=iT(e);if(t.every(e=>"string"==typeof e))return mT(e).map(e=>({user:e}));const r=[];for(const s of t){const e=eT(s);if(!e)continue;const t=rT(e.user)??rT(e.member)??rT(e.owner)??rT(e.admin);t&&r.push({user:uT(t),muteExpire:sT(e.muteExpire)??sT(e.expire)??sT(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(o,{operation:"getChatRoomMuteList"}))},LT=async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=_T(s,`/sdk/chatrooms/${encodeURIComponent(n)}/mute/${s.encodedUserId}?version=v3`);return(e=>{const t=oT(e)??{};return{muted:nT(t.muted)??nT(t.value)??Boolean(t.data),muteExpireAt:sT(t.muteExpireAt)??sT(t.expire)??sT(t.mute_expire)}})(await e.get(i,{operation:"isCurrentUserMutedInChatRoom"}))},kT=async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=ST(r),o=i?"&":"",a=_T(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users?version=v3${o}${i.replace("?","")}`),c=await e.get(a,{operation:"getChatRoomBlocklist"});return mT(c).map(e=>({user:e}))},DT=async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=_T(s,`/chatrooms/${encodeURIComponent(n)}/white/users`),o=await e.get(i,{operation:"getChatRoomAllowlist"});return mT(o).map(e=>({user:e}))},PT=async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=_T(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${s.encodedUserId}?version=v3`);return(e=>{const t=oT(e)??{};return nT(t.value)??nT(t.white)??!1})(await e.get(i,{operation:"checkIfInChatRoomAllowList"}))},xT=async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=_T(s,`/chatrooms/${encodeURIComponent(n)}/announcement`);return(e=>{const t=oT(e)??{};return{announcement:tT(t.announcement)??""}})(await e.get(i,{operation:"getChatRoomAnnouncement"}))},FT=async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=_T(s,`/metadata/chatroom/${encodeURIComponent(n)}`);return((e,t)=>{const r=oT(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(i,{keys:r.keys?AT(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),n)},BT=async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw bT(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw IT(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw bT(t,`${t} contains invalid key`);if("string"!=typeof r)throw bT(`${t}.${e}`,`${t}.${e} must be a string`);return[e,r]}))})(r.attributes,"params.attributes"),{autoDelete:o=!0,isForced:a=!1}=r,c=a?"/forced":"",d=_T(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${c}`),u=await e.put(d,{metaData:i,autoDelete:o?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return gT(u,n)},GT={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},qT=(e,t,r)=>new mt(e,{code:"required"===r?ot.VALIDATION_REQUIRED:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:e,rule:r}]}}),$T=(e,t)=>{if("string"!=typeof e)throw qT(`${t} must be a string`,t,"invalid_format");return e},jT=(e,t)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw qT(`${t} must be a string, number, or boolean`,t,"invalid_format")},VT=(e,t="attribute")=>{const r=GT[e];if(!r)throw qT(`${t} is invalid`,t,"invalid_format");return r},KT=(e,t="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw qT(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,i]of e.entries()){const e=$T(i,`${t}[${n}]`).trim();e&&(s.has(e)||(s.add(e),r.push(e)))}if(0===r.length)throw qT(`${t} is required`,t,"required");return r},zT=(e,t="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw qT(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,i]of e.entries()){const e=$T(i,`${t}[${n}]`);if(!(e in GT))throw qT(`${t}[${n}] is invalid`,`${t}[${n}]`,"invalid_format");s.has(e)||(s.add(e),r.push(e))}if(0===r.length)throw qT(`${t} is required`,t,"required");return r},HT=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}/metadata/user/get`},WT=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}/metadata/user/${encodeURIComponent(e.userId)}`},JT=e=>({targets:KT(e)}),QT=e=>!!Uu(e)&&("nickname"in e||"avatarurl"in e||"avatarUrl"in e||"mail"in e||"phone"in e||"gender"in e||"sign"in e||"birth"in e||"ext"in e),ZT=(e,t)=>{if(Array.isArray(e))for(const r of e){if(!Uu(r))continue;const e="string"==typeof r.username?r.username:"";e&&t.set(e,r)}},YT=(e,t)=>{const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r},XT=(e,t)=>{const r=(e=>{const t=new Map,r=Uu(e)?e:null;if(r?.data&&Uu(r.data))for(const[s,n]of Object.entries(r.data))QT(n)&&t.set(s,n);return ZT(r?.entities,t),ZT(r?.data&&Uu(r.data)?r.data.entities:void 0,t),t})(e),s=(e=>{const t=new Map,r=Uu(e)?e:null;if(!r?.lastModified||!Uu(r.lastModified))return t;for(const[s,n]of Object.entries(r.lastModified))"number"==typeof n&&t.set(s,n);return t})(e),n=[];for(const i of t){const e=r.get(i);e&&n.push({profile:YT(i,e),lastModified:s.get(i)})}return n},eC=(e,t)=>XT(e,t).map(e=>e.profile),tC=(e,t,r,s)=>{void 0!==r&&("gender"!==t?e.push([t,$T(r,s)]):e.push([t,String(jT(r,s))]))},rC=e=>e.map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"),sC={onChatRoomDestroyed:Se,onMembersJoined:Ee,onMembersExited:we,onRemovedFromChatRoom:Ae,onMuteListAdded:Re,onMuteListRemoved:Ne,onAllowListAdded:Oe,onAllowListRemoved:Me,onAllMemberMuteStateChanged:Ue,onAdminAdded:Le,onAdminRemoved:ke,onOwnerChanged:De,onAnnouncementChanged:Pe,onChatRoomInfoChanged:xe,onAttributesUpdate:Fe,onAttributesRemoved:Be},nC=AI(RI,{common:{},apis:{getChatRoomList:{range:"",errors:{}},getChatRoomInfo:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},updateChatRoomInfo:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},destroyChatRoom:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},joinChatRoom:{range:"4,705,704,707",errors:{exceed_limit:{code:4,httpStatus:403,retryable:!1},members_full:{code:704,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"member list is full"},user_in_blocklist:{code:707,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"is in the blacklist"},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},leaveChatRoom:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMemberList:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},addChatRoomMembers:{range:"110,204,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAdminList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAdmin:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeChatRoomAdmin:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomMuteList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteChatRoomMembers:{range:"110,210,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},muteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},unmuteAllChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},isCurrentUserMutedInChatRoom:{range:"705",errors:{resource_not_found:{code:705,runtimeMessage:"Chat room does not exist",httpStatus:404,retryable:!1,aliases:["30005"]}}},getChatRoomBlocklist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},blockChatRoomMembers:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},unblockChatRoomMembers:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAllowlist:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},addUsersToChatRoomAllowlist:{range:"204,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1},service_resource_not_found:{code:204,httpStatus:404,retryable:!1}}},removeUsersFromChatRoomAllowlist:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},checkIfInChatRoomAllowList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAnnouncement:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},updateChatRoomAnnouncement:{range:"110,210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},forbidden_op:{code:110,httpStatus:403,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomSharedFileList:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},deleteChatRoomSharedFile:{range:"210,705",errors:{group_authorization:{code:210,httpStatus:401,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},getChatRoomAttributes:{range:"110,705",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},resource_not_found:{code:705,httpStatus:404,retryable:!1}}},setChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},setChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttributes:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}},removeChatRoomAttribute:{range:"110,210,702,703,4",errors:{illegal_argument:{code:110,httpStatus:400,retryable:!1},chatroom_not_joined:{code:702,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60011},chatroom_permission_denied:{code:703,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60010},exceed_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60012},MetadataException:{code:210,httpStatus:401,retryable:!1}}}}}),iC=class{constructor(){this.capabilities=["rawNotify:chatroom"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.chatRoomRegistry=new Map}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){const r=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{const r=sC[e];return r&&t?[[r,t]]:[]}));this.eventContext?.addEventHandler(e,r)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("chatroom"!==e.type)return;const t=e.payload,r=await this.buildIncomingEventPayload(t.eventName,t);if(!r)return;const s=sC[t.eventName];s&&this.eventContext?.dispatch?.(s,r)}async buildIncomingEventPayload(e,t){const r=t.payload,s=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(e){case"onChatRoomDestroyed":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName};case"onMembersJoined":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),s),ext:r.ext};case"onMembersExited":return{chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,members:this.pickEventUsers(r.memberIds??(r.memberId?[r.memberId]:[]),s)};case"onRemovedFromChatRoom":return{reason:r.reasonCode??0,chatRoomId:r.chatRoomId,chatRoomName:r.chatRoomName,participant:this.pickEventUser(r.participantId,s)};case"onMuteListAdded":return{chatRoomId:r.chatRoomId,mutes:this.pickEventMuteEntries(r.userIds,r.muteExpire,s),muteExpire:r.muteExpire};case"onMuteListRemoved":return{chatRoomId:r.chatRoomId,mutes:this.pickEventUsers(r.userIds,s)};case"onAllowListAdded":case"onAllowListRemoved":return{chatRoomId:r.chatRoomId,allowlist:this.pickEventUsers(r.userIds,s)};case"onAllMemberMuteStateChanged":return{chatRoomId:r.chatRoomId,isMuted:Boolean(r.isMuted)};case"onAdminAdded":case"onAdminRemoved":return{chatRoomId:r.chatRoomId,admin:this.pickEventUser(r.adminId,s)};case"onOwnerChanged":return{chatRoomId:r.chatRoomId,newOwner:this.pickEventUser(r.newOwnerId,s),oldOwner:this.pickEventUser(r.oldOwnerId,s)};case"onAnnouncementChanged":return{chatRoomId:r.chatRoomId,announcement:r.announcement??""};case"onChatRoomInfoChanged":return{chatRoomId:r.chatRoomId,chatRoomInfo:await this.resolveChatRoomDetailForEvent(r)};case"onAttributesUpdate":return{chatRoomId:r.chatRoomId,attributes:r.attributes??{},from:this.pickEventUser(r.from,s)};case"onAttributesRemoved":return{chatRoomId:r.chatRoomId,keyList:r.keyList??[],from:this.pickEventUser(r.from,s)};default:return null}}async getChatRoomList(e={}){return this.runOperation("getChatRoomList",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r={})=>{const s=vT(t),n=_T(s,`/chatrooms${ST(r)}`),i=await e.get(n,{operation:"getChatRoomList"});return pT(i)})(this.getRestClient(t),t,e);return{...r,items:await this.hydrateSummaryOwners(r.items)}})}getChatRoom(e){this.requireClient();const t=e.trim();if(0===t.length)throw new mt("chatRoomId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"chatRoomId",message:"chatRoomId is required",rule:"required"}]}});const r=this.chatRoomRegistry.get(t);if(r)return r;const s=new H_(t,this);return this.chatRoomRegistry.set(t,s),s}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await RT(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return NT(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=ET(e.chatRoomId,"params.chatRoomId"),s=this.normalizeOptionalString(e.ext,"params.ext"),n=this.normalizeOptionalBoolean(e.leaveOtherRooms,"params.leaveOtherRooms");try{return(await t.sendChatRoomOperation({operation:"join",chatRoomId:r,ext:s,leaveOtherRooms:n})).chatRoomInfo??{}}catch(i){throw this.remapChatRoomOperationError("joinChatRoom",i)}})}async leaveChatRoom(e){return this.runOperation("leaveChatRoom",async()=>{const t=this.requireClient(),r=ET(e.chatRoomId,"params.chatRoomId");try{await t.sendChatRoomOperation({operation:"leave",chatRoomId:r})}catch(s){throw this.remapChatRoomOperationError("leaveChatRoom",s)}})}async getMemberList(e){return this.runOperation("getMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await OT(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(r.items)}})}async removeMembers(e){return this.runOperation("removeMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=wT(r.userIds,"params.userIds"),o=_T(s,`/chatrooms/${encodeURIComponent(n)}/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"removeChatRoomMembers"});return fT(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await MT(this.getRestClient(t),t,e);return this.hydrateUserInfos(r)})}async addAdmin(e){return this.runOperation("addAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=ET(r.userId,"params.userId"),o=_T(s,`/chatrooms/${encodeURIComponent(n)}/admin?resource=${s.encodedResource}`);await e.post(o,{newadmin:i},{operation:"setChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async removeAdmin(e){return this.runOperation("removeAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=ET(r.userId,"params.userId"),o=_T(s,`/chatrooms/${encodeURIComponent(n)}/admin/${encodeURIComponent(i)}?resource=${s.encodedResource}`);await e.delete(o,{operation:"removeChatRoomAdmin"})})(this.getRestClient(t),t,e)})}async getMuteList(e){return this.runOperation("getMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await UT(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async muteMembers(e){return this.runOperation("muteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=wT(r.userIds,"params.userIds"),o=CT(r.duration,"params.duration"),a=_T(s,`/chatrooms/${encodeURIComponent(n)}/mute?resource=${s.encodedResource}`);await e.post(a,{usernames:i,mute_duration:o},{operation:"muteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteMembers(e){return this.runOperation("unmuteMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=wT(r.userIds,"params.userIds"),o=_T(s,`/chatrooms/${encodeURIComponent(n)}/mute/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(o,{operation:"unmuteChatRoomMembers"})})(this.getRestClient(t),t,e)})}async muteAllMembers(e){return this.runOperation("muteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=_T(s,`/chatrooms/${encodeURIComponent(n)}/ban?resource=${s.encodedResource}`);await e.post(i,void 0,{operation:"muteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllMembers(e){return this.runOperation("unmuteAllMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=_T(s,`/chatrooms/${encodeURIComponent(n)}/ban?resource=${s.encodedResource}`);await e.delete(i,{operation:"unmuteAllChatRoomMembers"})})(this.getRestClient(t),t,e)})}async checkIfInMuteList(e){return this.runOperation("checkIfInMuteList",async()=>{const t=this.getRestContextOrThrow();return LT(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await kT(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async blockMembers(e){return this.runOperation("blockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=wT(r.userIds,"params.userIds"),o=1===i.length,a=_T(s,o?`/chatrooms/${encodeURIComponent(n)}/blocks/users/${encodeURIComponent(i[0]??"")}?resource=${s.encodedResource}`:`/chatrooms/${encodeURIComponent(n)}/blocks/users?resource=${s.encodedResource}`),c=await e.post(a,o?void 0:{usernames:i},{operation:"blockChatRoomMembers"});return fT(c)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async unblockMembers(e){return this.runOperation("unblockMembers",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=wT(r.userIds,"params.userIds"),o=_T(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"unblockChatRoomMembers"});return fT(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await DT(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(r)})}async addUsersToAllowlist(e){return this.runOperation("addUsersToAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=wT(r.userIds,"params.userIds"),o=_T(s,`/chatrooms/${encodeURIComponent(n)}/white/users?resource=${s.encodedResource}`),a=await e.post(o,{usernames:i},{operation:"addUsersToChatRoomAllowlist"});return fT(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async removeUsersFromAllowlist(e){return this.runOperation("removeUsersFromAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=wT(r.userIds,"params.userIds"),o=_T(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"removeUsersFromChatRoomAllowlist"});return fT(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return PT(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return xT(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=TT(r.announcement,"params.announcement");if(void 0===i)throw IT("params.announcement");const o=_T(s,`/chatrooms/${encodeURIComponent(n)}/announcement?resource=${s.encodedResource}`);await e.post(o,{announcement:i},{operation:"updateChatRoomAnnouncement"})})(this.getRestClient(t),t,e)})}async getAttributes(e){return this.runOperation("getAttributes",async()=>{const t=this.getRestContextOrThrow();return FT(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await BT(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async removeAttributes(e){return this.runOperation("removeAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=vT(t),n=ET(r.chatRoomId,"params.chatRoomId"),i=AT(r.keys,"params.keys"),{isForced:o=!1}=r,a=o?"/forced":"",c=_T(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${a}`),d=await e.request(c,{method:"DELETE",body:{keys:i},operation:"removeChatRoomAttributes"});return gT(d,n)})(this.getRestClient(t),t,e);return this.checkAttributeMutationResult(r)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Ks(`ChatRoomManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof ut?t:t instanceof Error?new ut(`ChatRoomManager ${e} failed: ${t.message}`,ot.UNKNOWN):new ut(`ChatRoomManager ${e} failed`,ot.UNKNOWN)}remapChatRoomOperationError(e,t){return t instanceof ut&&t.code===ot.GROUP_NOT_EXIST?new gt("Chat room does not exist",{code:ot.CHATROOM_NOT_EXIST,details:{...t.details,api:e,originalCode:t.code,canonicalCode:ot.CHATROOM_NOT_EXIST,retryable:!1}}):t}checkAttributeMutationResult(e){const t=Object.values(e.failedKeys);if(t.length>0&&0===e.appliedKeys.length){const[e]=t;if(e)throw new ut(e.message,e.code)}return e}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Cv(e.restBaseUrl,{errorMap:nC,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new ut("ChatRoomManager is not bound to client",ot.VALIDATION_REQUIRED);return this.client}normalizeOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw new mt(`${t} must be a string`,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:`${t} must be a string`,rule:"invalid_format"}]}});return e}}normalizeOptionalBoolean(e,t){if(void 0!==e){if("boolean"!=typeof e)throw new mt(`${t} must be a boolean`,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:`${t} must be a boolean`,rule:"invalid_format"}]}});return e}}getCacheManager(){return this.client?.getCacheManager()??null}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}async resolveUserInfoMap(e){return X_(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Ks("ChatRoomManager user info fetch failed",{userIds:e,error:r}),[]}}})}async hydrateUserInfos(e){return(async(e,t)=>{const r=J_(e),s=await X_(r,t);return r.map(e=>Y_(void 0,s.get(e),e))})(e.map(e=>e.userId),{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Ks("ChatRoomManager hydrate users failed",{userIds:e,error:r}),[]}}})}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=JT(e),s=await this.getRestClient(t).request(HT(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return eC(s,r.targets)}collectEventUserIds(e){const t=e.payload,r=[t.participantId,t.memberId,...t.memberIds??[],t.adminId,t.oldOwnerId,t.newOwnerId,t.from,...t.userIds??[]],s=[],n=new Set;for(const i of r){if("string"!=typeof i)continue;const e=i.trim();e&&!n.has(e)&&(n.add(e),s.push(e))}return s}pickEventUser(e,t){if(e)return Y_(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>Y_(void 0,t.get(e),e))}pickEventMuteEntries(e,t,r){return this.pickEventUsers(e,r).map(e=>({user:e,muteExpire:t}))}async resolveChatRoomDetailForEvent(e){if(e.shouldFetchChatRoomDetail)try{return await this.getChatRoomInfo({chatRoomId:e.chatRoomId})}catch(t){Ks("ChatRoomManager event detail fetch failed",{chatRoomId:e.chatRoomId,error:t})}return{chatRoomId:e.chatRoomId,name:e.chatRoomPatch?.name??e.chatRoomName??"",...e.chatRoomPatch??{}}}async hydrateEntriesWithUsers(e){const t=e.map(e=>e.user.userId),r=await this.resolveUserInfoMap(t);return e.map(e=>({...e,user:Y_(e.user,r.get(e.user.userId),e.user.userId)}))}async hydrateActionListResult(e){return{succeeded:await this.hydrateEntriesWithUsers(e.succeeded),failed:await this.hydrateEntriesWithUsers(e.failed)}}async hydrateSummaryOwners(e){const t=e.map(e=>e.owner?.userId).filter(e=>"string"==typeof e),r=await this.resolveUserInfoMap(t);return e.map(e=>e.owner?.userId?{...e,owner:Y_(e.owner,r.get(e.owner.userId),e.owner.userId)}:e)}async hydrateChatRoomDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveUserInfoMap([e.owner.userId]);return{...e,owner:Y_(e.owner,t.get(e.owner.userId),e.owner.userId)}}};iC.key="chatRoomManager";let oC=iC;const aC={common:{},apis:{getContactList:{range:"",errors:{}},addContact:{range:"110,204,210,1000,1001,1002",localErrors:{addContact:{validation_invalid:{code:110,retryable:!1},cannot_add_self:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},ALREADY_FRIEND:{code:1e3,retryable:!1},BLOCKED_BY_USER:{code:210,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},deleteContact:{range:"110,204",localErrors:{deleteContact:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},acceptContactInvite:{range:"110,204,1001,1002",localErrors:{acceptContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1},CONTACT_REACH_LIMIT:{code:1001,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Inviter's contact max count"},CONTACT_REACH_LIMIT_PEER:{code:1002,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"Invitee's contact max count"}}},declineContactInvite:{range:"110,204",localErrors:{declineContactInvite:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_FOUND:{code:204,httpStatus:404,retryable:!1}}},setContactRemark:{range:"4,110,221",localErrors:{setContactRemark:{validation_invalid:{code:110,retryable:!1}}},errors:{USER_NOT_ON_ROSTER:{code:221,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"please add as a friend first"},remark_length_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"remark length must less than"}}},getBlocklist:{range:"",errors:{}},addUsersToBlocklist:{range:"4,110,204",localErrors:{addUsersToBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{service_resource_not_found:{code:204,httpStatus:404,retryable:!1},blocklist_limit_exceeded:{code:4,httpStatus:400,retryable:!1,matchField:"error_description",matchPattern:"almost reached or been greater than the upper range"}}},removeUserFromBlocklist:{range:"110",localErrors:{removeUserFromBlocklist:{validation_invalid:{code:110,retryable:!1}}},errors:{}}}},cC="User ID is invalid: cannot add yourself as a contact",dC=(e,t,r)=>{if(!Uu(e)||!Uu(e.data))return;const s=e.data[t];if(Array.isArray(s))for(const n of s)if(Uu(n)&&"string"==typeof n.failReason&&n.failReason.toLowerCase().includes(r))return n.failReason},uC=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},lC=e=>Uu(e)&&Array.isArray(e.data)?e.data.filter(e=>"string"==typeof e&&e.length>0):Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[],hC=(e,t)=>{if(!Array.isArray(e.userIds)||0===e.userIds.length)throw new mt(`${t} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}});const r=e.userIds.map((e,r)=>{if("string"!=typeof e)throw new mt(`${t}[${r}] must be a string`,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:`${t}[${r}]`,message:"userId must be a string",rule:"invalid_format"}]}});return e.trim()}),s=(e=>{const t=[],r=new Set;for(const s of e)s&&!r.has(s)&&(r.add(s),t.push(s));return t})(r);if(0===s.length)throw new mt(`${t} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}});return s.length!==r.length&&Uu(e),s},pC=async(e,t,r)=>{const s=uC(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/apply?resource=${s.encodedResource}`;(e=>{const t=dC(e,"applyYourselfUsers","user cannot apply to become a new friend");if(t)throw new mt(cC,{code:ot.VALIDATION_INVALID_FORMAT,details:{api:"addContact",mapped:!0,reasonKey:"cannot_add_self",serverMessage:t,retryable:!1,canonicalCode:ot.VALIDATION_INVALID_FORMAT,fields:[{path:"params.userId",message:cC,rule:"invalid_format"}]}});const r=dC(e,"notExistUsers","the users not exist");if(!r)return;const s=Iv(aC,"addContact",{error:"USER_NOT_FOUND"});if(!s)throw bv({apiName:"addContact",serverMessage:r,mapped:!1,reasonKey:"USER_NOT_FOUND"});throw bv({apiName:"addContact",entry:s.entry,serverMessage:r,mapped:!0,reasonKey:s.reasonKey,matchedBy:s.matchedBy})})(await e.post(n,{usernames:[r.userId],reason:r.message??""},{operation:"addContact"}))},mC=async(e,t)=>{const r=uC(t),s=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/blocks/users`,n=await e.get(s,{operation:"getBlocklist"});return lC(n).map(e=>({userId:e}))},gC=async(e,t,r)=>{const s=uC(t),n=`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/blocks?resource=${s.encodedResource}`,i=await e.post(n,{usernames:r},{operation:"addUsersToBlocklist"});return{succeeded:lC(i).map(e=>({userId:e})),failed:[]}},fC={nested:{easemob:{nested:{imfusion:{nested:{gateway:{nested:{v1:{nested:{MessageType:{values:{MESSAGE_TYPE_UNSPECIFIED:0,MESSAGE_TYPE_PING:1,MESSAGE_TYPE_PONG:2,MESSAGE_TYPE_ROSTER_REQUEST:3,MESSAGE_TYPE_ROSTER_RESPONSE:4,MESSAGE_TYPE_ERROR:5}},ServerStatus:{values:{SERVER_STATUS_OK:0,SERVER_STATUS_BUSY:1}},RosterResponseType:{values:{ROSTER_RESPONSE_TYPE_UNSPECIFIED:0,ROSTER_RESPONSE_TYPE_INCREMENTAL:1,ROSTER_RESPONSE_TYPE_FULL:2}},BaseMessage:{fields:{type:{type:"MessageType",id:1}}},GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},requestId:{type:"string",id:3},protocolVersion:{type:"int32",id:4}}},PingRequest:{fields:{type:{type:"MessageType",id:1}}},PongResponse:{fields:{type:{type:"MessageType",id:1},status:{type:"ServerStatus",id:2}}},ErrorDetail:{fields:{type:{type:"MessageType",id:1},code:{type:"string",id:2},message:{type:"string",id:3},header:{type:"GatewayHeader",id:4}}},GetRosterRequest:{fields:{type:{type:"MessageType",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},version:{type:"string",id:6},cursor:{type:"uint64",id:7}}},RosterItem:{fields:{contact:{type:"string",id:1},remark:{type:"string",id:2},metadata:{type:"string",id:3},createdAt:{type:"int64",id:4},updatedAt:{type:"int64",id:5},metadataUpdatedAt:{type:"int64",id:6}}},GetRosterResponse:{fields:{type:{type:"MessageType",id:1},header:{type:"GatewayHeader",id:2},data:{rule:"repeated",type:"RosterItem",id:3},cursor:{type:"uint64",id:4},version:{type:"string",id:5},responseType:{type:"RosterResponseType",id:6}}}}}}}}}}}}};let yC=!1,vC=null;const IC=()=>vC||(yC||(fa.util.Long=Pn,fa.configure(),yC=!0),Ka(),vC=fa.Root.fromJSON(fC),Va(vC),vC),bC=e=>"number"==typeof e?e:Pn.isLong(e)?e.toNumber():0,_C=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:bC(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:bC(t.protocolVersion)}};class TC{encodeRequest(e){const t=IC().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=$I){const t=IC().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:FI,status:e})).finish()}decode(e){const t=IC(),r=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(r.type){case xI:return{type:xI};case FI:{const r=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:FI,status:bC(r.status)}}case GI:{const r=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:GI,header:_C(r.header),data:Array.isArray(r.data)?r.data.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{contact:"string"==typeof t.contact?t.contact:"",remark:"string"==typeof t.remark?t.remark:"",metadata:"string"==typeof t.metadata?t.metadata:"",createdAt:bC(t.createdAt),updatedAt:bC(t.updatedAt),metadataUpdatedAt:bC(t.metadataUpdatedAt)}})(e)):[],cursor:bC(r.cursor),version:"string"==typeof r.version?r.version:"",responseType:bC(r.responseType)||jI}}case qI:{const r=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:qI,header:_C(r.header),code:"string"==typeof r.code?r.code:"",message:"string"==typeof r.message?r.message:"Unknown roster error"}}default:return{type:"number"==typeof r.type?r.type:PI}}}}class CC{constructor(e){this.pages=[],this.responseType=null,this.version="",this.nextCursor=0,this.pageCount=0,this.completed=!1,this.requestId=e}push(e){const t=e.header?.requestId;if(t&&t!==this.requestId)throw new ut("Roster response requestId mismatched",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",expectedRequestId:this.requestId,receivedRequestId:t}});if(this.completed)throw new ut("Roster response received after completion",ot.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:e.cursor}});if(null!==this.responseType&&this.responseType!==e.responseType)throw new ut("Roster response type changed in same session",ot.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.responseType,received:e.responseType}});if(this.pages.length>0&&0!==e.cursor&&e.cursor===this.pages[this.pages.length-1]?.cursor)throw new ut("Roster cursor duplicated",ot.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:e.cursor}});return this.responseType=e.responseType,this.version=e.version||this.version,this.pages.push(e),this.nextCursor=e.cursor,this.pageCount+=1,this.completed=0===e.cursor,{done:this.completed,nextCursor:this.nextCursor,pageCount:this.pageCount}}getNextCursor(){return this.nextCursor}getPageCount(){return this.pageCount}hasPages(){return this.pages.length>0}isCompleted(){return this.completed}buildResult(){return{mode:this.responseType===VI?"incremental":"full",version:this.version,pages:this.pages}}}const SC=e=>e.type===GI,EC=e=>"message"in e&&"code"in e;class wC{constructor(e){this.codec=new TC,this.sharedSession=e}async sync(e){const t=new CC(e.request.header.requestId);return await this.syncWithSharedSession(e.request,t)}cancel(){this.sharedSession.cancel("contact-sync-cancelled")}async syncWithSharedSession(e,t){return await this.sharedSession.request({dataType:"contact",label:"Roster sync",requestId:e.header.requestId,encode:()=>{const r=this.buildAttemptRequest(e,t.getNextCursor());return this.codec.encodeRequest(r)},decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:SC(t)||EC(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(e,r)=>{try{if(e.type===xI)return void(await r.send(this.codec.encodePong()));if(SC(e)){if(!t.push(e).done)return;return{done:!0,result:t.buildResult()}}if(EC(e))throw(e=>{const t=e.header?.requestId,r=r=>({stage:"sync_page",serverCode:e.code,requestId:t,retryable:r});switch(Number.parseInt(e.code,10)){case zI:return new pt(e.message,{code:ot.AUTH_UNAUTHORIZED,details:r(!1)});case HI:return new ut(e.message,ot.SERVICE_LIMIT_EXCEEDED,{details:r(!0)});case KI:return new ut(e.message,ot.VALIDATION_REQUIRED,{details:r(!1)});case WI:return new ut(e.message,ot.VALIDATION_INVALID_FORMAT,{details:r(!1)});case JI:return new ut(e.message,ot.REST_BUSINESS_UNKNOWN,{details:r(!0)});case QI:return new ut(e.message,ot.CONTACT_SYNC_SOCKET_FAILED,{details:r(!1)});default:return new ut(e.message,ot.CONTACT_SYNC_SOCKET_FAILED,{details:r(!0)})}})(e);return}catch(s){throw s instanceof ut?s:new ut("Roster frame decode failed",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:s instanceof Error?s.message:String(s)}})}}})}buildAttemptRequest(e,t){return{...e,cursor:t,header:{...e.header,timestamp:Date.now(),requestId:e.header.requestId}}}}const AC=e=>e.versionState.version?"incremental":"full",RC=e=>{const{metadata:t,metadataFailed:r,state:s}=e,n=s.versionState.version;return r||!t?{decision:"complete"===s.cacheMeta.cacheIntegrity?AC(s):"full",version:n}:t.requiresSync||"complete"!==s.cacheMeta.cacheIntegrity?t.requiresSync&&"complete"===s.cacheMeta.cacheIntegrity&&n?{decision:"incremental",version:t.version||n}:{decision:"full",version:t.version||n}:{decision:"skip",version:t.version||n}},NC=e=>{if(!e)return{};try{const t=JSON.parse(e);return{nickname:"string"==typeof t.nickname?t.nickname:void 0,avatarUrl:"string"==typeof t.avatarUrl?t.avatarUrl:"string"==typeof t.avatarurl?t.avatarurl:void 0,sign:"string"==typeof t.sign?t.sign:void 0,ext:"string"==typeof t.ext?t.ext:void 0}}catch{return{}}},OC=e=>{const t=(e=>{if(!(e instanceof ut&&e.details))return null;const t=e.details.httpStatus;return"number"==typeof t?t:null})(e);return 401===t||403===t||404===t},MC=(e,t,r,s)=>({code:t,stage:e,message:`${e}: ${r}`,retryable:s}),UC=e=>{Ks("Contact sync duration",e)};class LC{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("contact-sync-cancelled")}async runSync(){const e=this.dependencies.getContextState(),t=Date.now();let r;this.dependencies.onStart();try{const s=await this.dependencies.queryMetadata(e.versionState.version);if(r=RC({metadata:s,state:e}),"skip"===r.decision)return this.dependencies.onFinish(),void UC({outcome:"skip",decision:r.decision,durationMs:Date.now()-t,version:r.version,hasUsableSnapshot:e.cachedSnapshot.complete})}catch(s){if(OC(s)){const r=RC({metadataFailed:!0,state:e}),n=s instanceof ut?s:new ut("Contact metadata request failed",ot.CONTACT_SYNC_METADATA_FAILED,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:MC("metadata",n.code,n.message,!1)}),void UC({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:e.versionState.version,stage:"metadata",hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}if(r=RC({metadataFailed:!0,state:e}),e.cachedSnapshot.complete)return this.dependencies.onFinish({error:MC("metadata",ot.CONTACT_SYNC_METADATA_FAILED,s instanceof Error?s.message:String(s),!0)}),void UC({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:r.version,stage:"metadata",hasUsableSnapshot:!0,source:e.cachedSnapshot.source})}try{const s=await this.dependencies.getSyncUrls(),n=this.dependencies.buildRosterRequest({decision:r.decision,version:e.versionState.version}),i=await new wC(this.dependencies.getSharedSyncSession()).sync({urls:s,request:n}),o=(e=>{const t=[];for(const r of e)for(const e of r.data){const r=NC(e.metadata);t.push({relation:{userId:e.contact,remark:e.remark,sign:r.sign??"",addTs:e.createdAt,updatedAt:e.updatedAt,metadataUpdatedAt:e.metadataUpdatedAt},userInfo:{userId:e.contact,nickname:r.nickname,avatarUrl:r.avatarUrl,sign:r.sign,ext:r.ext}})}return t})(i.pages),a=this.dependencies.applySyncResult({mode:i.mode,relations:o.map(e=>e.relation),userInfos:o.map(e=>e.userInfo),version:i.version,lastSyncTs:Date.now()});this.dependencies.onFinish(),UC({outcome:"finish",decision:r.decision,durationMs:Date.now()-t,version:i.version,source:"sync",changed:a.changed,hasUsableSnapshot:a.snapshot.complete})}catch(s){const n=s instanceof ut?s:new ut("Contact sync failed",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"sync_page",cause:s instanceof Error?s.message:String(s)}}),i=n.details??{},o="string"==typeof i.stage?i.stage:"sync_page";this.dependencies.onFinish({error:MC(o,n.code,n.message,!0)}),UC({outcome:"fail",decision:r.decision,durationMs:Date.now()-t,version:r.version,stage:o,hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}}}const kC={items:[],loaded:!1,source:"server"},DC=AI(RI,aC),PC=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=kC,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=kC,this.blocklistSessionKey=null}getContacts(){return this.client?.getContactSnapshot()?.items??[]}async addContact(e){return this.runOperation("addContact",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.validateOptionalString(e.message,"params.message"),s=this.getRestContextOrThrow();if(t===s.userId)throw this.buildValidationError(cC,[{path:"params.userId",message:cC,rule:"invalid_format"}]);const n=this.getRestClient(s);Vs("ContactManager addContact",{userId:t,hasMessage:"string"==typeof r&&r.length>0}),await pC(n,s,{userId:t,message:r})})}async deleteContact(e){return this.runOperation("deleteContact",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);Vs("ContactManager deleteContact",{userId:t}),await(async(e,t,r)=>{const s=uC(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.delete(n,{operation:"deleteContact"})})(s,r,{userId:t});const n=this.client?.getCacheManager()?.removeContact(t);Vs("ContactManager deleteContact patched cache",{userId:t,changed:n?.changed??!1})})}async acceptContactInvite(e){return this.runOperation("acceptContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);Vs("ContactManager acceptContactInvite",{userId:t}),await(async(e,t,r)=>{const s=uC(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/accept/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.post(n,void 0,{operation:"acceptContactInvite"})})(s,r,{userId:t}),await this.requireClient().refreshContactSnapshot()})}async declineContactInvite(e){return this.runOperation("declineContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.getRestContextOrThrow(),s=this.getRestClient(r);Vs("ContactManager declineContactInvite",{userId:t}),await(async(e,t,r)=>{const s=uC(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/decline/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.post(n,void 0,{operation:"declineContactInvite"})})(s,r,{userId:t})})}async setContactRemark(e){return this.runOperation("setContactRemark",async()=>{const t=this.validateUserId(e.userId,"params.userId"),r=this.validateRemark(e.remark,"params.remark"),s=this.getRestContextOrThrow(),n=this.getRestClient(s);Vs("ContactManager setContactRemark",{userId:t,remarkLength:r.length}),await(async(e,t,r)=>{const s=uC(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/users/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`;await e.put(n,{remark:r.remark},{operation:"setContactRemark"})})(n,s,{userId:t,remark:r});const i=this.client?.getCacheManager()?.updateContactRemark(t,r);this.client?.refreshConversationDisplayFromUserInfos([{userId:t}],"profile"),Vs("ContactManager setContactRemark patched cache",{userId:t,changed:i?.changed??!1})})}async getBlocklist(){return this.runOperation("getBlocklist",async()=>{const e=this.getRestContextOrThrow();this.ensureBlocklistSession(e);const t=this.getRestClient(e);if(this.blocklistSnapshot.loaded)return this.blocklistSnapshot.items;const r=await this.enrichBlocklistUsers(await mC(t,e));return this.blocklistSnapshot={items:r,loaded:!0,source:"server"},Vs("ContactManager getBlocklist",{count:r.length}),r})}async addUsersToBlocklist(e){return this.runOperation("addUsersToBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const r=hC(e,"params.userIds"),s=this.getRestClient(t);Vs("ContactManager addUsersToBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length});const n=await gC(s,t,r),i=await this.enrichBlocklistUsers(n.succeeded);return this.blocklistSnapshot=this.patchBlocklistSnapshotWithAdditions(i),{succeeded:i,failed:await this.enrichBlocklistUsers(n.failed)}})}async removeUserFromBlocklist(e){return this.runOperation("removeUserFromBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const r=hC(e,"params.userIds"),s=this.getRestClient(t);Vs("ContactManager removeUserFromBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length}),await(async(e,t,r)=>{const s=uC(t),n=`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/blocks?resource=${s.encodedResource}`;await e.request(n,{method:"DELETE",body:{usernames:r},operation:"removeUserFromBlocklist"})})(s,t,r),this.blocklistSnapshot=this.patchBlocklistSnapshotWithRemovals(r)})}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Ks(`ContactManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof ut?t:t instanceof Error?new ut(`ContactManager ${e} failed: ${t.message}`,ot.UNKNOWN):new ut(`ContactManager ${e} failed`,ot.UNKNOWN)}requireClient(){if(!this.client)throw this.buildValidationError("ContactManager is not bound to client",[{path:"contactManager.client",message:"ContactManager is not bound to client",rule:"required"}]);return this.client}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Cv(e.restBaseUrl,{errorMap:DC,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}ensureBlocklistSession(e){const t=`${e.restBaseUrl}:${e.userId}:${e.token}`;this.blocklistSessionKey!==t&&(this.blocklistSessionKey=t,this.blocklistSnapshot=kC)}patchBlocklistSnapshotWithAdditions(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const r of e)t.set(r.userId,r);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}patchBlocklistSnapshotWithRemovals(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const r of e)t.delete(r);return{items:Array.from(t.values()),loaded:this.blocklistSnapshot.loaded,source:"mutation_patch"}}validateUserId(e,t){if("string"!=typeof e)throw this.buildValidationError("userId must be a string",[{path:t,message:"userId must be a string",rule:"invalid_format"}]);const r=e.trim();if(!r)throw this.buildValidationError("userId is required",[{path:t,message:"userId is required",rule:"required"}]);return r}validateOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw this.buildValidationError(`${t} must be a string`,[{path:t,message:`${t} must be a string`,rule:"invalid_format"}]);return e}}validateRemark(e,t){if("string"!=typeof e)throw this.buildValidationError("remark must be a string",[{path:t,message:"remark must be a string",rule:"invalid_format"}]);return e}buildValidationError(e,t){const r=t.some(e=>"invalid_format"===e.rule)?ot.VALIDATION_INVALID_FORMAT:ot.VALIDATION_REQUIRED;return new mt(e,{code:r,details:{fields:t}})}async enrichBlocklistUsers(e){if(0===e.length||!this.requireClient().isUserInfoSyncEnabled())return e;const t=await UI(e.map(e=>e.userId),{cacheManager:this.requireClient().getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchUserInfos(e)});return e.map(e=>t.get(e.userId)??e)}async fetchUserInfos(e){if(0===e.length)return[];try{const t=this.getUserInfoManager();return t?await t.getUserInfoByUserId({userIds:e}):await this.fetchUserInfosFromRest(e)}catch(t){return Ks("ContactManager user info fetch failed",{userIds:e,error:t}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=JT(e),s=await this.getRestClient(t).request(HT(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return eC(s,r.targets)}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}createSyncController(e){return new LC(e)}};PC.key="contactManager";let xC=PC;class FC{constructor(e,t){this.groupId=e,this.manager=t}getSummary(){return this.manager.getGroupSummaryForHandle(this.groupId)}getDetail(){return this.manager.getGroupDetailForHandle(this.groupId)}refresh(){return this.manager.refreshGroupDetailForHandle(this.groupId)}updateInfo(e){return this.manager.updateGroupInfo({groupId:this.groupId,...e})}updateConfigs(e){return this.manager.updateGroupInfo({groupId:this.groupId,...e})}changeOwner(e){return this.manager.changeGroupOwner({groupId:this.groupId,newOwner:e.newOwner})}destroy(){return this.manager.destroyGroup(this.toTarget())}leave(){return this.manager.leaveGroup(this.toTarget())}getMembers(e={}){return this.manager.getGroupMemberList({groupId:this.groupId,...e})}removeMembers(e){return this.manager.removeGroupMembers(this.toUserBatchParams(e))}getAdmins(){return this.manager.getGroupAdminList(this.toTarget())}addAdmin(e){return this.manager.addGroupAdmin({groupId:this.groupId,userId:e.userId})}removeAdmin(e){return this.manager.removeGroupAdmin({groupId:this.groupId,userId:e.userId})}getMuteList(e){return this.manager.getGroupMuteList({...this.toTarget(),...e})}muteMembers(e){return this.manager.muteGroupMembers({groupId:this.groupId,userIds:e.userIds,muteDuration:e.muteDuration})}unmuteMembers(e){return this.manager.unmuteGroupMembers(this.toUserBatchParams(e))}muteAllMembers(){return this.manager.muteAllGroupMembers(this.toTarget())}unmuteAllMembers(){return this.manager.unmuteAllGroupMembers(this.toTarget())}getBlocklist(e){return this.manager.getGroupBlocklist({...this.toTarget(),...e})}blockMembers(e){return this.manager.blockGroupMembers(this.toUserBatchParams(e))}unblockMembers(e){return this.manager.unblockGroupMembers(this.toUserBatchParams(e))}getAllowlist(){return this.manager.getGroupAllowlist(this.toTarget())}addUsersToAllowlist(e){return this.manager.addUsersToGroupAllowlist(this.toUserBatchParams(e))}removeUsersFromAllowlist(e){return this.manager.removeUsersFromGroupAllowlist(this.toUserBatchParams(e))}checkIfInAllowList(){return this.manager.checkIfInGroupAllowList({groupId:this.groupId})}checkIfInMuteList(){return this.manager.checkIfInGroupMuteList(this.toTarget())}getAnnouncement(){return this.manager.getGroupAnnouncement(this.toTarget())}updateAnnouncement(e){return this.manager.updateGroupAnnouncement({groupId:this.groupId,announcement:e.announcement})}getSharedFileList(e={}){return this.manager.getGroupSharedFileList({groupId:this.groupId,...e})}uploadSharedFile(e){return this.manager.uploadGroupSharedFile({groupId:this.groupId,...e})}deleteSharedFile(e){return this.manager.deleteGroupSharedFile({groupId:this.groupId,fileId:e.fileId})}downloadSharedFile(e){return this.manager.downloadGroupSharedFile({groupId:this.groupId,...e})}setMemberAttributes(e){return this.manager.setGroupMemberAttributes({groupId:this.groupId,userId:e.userId,memberAttributes:e.memberAttributes})}getMembersAttributes(e){return this.manager.getGroupMembersAttributes({groupId:this.groupId,userIds:e.userIds,keys:e.keys})}toTarget(){return{groupId:this.groupId}}toUserBatchParams(e){return{groupId:this.groupId,userIds:e.userIds}}}const BC=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},GC=e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),qC=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),$C=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw GC(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw qC(`${t}[${n}]`,`${t}[${n}] must be a string`);const i=e.trim();i&&!s.has(i)&&(s.add(i),r.push(i))}),0===r.length)throw GC(t);return r},jC=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw GC(t);return e.trim()},VC=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw qC(t,`${t} must be a string`);return e}},KC=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw qC(t,`${t} must be a boolean`);return e}},zC=(e,t)=>`/${e.orgName}/${e.appName}${t}`,HC=new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),WC=e=>{const t=xv();"number"==typeof e?.pageNum&&t.set("pagenum",String(e.pageNum)),"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize));const r=t.toString();return r?`?${r}`:""},JC=async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups?resource=${s.encodedResource}`);return(e=>{const t=Vu(e),r=Bu(t[0]),s=Ku(e)??r;return{groupId:s&&Wu(s)||r&&Wu(r)||""}})(await e.post(n,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?$C(r.memberIds,"params.memberIds"):[],public:r.public,approval:r.joinApprovalRequired,allowinvites:r.allowInvites,invite_need_confirm:r.inviteNeedConfirm,maxusers:r.maxMembers,custom:r.ext,avatar:r.avatar},{operation:"createGroup"}))},QC=async(e,t,r)=>{const s=BC(t),n=jC(r.groupId,"params.groupId"),i=zC(s,`/chatgroups/${encodeURIComponent(n)}?joined_time=true&version=v3`),o=await e.get(i,{operation:"getGroupInfo"});return Qu(o)},ZC=async(e,t,r)=>{const s=BC(t),n=jC(r.groupId,"params.groupId"),i={},o=VC(r.name,"params.name"),a=VC(r.description,"params.description"),c=VC(r.avatar,"params.avatar"),d=VC(r.ext,"params.ext"),u=KC(r.public,"params.public"),l=KC(r.joinApprovalRequired,"params.joinApprovalRequired"),h=KC(r.allowInvites,"params.allowInvites"),p=KC(r.inviteNeedConfirm,"params.inviteNeedConfirm"),m=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw qC(t,`${t} must be a number`);return e}})(r.maxMembers,"params.maxMembers");if(void 0!==o&&(i.groupname=o),void 0!==a&&(i.description=a),void 0!==c&&(i.avatar=c),void 0!==d&&(i.custom=d),void 0!==u&&(i.public=u),void 0!==l&&(i.membersonly=l),void 0!==h&&(i.allowinvites=h),void 0!==p&&(i.invite_need_confirm=p),void 0!==m&&(i.maxusers=m),0===Object.keys(i).length)throw GC("params");const g=zC(s,`/chatgroups/${encodeURIComponent(n)}?resource=${s.encodedResource}&version=v3`);await e.put(g,i,{operation:"updateGroupInfo"})},YC=async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/users${(e=>{const t=xv();return"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor),t.set("version","v3"),`?${t.toString()}`})(r)}`);return(e=>{const t=[];for(const i of Vu(e)){const e=Bu(i);if(!e)continue;const r=qu(e.owner),s=qu(e.admin),n=qu(e.member),o=r??s??n;if(!o)continue;const a=$u(e.joinedAt)??$u(e.joined_time);t.push({user:Zu(o),role:r?"owner":s?"admin":"member",...void 0===a?{}:{joinedAt:a}})}const r=zu(e,"pagenum"),s=zu(e,"pagesize"),n=Hu(e,s);return{items:t,pageNum:r,pageSize:s,...void 0===n?{}:{hasMore:n}}})(await e.get(n,{operation:"getGroupMemberList"}))},XC=async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/admin`),i=await e.get(n,{operation:"getGroupAdminList"});return Yu(i)},eS=async(e,t,r)=>{const s=BC(t),n=jC(r.groupId,"params.groupId"),i=WC(r),o=i?"&":"",a=zC(s,`/chatgroups/${encodeURIComponent(n)}/mute?version=v3${o}${i.replace("?","")}`);return(e=>{const t=[];for(const r of Vu(e)){const e=qu(r);if(e){t.push({user:Zu(e)});continue}const s=Bu(r);if(!s)continue;const n=qu(s.user);if(!n)continue;const i=$u(s.expire);t.push({user:Zu(n),...void 0===i?{}:{muteExpire:i}})}return t})(await e.get(a,{operation:"getGroupMuteList"}))},tS=async(e,t,r)=>{const s=BC(t),n=jC(r.groupId,"params.groupId"),i=WC(r),o=i?"&":"",a=zC(s,`/chatgroups/${encodeURIComponent(n)}/blocks/users?version=v3${o}${i.replace("?","")}`),c=await e.get(a,{operation:"getGroupBlocklist"});return Yu(c).map(e=>({user:e}))},rS=async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/white/users`),i=await e.get(n,{operation:"getGroupAllowlist"});return Yu(i).map(e=>({user:e}))},sS=async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=Ku(e)??{};return{announcement:Gu(t.announcement)??""}})(await e.get(n,{operation:"getGroupAnnouncement"}))},nS=async(e,t,r)=>{const s=BC(t),n=xv();n.set("pagenum",String(r.pageNum??1)),n.set("pagesize",String(r.pageSize??20));const i=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/share_files?${n.toString()}`);return(e=>{const t=zu(e,"pagenum"),r=zu(e,"pagesize"),s=Hu(e,r);return{items:Vu(e).map(e=>Xu(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===s?{}:{hasMore:s}}})(await e.get(i,{operation:"getGroupSharedFileList"}))},iS=(e,t)=>{const r=BC(e);return zC(r,`/chatgroups/${encodeURIComponent(jC(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(jC(t.fileId,"params.fileId"))}`)},oS=async(e,t,r)=>{const s=BC(t),n=jC(r.groupId,"params.groupId"),i=jC(r.userId,"params.userId"),o=((e,t,r)=>{if(t!==e.userId)return null;const s=Object.entries(r);if(0===s.length)return null;let n;for(const[i,o]of s){if(!HC.has(i)||"string"!=typeof o)return null;if(void 0!==n){if(n!==o)return null}else n=o}return void 0===n?null:{nameCard:n}})(t,i,r.memberAttributes);if(o){const t=zC(s,`/sdk/chatgroups/${encodeURIComponent(n)}/nameCard`);return await e.put(t,o,{operation:"setGroupMemberAttributes"})}const a=zC(s,`/sdk/metadata/chatgroup/${encodeURIComponent(n)}/user/${encodeURIComponent(i)}?resource=${s.encodedResource}`);return await e.put(a,{metaData:r.memberAttributes},{operation:"setGroupMemberAttributes"})},aS=async(e,t,r)=>{const s=BC(t),n=zC(s,`/sdk/metadata/chatgroup/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/get`);return(e=>{const t=Ku(e)??{},r=Bu(t.data)??t,s={};for(const[n,i]of Object.entries(r)){const e=Bu(i);e&&(s[n]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:s}})(await e.post(n,{targets:$C(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},cS=e=>{const t=Uu(e)?e:{},r=t.data,s=Uu(r)?r.data:void 0,n=Array.isArray(r)?r:Array.isArray(s)?s:null;if(Array.isArray(n))return dS(n);const i=Uu(r)?r:t,o=Uu(i.namecards)?i.namecards:i,a={};for(const[c,d]of Object.entries(o)){if("string"==typeof d){a[c]={namecard:d};continue}if(!Uu(d))continue;const e=d.namecard??d.nameCard??d.groupNamecard??d.group_namecard??d.group_name_card;"string"==typeof e&&(a[c]={namecard:e,namecardUpdateTime:uS(d)})}return a},dS=e=>{const t={};return e.forEach(e=>{if(!Uu(e))return;const r=e.username??e.userId??e.userid??e.user_id,s=e.name_card??e.namecard??e.nameCard??e.groupNamecard??e.group_namecard??e.group_name_card;"string"==typeof r&&r.trim()&&"string"==typeof s&&(t[r.trim()]={namecard:s,namecardUpdateTime:uS(e)})}),t},uS=e=>Bl("number"==typeof e.update_timestamp?e.update_timestamp:"number"==typeof e.updateTimestamp?e.updateTimestamp:"number"==typeof e.timestamp?e.timestamp:"number"==typeof e.lastModified?e.lastModified:"number"==typeof e.last_modified?e.last_modified:void 0),lS=e=>{if(Uu(e))return Bl("number"==typeof e.timestamp?e.timestamp:"number"==typeof e.update_timestamp?e.update_timestamp:"number"==typeof e.updateTimestamp?e.updateTimestamp:"number"==typeof e.lastModified?e.lastModified:"number"==typeof e.last_modified?e.last_modified:void 0)};class hS{constructor(e){this.repository=e}applyPatch(e){e.shouldMarkStale&&this.repository.markStale(e.groupId);const t=this.repository.getDetailSnapshot(e.groupId);if(!e.groupPatch)return t;const r=t??{groupId:e.groupId,name:e.groupPatch.name??e.groupName??""};return this.repository.mergeDetail({...r,...e.groupPatch,groupId:e.groupId})}}const pS=e=>({...e}),mS=e=>({...e,owner:e.owner?{...e.owner}:void 0});class gS{constructor(e){this.summarySnapshot=null,this.detailSnapshot=null,this.loadedSummary=!1,this.stale=!1,this.loadedDetail=!1,this.lastPatchedAt=null,this.lastHydratedAt=null,this.groupId=e}mergeSummary(e){e.groupId===this.groupId&&(this.summarySnapshot=pS({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=mS({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=pS(this.toSummaryFromDetail(this.detailSnapshot)),this.loadedSummary=!0,this.loadedDetail=!0,this.stale=!1,this.lastPatchedAt=Date.now(),this.lastHydratedAt=Date.now())}markStale(){this.stale=!0,this.lastPatchedAt=Date.now()}clear(){this.summarySnapshot=null,this.detailSnapshot=null,this.loadedSummary=!1,this.stale=!1,this.loadedDetail=!1,this.lastPatchedAt=null,this.lastHydratedAt=null}getSummarySnapshot(){return this.summarySnapshot?pS(this.summarySnapshot):this.detailSnapshot?pS(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?mS(this.detailSnapshot):null}isStale(){return this.stale}hasLoadedSummary(){return this.loadedSummary}hasLoadedDetail(){return this.loadedDetail}getLastPatchedAt(){return this.lastPatchedAt}getLastHydratedAt(){return this.lastHydratedAt}toSummaryFromDetail(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,public:e.public,joinApprovalRequired:e.joinApprovalRequired,allowInvites:e.allowInvites,maxMembers:e.maxMembers,role:e.role,disabled:e.disabled}}}class fS{toSummary(e){const t=e.getSummarySnapshot();return t?(e=>({...e}))(t):null}toDetail(e){const t=e.getDetailSnapshot();return t?(e=>({...e,owner:e.owner?{...e.owner}:void 0}))(t):null}}class yS{constructor(){this.groups=new Map,this.joinedGroupById=new Map,this.removedJoinedGroupIds=new Set,this.snapshotMapper=new fS,this.joinedGroupSnapshot=null,this.sessionKey=null}ensureSession(e){return this.sessionKey!==e&&(this.sessionKey=e,this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null,!0)}getSessionKey(){return this.sessionKey}getOrCreate(e){const t=this.groups.get(e);if(t)return t;const r=new gS(e);return this.groups.set(e,r),r}mergeSummary(e){return this.getOrCreate(e.groupId).mergeSummary(e),this.getSummarySnapshot(e.groupId)??{...e}}mergeSummaries(e){return e.map(e=>this.mergeSummary(e))}applyJoinedGroupSnapshot(e){const t=e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId));this.joinedGroupSnapshot={items:t.map(e=>({...e})),meta:{...e.meta}},this.joinedGroupById.clear();for(const r of t){const e={...r};this.joinedGroupById.set(e.groupId,e),this.mergeSummary(this.toGroupSummary(e))}}getJoinedGroupSnapshot(e){return this.joinedGroupSnapshot?{items:this.joinedGroupSnapshot.items.map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}}:e?{items:e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId)).map(e=>({...e})),meta:{...e.meta}}:{items:[],meta:{integrity:"unknown",limited:!1,storageLimit:100,serverLimit:3e3,source:"sync"}}}getJoinedGroupSummarySnapshot(e,t){const r=this.joinedGroupById.get(e);if(r)return{...r};if(this.removedJoinedGroupIds.has(e))return null;const s=t?.items.find(t=>t.groupId===e);return s?{...s}:null}addJoinedGroupIfAbsent(e,t){const r=this.getJoinedGroupSnapshot(t);return r.items.some(t=>t.groupId===e.groupId)?null:(this.removedJoinedGroupIds.delete(e.groupId),this.applyJoinedGroupSnapshot({items:[{...e},...r.items],meta:{...r.meta}}),this.getJoinedGroupSnapshot())}mergeJoinedGroupSummary(e,t){const r=this.joinedGroupById.get(e);if(!r||!this.joinedGroupSnapshot)return null;const s={...r,...t,groupId:e};return this.joinedGroupById.set(e,s),this.mergeSummary(this.toGroupSummary(s)),this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.map(t=>t.groupId===e?{...s}:{...t}),meta:{...this.joinedGroupSnapshot.meta}},this.getJoinedGroupSnapshot()}mergeDetail(e){const t=this.mergeJoinedGroupFieldsIntoDetail(e);return this.getOrCreate(t.groupId).mergeDetail(t),this.getDetailSnapshot(t.groupId)??{...t}}mergeDetails(e){return e.map(e=>this.mergeDetail(e))}getSummarySnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toSummary(t):null}getDetailSnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toDetail(t):null}hasFreshDetail(e){const t=this.groups.get(e);return Boolean(t&&t.hasLoadedDetail()&&!t.isStale())}markStale(e){this.getOrCreate(e).markStale()}delete(e){this.groups.delete(e),this.joinedGroupById.delete(e),this.joinedGroupSnapshot&&(this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.filter(t=>t.groupId!==e).map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}})}markJoinedGroupRemoved(e){this.removedJoinedGroupIds.add(e),this.delete(e)}clear(){this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null}mergeJoinedGroupFieldsIntoDetail(e){const t=this.joinedGroupById.get(e.groupId);return t&&void 0===e.joinedAt&&void 0!==t.joinedAt?{...e,joinedAt:t.joinedAt}:e}toGroupSummary(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,role:e.role,disabled:e.disabled}}}const vS=0,IS=5,bS=12,_S=13,TS=0,CS=1,SS=2,ES=0,wS=1,AS=2,RS=3,NS=e=>{const t=e.group_id?.trim();return t?{groupId:t,name:e.group_name??"",description:e.description,memberCount:e.members_count,role:(s=e.role,s===TS?"owner":s===CS?"admin":s===SS?"member":void 0),disabled:e.disabled,ownerId:e.group_owner,avatarUrl:e.group_avatar,muteAllMembers:e.mute_all,muteExpiration:e.mute_expiration,remindType:(r=e.remind_type,r===ES?"DEFAULT":r===wS?"ALL":r===AS?"AT":r===RS?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,s},OS=e=>e.updatedAt??0,MS=(e,t)=>{if(!e)return!0;return OS(t)>=OS(e)},US={nested:{easemob:{nested:{joinedgroups:{nested:{GatewayHeader:{fields:{resource:{type:"string",id:1},timestamp:{type:"int64",id:2},request_id:{type:"string",id:3},protocol_version:{type:"int32",id:4}}},GetJoinedGroupsRequest:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},org:{type:"string",id:3},app:{type:"string",id:4},username:{type:"string",id:5},last_sync_time:{type:"int64",id:6},cursor:{type:"string",id:7}}},GroupItem:{fields:{group_id:{type:"string",id:1},group_name:{type:"string",id:2},group_owner:{type:"string",id:3},members_count:{type:"int64",id:4},mute_all:{type:"bool",id:5},disabled:{type:"bool",id:6},description:{type:"string",id:7},group_avatar:{type:"string",id:8},role:{type:"uint32",id:9},mute_expiration:{type:"int64",id:10},remind_type:{type:"int32",id:11},create_at:{type:"uint64",id:12},update_at:{type:"uint64",id:13},joined_timestamp:{type:"int64",id:14}}},GetJoinedGroupsResponse:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},groups:{rule:"repeated",type:"GroupItem",id:3},is_last_batch:{type:"bool",id:4},last_sync_finished_ts:{type:"int64",id:5},cursor:{type:"string",id:6}}},ErrorDetail:{fields:{type:{type:"int32",id:1},header:{type:"GatewayHeader",id:2},code:{type:"uint32",id:3},message:{type:"string",id:4}}}}}}}}};let LS=null,kS=!1;const DS=()=>LS||(kS||(fa.util.Long=Pn,fa.configure(),kS=!0),Ka(),LS=fa.Root.fromJSON(US),Va(LS),LS),PS=e=>DS().lookupType(e),xS=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.length>0){const t=Number(e);return Number.isFinite(t)?t:void 0}if(Pn.isLong(e))return e.toNumber();if(e&&"object"==typeof e&&"toString"in e&&"function"==typeof e.toString){const t=Number(e.toString());return Number.isFinite(t)?t:void 0}},FS=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:xS(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:xS(t.protocol_version)??xS(t.protocolVersion)??0}};class BS{constructor(){this.requestType=PS("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=PS("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=PS("easemob.joinedgroups.ErrorDetail")}encodeRequest(e){const t=this.requestType.create({type:e.type,header:e.header?{resource:e.header.resource,timestamp:e.header.timestamp,request_id:e.header.requestId,protocol_version:e.header.protocolVersion}:void 0,org:e.org,app:e.app,username:e.username,last_sync_time:e.lastSyncTime??0,cursor:e.cursor});return this.requestType.encode(t).finish()}decode(e){const t=this.tryDecodeError(e);if(t)return t;const r=this.tryDecodeResponse(e);if(r)return r;const s=this.tryDecodeRequest(e);return s||{type:vS}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=xS(t.type);return r!==bS?null:{type:r,header:FS(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:xS(t.last_sync_time)??xS(t.lastSyncTime)??0,cursor:"string"==typeof t.cursor?t.cursor:void 0}}catch{return null}}tryDecodeResponse(e){try{const t=this.responseType.toObject(this.responseType.decode(e),{longs:String,bytes:Uint8Array}),r=xS(t.type);return r!==_S?null:{type:r,header:FS(t.header),groups:Array.isArray(t.groups)?t.groups.map(e=>(e=>{const t=e&&"object"==typeof e?e:{};return{group_id:"string"==typeof t.group_id?t.group_id:"string"==typeof t.groupId?t.groupId:void 0,group_name:"string"==typeof t.group_name?t.group_name:"string"==typeof t.groupName?t.groupName:void 0,group_owner:"string"==typeof t.group_owner?t.group_owner:"string"==typeof t.groupOwner?t.groupOwner:void 0,members_count:xS(t.members_count)??xS(t.membersCount),mute_all:"boolean"==typeof t.mute_all?t.mute_all:"boolean"==typeof t.muteAll?t.muteAll:void 0,disabled:"boolean"==typeof t.disabled?t.disabled:void 0,description:"string"==typeof t.description?t.description:void 0,group_avatar:"string"==typeof t.group_avatar?t.group_avatar:"string"==typeof t.groupAvatar?t.groupAvatar:void 0,role:xS(t.role),mute_expiration:xS(t.mute_expiration)??xS(t.muteExpiration),remind_type:xS(t.remind_type)??xS(t.remindType),create_at:xS(t.create_at)??xS(t.createAt),update_at:xS(t.update_at)??xS(t.updateAt),joined_timestamp:xS(t.joined_timestamp)??xS(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:xS(t.last_sync_finished_ts)??xS(t.lastSyncFinishedTs),cursor:"string"==typeof t.cursor?t.cursor:void 0}}catch{return null}}tryDecodeError(e){try{const t=this.errorType.toObject(this.errorType.decode(e),{longs:String,bytes:Uint8Array}),r=xS(t.type);return r!==IS?null:{type:r,header:FS(t.header),code:xS(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class GS{constructor(e){this.batches=[],this.done=!1,this.requestId=e}getResumeCursor(){return this.latestCursor}push(e){if(e.type!==_S)return{done:!1};const t=e.header?.requestId;if(t!==this.requestId)return{done:!1};if(this.done)throw new ut("Joined groups response received after completion",ot.REST_BUSINESS_UNKNOWN,{details:{stage:"response_decode",requestId:this.requestId}});if(this.batches.push(e),e.cursor&&(this.latestCursor=e.cursor),e.isLastBatch){if("number"!=typeof e.lastSyncFinishedTs)throw new ut("Joined groups final batch missing lastSyncFinishedTs",ot.REST_BUSINESS_UNKNOWN,{details:{stage:"completion_meta",requestId:this.requestId}});this.done=!0,this.lastSyncFinishedTs=e.lastSyncFinishedTs}return{done:this.done}}buildResult(){return{batches:this.batches.map(e=>({...e,groups:e.groups.map(e=>({...e}))})),lastSyncFinishedTs:this.lastSyncFinishedTs}}}const qS=e=>e.type===_S,$S=e=>e.type===IS;class jS{constructor(e){this.codec=new BS,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new GS(t);return await this.syncWithSharedSession(e.request,t,r)}cancel(){this.sharedSession.cancel("group-sync-cancelled")}async syncWithSharedSession(e,t,r){return await this.sharedSession.request({dataType:"group",label:"Group sync",requestId:t,encode:()=>this.codec.encodeRequest(this.buildAttemptRequest(e,t,r.getResumeCursor())),decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:qS(t)||$S(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(qS(e)){if(!r.push(e).done)return;return{done:!0,result:r.buildResult()}}if($S(e))throw(e=>{const t=(t,r)=>({stage:t,serverCode:e.code,requestId:e.header?.requestId,retryable:r});switch(e.code){case 1601:return new ut(e.message,ot.VALIDATION_REQUIRED,{details:t("request_send",!1)});case 1602:return new ut(e.message,ot.REST_BUSINESS_UNKNOWN,{details:t("batch_merge",!0)});case 1002:return new pt(e.message,{code:ot.AUTH_UNAUTHORIZED,details:t("auth",!1)});case 1003:return new ut(e.message,ot.SERVICE_LIMIT_EXCEEDED,{details:t("server_limit",!0)});default:return new ut(e.message,ot.REST_BUSINESS_UNKNOWN,{details:t("response_decode",!0)})}})(e);return}catch(t){throw t instanceof ut?t:new ut("Joined groups frame decode failed",ot.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:t instanceof Error?t.message:String(t)}})}}})}buildAttemptRequest(e,t,r){return{...e,cursor:r,lastSyncTime:0,header:{resource:e.header?.resource??"",timestamp:Date.now(),requestId:t,protocolVersion:e.header?.protocolVersion??1}}}}class VS{constructor(e){this.running=null,this.dependencies=e}async sync(){if(this.running)return await this.running;this.running=this.runSync();try{await this.running}finally{this.running=null}}cancel(){this.dependencies.getSharedSyncSession().cancel("group-sync-cancelled")}async runSync(){this.dependencies.onStart();const e=Date.now();try{const r=await this.dependencies.getSyncUrls();if(0===r.length)throw new ut("Group sync websocket urls are unavailable",ot.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",retryable:!0}});const s=this.buildRequest(),n=await new jS(this.dependencies.getSharedSyncSession()).sync({urls:r,request:s}),i=n.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=NS(r);e&&t.push(e)}return t})(e.groups)),o=this.dependencies.getRuntimeSnapshot(),a=(e=>{const t=new Map(e.existingItems.map(e=>[e.groupId,e])),r=new Map;for(const n of e.incomingItems){const e=r.get(n.groupId)??t.get(n.groupId);MS(e,n)?r.set(n.groupId,{...e??{},...n,groupId:n.groupId}):e&&r.set(n.groupId,{...e})}const s=r.size>=zf;return{items:Array.from(s?e.existingItems.map(e=>({...e})):r.values()).sort((e,t)=>{const r=(t.joinedAt??0)-(e.joinedAt??0);return 0!==r?r:e.groupId.localeCompare(t.groupId)}),meta:{integrity:s?"limited":"synced",limited:s,storageLimit:Kf,serverLimit:zf,source:"sync",lastSyncFinishedTs:e.lastSyncFinishedTs,lastSuccessfulAt:Date.now()}}})({existingItems:o?.items??[],incomingItems:i,lastSyncFinishedTs:n.lastSyncFinishedTs}),c=this.dependencies.getCacheManager();this.dependencies.applyRuntimeSnapshot(a);const d=this.dependencies.getRuntimeSnapshot()??a;try{await c.commitJoinedGroupPreviewSnapshot(d);const e=this.dependencies.getRuntimeSnapshot();e&&!this.hasSameMembership(d,e)&&await c.commitJoinedGroupPreviewSnapshot(e)}catch(t){throw o&&this.dependencies.applyRuntimeSnapshot(o),new yt("Joined-group preview persistence failed",{details:{stage:"preview_persist",cause:t instanceof Error?t.message:String(t)}})}Ks("Group sync finished",{durationMs:Date.now()-e,itemCount:a.items.length,limited:a.meta.limited}),this.dependencies.onFinish({status:"success"})}catch(t){const r=(e=>{const t=e instanceof ut?e:new ut("Group sync failed",ot.REST_BUSINESS_UNKNOWN,{details:{stage:"socket_connect",cause:e instanceof Error?e.message:String(e)}}),r=t.details??{},s=r.serverCode;return{dataType:"group",code:t.code,stage:(n=r.stage,"config"===n||"socket_connect"===n||"request_send"===n||"response_decode"===n||"batch_merge"===n||"preview_persist"===n||"completion_meta"===n||"auth"===n||"server_limit"===n||"cancelled"===n?n:"socket_connect"),message:t.message,retryable:!0===r.retryable,serverCode:"number"==typeof s||"string"==typeof s?s:void 0};var n})(t);Ks("Group sync failed",{durationMs:Date.now()-e,stage:r.stage,code:r.code,serverCode:r.serverCode}),this.dependencies.onFinish({status:"failed",error:r})}}hasSameMembership(e,t){if(e.items.length!==t.items.length)return!1;const r=new Set(t.items.map(e=>e.groupId));return e.items.every(e=>r.has(e.groupId))}buildRequest(){const e=this.dependencies.getRestContext(),{orgName:t,appName:r}=fs(e.appKey);return{type:bS,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:t,app:r,username:e.userId,lastSyncTime:0}}}const KS=AI(RI,{common:{},apis:{createGroup:{range:"4,110,204,608",errors:{invalid_parameter:{code:110,httpStatus:400,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},exceed_limit:{code:4,httpStatus:403,retryable:!1},group_name_violation:{code:608,httpStatus:403,retryable:!1,aliases:["INVALID_GROUP_NAME"]},resource_not_found:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","username_not_found"]}}},getJoinedGroupList:{range:"",errors:{}},getGroupInfo:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupInfoList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},updateGroupInfo:{range:"110,603,606,607,608",errors:{group_authorization:{code:603,httpStatus:403,retryable:!1},forbidden_op:{code:603,httpStatus:403,retryable:!1},illegal_argument:{code:110,httpStatus:400,retryable:!1},exceed_limit:{code:110,httpStatus:403,retryable:!1},group_name_violation:{code:608,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1},group_disabled:{code:607,httpStatus:403,retryable:!1}}},changeGroupOwner:{range:"603,606",errors:{forbidden_op:{code:603,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1}}},destroyGroup:{range:"603,606,607",errors:{group_authorization:{code:603,httpStatus:403,retryable:!1},resource_not_found:{code:606,httpStatus:404,retryable:!1},group_disabled:{code:607,httpStatus:403,retryable:!1}}},leaveGroup:{range:"602,603,606",errors:{not_joined:{code:602,retryable:!1,aliases:["GROUP_NOT_JOINED","group_not_joined"]},owner_cannot_leave:{code:603,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"owner can not quit group"},resource_not_found:{code:606,httpStatus:404,retryable:!1}}},joinGroup:{range:"600-607,613",errors:{group_invalid_id:{code:600,retryable:!1,aliases:["GROUP_INVALID_ID"]},already_joined:{code:601,retryable:!1,aliases:["ALREADY_JOINED","GROUP_ALREADY_JOINED","group_already_joined"]},not_joined:{code:602,retryable:!1,aliases:["GROUP_NOT_JOINED","group_not_joined"]},group_authorization:{code:603,httpStatus:403,retryable:!1,aliases:["NEED_APPROVAL","GROUP_PERMISSION_DENIED"]},group_full:{code:604,httpStatus:403,retryable:!1,aliases:["GROUP_FULL","GROUP_MEMBERS_FULL"],matchField:"error_description",matchPattern:"member list is full"},resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["GROUP_NOT_FOUND","service_resource_not_found"]},group_disabled:{code:607,retryable:!1,aliases:["GROUP_DISABLED"]},group_user_in_blocklist:{code:613,httpStatus:403,retryable:!1,aliases:["GROUP_USER_IN_BLOCKLIST"],matchField:"error_description",matchPattern:"is in the blacklist"}}},inviteUsersToGroup:{range:"204,603,606,607",errors:{group_authorization:{code:603,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1,aliases:["service_resource_not_found","username_not_found"]},group_not_found:{code:606,retryable:!1,aliases:["GROUP_NOT_FOUND"]},group_disabled:{code:607,retryable:!1}}},acceptGroupJoinRequest:{range:"",errors:{}},rejectGroupJoinRequest:{range:"",errors:{}},acceptInvitation:{range:"",errors:{}},rejectInvitation:{range:"",errors:{}},removeGroupMembers:{range:"",errors:{}},addGroupAdmin:{range:"",errors:{}},removeGroupAdmin:{range:"",errors:{}},muteGroupMembers:{range:"",errors:{}},unmuteGroupMembers:{range:"",errors:{}},muteAllGroupMembers:{range:"",errors:{}},unmuteAllGroupMembers:{range:"",errors:{}},blockGroupMembers:{range:"",errors:{}},unblockGroupMembers:{range:"",errors:{}},addUsersToGroupAllowlist:{range:"",errors:{}},removeUsersFromGroupAllowlist:{range:"",errors:{}},checkIfInGroupAllowList:{range:"",errors:{}},getGroupMemberList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["service_resource_not_found"]}}},getGroupAdminList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupMuteList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},checkIfInGroupMuteList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupBlocklist:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupAllowlist:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},getGroupAnnouncement:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1}}},updateGroupAnnouncement:{range:"110",errors:{announcement_length_exceeded:{code:110,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"announce into length exceeds limit"},announcement_info_length_exceeded:{code:110,httpStatus:403,retryable:!1,matchField:"error_description",matchPattern:"announce info length exceeds limit"}}},getGroupSharedFileList:{range:"606",errors:{resource_not_found:{code:606,httpStatus:404,retryable:!1,aliases:["RestGroupFeignException"]}}},deleteGroupSharedFile:{range:"603,605,606",errors:{group_authorization:{code:603,retryable:!1},file_not_found:{code:605,retryable:!1,aliases:["GROUP_SHARED_FILE_INVALID_ID"]},resource_not_found:{code:606,retryable:!1}}},setGroupMemberAttributes:{range:"4,210,302,305,602,609-612",errors:{attributes_reach_limit:{code:609,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_REACH_LIMIT"],matchField:"error_code",matchValue:60006},attributes_update_failed:{code:610,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_UPDATE_FAILED"],matchField:"error_code",matchValue:60005},attributes_key_reach_limit:{code:611,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_KEY_REACH_LIMIT"],matchField:"error_code",matchValue:60009},attributes_value_reach_limit:{code:612,retryable:!1,aliases:["GROUP_MEMBER_ATTRIBUTES_VALUE_REACH_LIMIT"],matchField:"error_code",matchValue:600010},not_joined:{code:602,httpStatus:404,retryable:!1,matchField:"error_code",matchValue:60003},permission_denied:{code:210,httpStatus:401,retryable:!1,matchField:"error_code",matchValue:60001},permission_denied_403:{code:210,httpStatus:403,retryable:!1,matchField:"error_code",matchValue:60002},exceed_service_limit:{code:4,httpStatus:400,retryable:!1,matchField:"error_code",matchValue:60007},service_disabled:{code:305,httpStatus:403,retryable:!1,matchField:"error_code",matchValue:60004}}},getGroupMembersAttributes:{range:"606",errors:{resource_not_found:{code:606,retryable:!1}}},getGroupNamecards:{range:"",errors:{}}}}),zS=class{constructor(){this.capabilities=["rawNotify:group","group:namecard"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.groupRegistry=new Map,this.groupRepository=null,this.groupEventSync=null}bind(e,t){this.client=e,this.eventContext=t??null,this.groupRegistry.clear(),this.groupRepository=new yS,this.groupEventSync=new hS(this.groupRepository),this.ensureRepositorySession()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("group"!==e.type)return;const t=e.payload,r=t.eventName,s=await this.buildIncomingEventPayload(r,t);if(!s)return;if(this.eventContext?.dispatch?.(r,s),r!==Te)return;if(!("attribute"in s)||!("user"in s))return;const n=this.extractGroupNamecard(s.attribute);if(void 0===n||!s.user?.userId)return;const i=this.client?.getCurrentUserId();s.user.userId!==i&&(this.getCacheManager()?.setGroupNamecards([{groupId:s.groupId,userId:s.user.userId,namecard:n,lastAccess:Date.now(),lastUpdate:Date.now()}]),this.eventContext?.dispatch?.(Ce,{groupId:s.groupId,userId:s.user.userId,namecard:n}))}async createGroup(e){return this.runOperation("createGroup",async()=>{const t=this.getRestContextOrThrow(),r=await JC(this.getRestClient(t),t,e);return this.ensureRepositorySession(),this.addJoinedGroupIfAbsent({groupId:r.groupId,name:e.name,role:"owner",ownerId:t.userId,...void 0===e.description?{}:{description:e.description},...void 0===e.avatar?{}:{avatarUrl:e.avatar}}),r})}getJoinedGroupList(){return this.getJoinedGroupSnapshotForSync().items}getJoinedGroupSnapshotForSync(){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSnapshot(this.loadJoinedGroupPreviewSnapshot())}applyJoinedGroupSnapshot(e){this.ensureRepositorySession(),this.getGroupRepository().applyJoinedGroupSnapshot(e)}getGroupSummaryForHandle(e){return this.requireClient(),this.ensureRepositorySession(),this.getGroupRepository().getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())}getGroup(e){this.requireClient(),this.ensureRepositorySession();const t=e.trim();if(0===t.length)throw new mt("groupId is required",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"groupId",message:"groupId is required",rule:"required"}]}});const r=this.groupRegistry.get(t);if(r)return r;this.getGroupSummaryForHandle(t),this.getGroupRepository().getOrCreate(t);const s=new FC(t,this);return this.groupRegistry.set(t,s),s}async getGroupInfo(e){return this.runOperation("getGroupInfo",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow(),r=await QC(this.getRestClient(t),t,e),s=await this.hydrateGroupDetailUsers(r);return this.getGroupRepository().mergeDetail(s)})}async getGroupInfoList(e){return this.runOperation("getGroupInfoList",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=BC(t),n=$C(r.groupIds,"params.groupIds"),i=zC(s,`/chatgroups/${n.map(e=>encodeURIComponent(e)).join(",")}?joined_time=true&version=v3`),o=await e.get(i,{operation:"getGroupInfoList"});return(Uu(o)&&Array.isArray(o.data)?o.data:[]).map(e=>Qu({data:[e]}))})(this.getRestClient(t),t,e),s=await this.hydrateGroupDetailsUsers(r);return this.getGroupRepository().mergeDetails(s)})}async getGroupDetailForHandle(e){this.ensureRepositorySession();const t=this.getGroupRepository();if(t.getOrCreate(e),t.hasFreshDetail(e)){const r=t.getDetailSnapshot(e);if(r)return r}return this.getGroupInfo({groupId:e})}async refreshGroupDetailForHandle(e){return this.ensureRepositorySession(),this.getGroupRepository().getOrCreate(e),this.getGroupInfo({groupId:e})}resetSessionRuntime(){this.groupRegistry.clear(),this.getGroupRepository().ensureSession(null)}async buildIncomingEventPayload(e,t){this.ensureRepositorySession();const r=t.payload,s=e===ie?this.resolveLocalGroupName(r.groupId):void 0,n=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(await this.syncRuntimeForEvent(e,r,n),e){case Y:return{groupId:r.groupId,groupName:r.groupName,inviter:this.pickEventUser(r.inviterId,n),reason:r.reason};case X:return{groupId:r.groupId,groupName:r.groupName,applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case ee:return{groupId:r.groupId,groupName:r.groupName,accepter:this.pickEventUser(r.accepterId,n)};case te:return{groupId:r.groupId,groupName:r.groupName,decliner:this.pickEventUser(r.declinerId,n),applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case re:case se:return{groupId:r.groupId,invitee:this.pickEventUser(r.inviteeId,n),reason:r.reason};case ne:return{groupId:r.groupId,groupName:r.groupName};case ie:return{groupId:r.groupId,groupName:r.groupName??s};case oe:return{groupId:r.groupId,inviter:this.pickEventUser(r.inviterId,n),inviteMessage:r.reason};case ae:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n),muteExpire:r.muteExpire};case ce:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n)};case de:case ue:return{groupId:r.groupId,allowlist:this.pickEventUsers(r.userIds,n)};case le:return{groupId:r.groupId,isMuted:Boolean(r.isMuted)};case he:case pe:return{groupId:r.groupId,administrator:this.pickEventUser(r.administratorId,n)};case me:return{groupId:r.groupId,newOwner:this.pickEventUser(r.newOwnerId,n),oldOwner:this.pickEventUser(r.oldOwnerId,n)};case ge:return{groupId:r.groupId,groupName:await this.resolveMembersJoinedGroupName(r),members:this.pickEventUsers(r.memberIds,n)};case fe:return{groupId:r.groupId,members:this.pickEventUsers(r.memberIds,n)};case ye:return{groupId:r.groupId,announcement:r.announcement??""};case ve:return{groupId:r.groupId,sharedFile:this.hydrateEventSharedFile(r.sharedFile,n)};case Ie:return{groupId:r.groupId,fileId:r.fileId??""};case be:return{groupId:r.groupId,groupInfo:await this.resolveGroupDetailForEvent(r)};case _e:{const e=await this.resolveGroupDetailForEvent(r),t=void 0===r.isDisabled?Boolean(e.disabled):Boolean(r.isDisabled);return{groupId:r.groupId,groupInfo:e,disabled:t}}case Te:return{groupId:r.groupId,user:this.pickEventUser(r.userId,n),attribute:r.attribute??{},from:r.from,source:r.source};default:return null}}async resolveGroupDetailForEvent(e){this.ensureRepositorySession();const t=void 0===e.isDisabled?e.groupPatch:{...e.groupPatch??{},disabled:e.isDisabled},r=this.getGroupEventSync().applyPatch({groupId:e.groupId,groupName:e.groupName,groupPatch:t,shouldMarkStale:e.shouldFetchGroupDetail});if(e.shouldFetchGroupDetail)try{return await this.getGroupInfo({groupId:e.groupId})}catch(n){Ks("GroupManager resolveGroupDetailForEvent fallback to snapshot",{groupId:e.groupId,error:n})}if(r)return r;const s=this.getGroupRepository().getDetailSnapshot(e.groupId);return s||{groupId:e.groupId,name:t?.name??e.groupName??"",...t??{}}}async updateGroupInfo(e){return this.runOperation("updateGroupInfo",async()=>{const t=this.getRestContextOrThrow();await ZC(this.getRestClient(t),t,e)})}async changeGroupOwner(e){return this.runOperation("changeGroupOwner",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}?resource=${s.encodedResource}`);await e.put(n,{newowner:jC(r.newOwner,"params.newOwner")},{operation:"changeGroupOwner"})})(this.getRestClient(t),t,e)})}async destroyGroup(e){return this.runOperation("destroyGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}?version=v3&resource=${s.encodedResource}`);await e.delete(n,{operation:"destroyGroup"})})(this.getRestClient(t),t,e),await this.requireClient().handleGroupDestroyedConversation(e.groupId),await this.removeJoinedGroupLocal(e.groupId)})}async leaveGroup(e){return this.runOperation("leaveGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/quit?resource=${s.encodedResource}`);await e.delete(n,{operation:"leaveGroup"})})(this.getRestClient(t),t,e),await this.removeJoinedGroupLocal(e.groupId)})}async joinGroup(e){return this.runOperation("joinGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/apply?resource=${s.encodedResource}`);await e.post(n,{message:r.message??""},{operation:"joinGroup"})})(this.getRestClient(t),t,e)})}async inviteUsersToGroup(e){return this.runOperation("inviteUsersToGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/invite?resource=${s.encodedResource}`);await e.post(n,{usernames:$C(r.userIds,"params.userIds")},{operation:"inviteUsersToGroup"})})(this.getRestClient(t),t,e)})}async acceptGroupJoinRequest(e){return this.runOperation("acceptGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:jC(r.userId,"params.userId"),verifyResult:!0},{operation:"acceptGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async rejectGroupJoinRequest(e){return this.runOperation("rejectGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:jC(r.userId,"params.userId"),verifyResult:!1,reason:r.reason},{operation:"rejectGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async acceptInvitation(e){return this.runOperation("acceptInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/invite_verify?resource=${s.encodedResource}`);await e.post(n,{invitee:t.userId,verifyResult:!0},{operation:"acceptInvitation"})})(this.getRestClient(t),t,e)})}async rejectInvitation(e){return this.runOperation("rejectInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/invite_verify?resource=${s.encodedResource}`);await e.post(n,{invitee:t.userId,verifyResult:!1},{operation:"rejectInvitation"})})(this.getRestClient(t),t,e)})}async getGroupMemberList(e){return this.runOperation("getGroupMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await YC(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(e.groupId,r.items)}})}async removeGroupMembers(e){return this.runOperation("removeGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=$C(r.userIds,"params.userIds"),i=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"removeGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAdminList(e){return this.runOperation("getGroupAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await XC(this.getRestClient(t),t,e);return this.hydrateUserInfos(e.groupId,r)})}async addGroupAdmin(e){return this.runOperation("addGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/admin?resource=${s.encodedResource}`);await e.post(n,{newadmin:r.userId},{operation:"addGroupAdmin"})})(this.getRestClient(t),t,e)})}async removeGroupAdmin(e){return this.runOperation("removeGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/admin/${encodeURIComponent(r.userId)}?resource=${s.encodedResource}`);await e.delete(n,{operation:"removeGroupAdmin"})})(this.getRestClient(t),t,e)})}async getGroupMuteList(e){return this.runOperation("getGroupMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await eS(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async muteGroupMembers(e){return this.runOperation("muteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/mute?resource=${s.encodedResource}`);await e.post(n,{usernames:$C(r.userIds,"params.userIds"),mute_duration:r.muteDuration},{operation:"muteGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteGroupMembers(e){return this.runOperation("unmuteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=$C(r.userIds,"params.userIds"),i=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/mute/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"unmuteGroupMembers"})})(this.getRestClient(t),t,e)})}async muteAllGroupMembers(e){return this.runOperation("muteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/ban?resource=${s.encodedResource}`);await e.post(n,void 0,{operation:"muteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllGroupMembers(e){return this.runOperation("unmuteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/ban?resource=${s.encodedResource}`);await e.delete(n,{operation:"unmuteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupBlocklist(e){return this.runOperation("getGroupBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await tS(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async blockGroupMembers(e){return this.runOperation("blockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/blocks/users?resource=${s.encodedResource}`);await e.post(n,{usernames:$C(r.userIds,"params.userIds")},{operation:"blockGroupMembers"})})(this.getRestClient(t),t,e)})}async unblockGroupMembers(e){return this.runOperation("unblockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=$C(r.userIds,"params.userIds"),i=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/blocks/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"unblockGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAllowlist(e){return this.runOperation("getGroupAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await rS(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async addUsersToGroupAllowlist(e){return this.runOperation("addUsersToGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/white/users?resource=${s.encodedResource}`);await e.post(n,{usernames:$C(r.userIds,"params.userIds")},{operation:"addUsersToGroupAllowlist"})})(this.getRestClient(t),t,e)})}async removeUsersFromGroupAllowlist(e){return this.runOperation("removeUsersFromGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=$C(r.userIds,"params.userIds"),i=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/white/users/${n.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`);await e.delete(i,{operation:"removeUsersFromGroupAllowlist"})})(this.getRestClient(t),t,e)})}async checkIfInGroupAllowList(e){return this.runOperation("checkIfInGroupAllowList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),i=await e.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof i?i:Uu(i)&&"boolean"==typeof i.data?i.data:Boolean(i)})(this.getRestClient(t),t,e)})}async checkIfInGroupMuteList(e){return this.runOperation("checkIfInGroupMuteList",async()=>{const t=this.getRestContextOrThrow();return(async(e,t,r)=>{const s=BC(t),n=zC(s,`/sdk/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),i=await e.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof i?i:Uu(i)&&"boolean"==typeof i.data?i.data:Boolean(i)})(this.getRestClient(t),t,e)})}async getGroupAnnouncement(e){return this.runOperation("getGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();return sS(this.getRestClient(t),t,e)})}async updateGroupAnnouncement(e){return this.runOperation("updateGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/announcement?resource=${s.encodedResource}`);await e.post(n,{announcement:r.announcement},{operation:"updateGroupAnnouncement"})})(this.getRestClient(t),t,e)})}async getGroupSharedFileList(e){return this.runOperation("getGroupSharedFileList",async()=>{const t=this.getRestContextOrThrow(),r=await nS(this.getRestClient(t),t,e),s=await this.resolveGroupContextUserInfoMap(e.groupId,r.items.map(e=>e.fileOwner).filter(e=>void 0!==e));return{...r,items:r.items.map(e=>({...e,fileOwner:e.fileOwner?.userId?s.get(e.fileOwner.userId)??e.fileOwner:e.fileOwner}))}})}async uploadGroupSharedFile(e){return this.runOperation("uploadGroupSharedFile",async()=>{const t=this.getRestContextOrThrow(),r=iS(t,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),s=os({file:e.file}),n=Zh({operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"}),i=n?.startRequest({requestName:"GROUP_UPLOAD_SHAREDFILE",method:"POST",url:`${t.restBaseUrl}${r}`});try{const o=await(this.requireClient().getUploadAdapter()?.upload({url:`${t.restBaseUrl}${r}?resource=${encodeURIComponent(t.clientResource)}`,headers:{Authorization:`Bearer ${t.token}`,[_u]:bu()},source:s.source,timeoutMs:3e5,onProgress:e.onFileUploadProgress}));if(!o)throw new Error("platform upload adapter is unavailable");if(o.status<200||o.status>=300)throw new ut("uploadGroupSharedFile failed",ot.REST_HTTP_ERROR,{details:{status:o.status}});i?.finish({code:o.status,success:!0}),n?.finish({code:0,success:!0}),e.onFileUploadComplete?.(o.body)}catch(o){const t=Fd(o);throw i?.finish({code:t.code,success:!1,description:t.message}),n?.finish({code:t.code,success:!1,description:t.message}),t.code===ot.UPLOAD_ABORTED&&e.onFileUploadCanceled?.(),e.onFileUploadError?.(t),t}})}async deleteGroupSharedFile(e){return this.runOperation("deleteGroupSharedFile",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(jC(r.fileId,"params.fileId"))}?resource=${s.encodedResource}`);await e.delete(n,{operation:"deleteGroupSharedFile"})})(this.getRestClient(t),t,e)})}async downloadGroupSharedFile(e){return this.runOperation("downloadGroupSharedFile",async()=>{let t,r;try{const s=this.getRestContextOrThrow(),n=`${s.restBaseUrl}${iS(s,e)}`;t=Zh({operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"}),r=t?.startRequest({requestName:"GROUP_DOWNLOAD_SHAREDFILE",method:"GET",url:n});const i=this.requireClient().getRequestAdapter();if(!i)throw new ut("downloadGroupSharedFile request adapter is unavailable",ot.REST_NETWORK_ERROR);const o=await i.request({url:n,method:"GET",headers:{Authorization:`Bearer ${s.token}`,...e.secret?{"Share-Secret":e.secret}:{},[_u]:bu()},responseType:"arraybuffer",timeoutMs:6e4});if(o.status<200||o.status>=300)throw r?.finish({code:o.status,success:!1,description:"downloadGroupSharedFile failed"}),t?.finish({code:o.status,success:!1,description:"downloadGroupSharedFile failed"}),new ut("downloadGroupSharedFile failed",ot.REST_HTTP_ERROR);r?.finish({code:o.status,success:!0}),t?.finish({code:0,success:!0});const a="undefined"!=typeof Blob?new Blob([o.data]):o.data;e.onFileDownloadComplete?.(a)}catch(s){const n=s instanceof ut?s.code:ot.REST_NETWORK_ERROR,i=s instanceof Error?s.message:String(s);throw r?.finish({code:n,success:!1,description:i}),t?.finish({code:n,success:!1,description:i}),e.onFileDownloadError?.(s),s}})}async setGroupMemberAttributes(e){return this.runOperation("setGroupMemberAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await oS(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return aS(this.getRestClient(t),t,e)})}async hydrateMessageProfileGroupNamecards(e,t){0!==t.length&&await this.runOperation("hydrateMessageProfileGroupNamecards",async()=>{const r=this.getRestContextOrThrow(),s=t.map(e=>e.userId),n=await(async(e,t,r)=>{const s=BC(t),n=zC(s,`/sdk/chatgroups/${encodeURIComponent(jC(r.groupId,"params.groupId"))}/nameCard/batch/get`),i=await e.post(n,{members:$C(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:cS(i),responseTimestamp:lS(i)}})(this.getRestClient(r),r,{groupId:e,userIds:s}),i=new Map(t.map(e=>[e.userId,e.namecardUpdateTime])),o=[],a=new Set;for(const[t,d]of Object.entries(n.items))a.add(t),o.push({groupId:e,userId:t,namecard:d.namecard,namecardUpdateTime:i.get(t)??d.namecardUpdateTime,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()});const c=s.filter(e=>!a.has(e));c.length>0&&"number"==typeof n.responseTimestamp&&o.push(...c.map(t=>({groupId:e,userId:t,namecard:"",namecardUpdateTime:n.responseTimestamp,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}))),this.getCacheManager()?.setGroupNamecards(o);for(const e of o)e.userId!==r.userId&&""!==e.namecard&&this.eventContext?.dispatch?.(Ce,{groupId:e.groupId,userId:e.userId,namecard:e.namecard});c.length>0&&"number"!=typeof n.responseTimestamp&&Ks("Group namecard hydration returned partial result",{groupId:e,requestedUserIds:s,missingUserIds:c})})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Ks(`GroupManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof ut?t:t instanceof Error?new ut(`GroupManager ${e} failed: ${t.message}`,ot.UNKNOWN):new ut(`GroupManager ${e} failed`,ot.UNKNOWN)}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Cv(e.restBaseUrl,{errorMap:KS,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new ut("GroupManager is not bound to client",ot.VALIDATION_REQUIRED);return this.client}getGroupRepository(){return this.groupRepository||(this.groupRepository=new yS),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new hS(this.getGroupRepository())),this.groupEventSync}ensureRepositorySession(){this.getGroupRepository().ensureSession(this.resolveRepositorySessionKey())&&this.groupRegistry.clear()}resolveRepositorySessionKey(){if(!this.client)return null;const e=this.client.getCurrentUserId();if(!e)return null;try{const e=this.client.getRestContext();return`${e.restBaseUrl}:${e.userId}:${e.token}:${e.clientResource}`}catch{return`pending:${e}`}}getCacheManager(){return this.client?.getCacheManager()??null}loadJoinedGroupPreviewSnapshot(){const e=this.getCacheManager();if(e&&"function"==typeof e.loadJoinedGroupPreviewSnapshot)return e.loadJoinedGroupPreviewSnapshot()}resolveLocalGroupName(e){const t=this.getGroupRepository(),r=t.getSummarySnapshot(e)?.name;if(r)return r;const s=t.getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())?.name;return s||void 0}async resolveMembersJoinedGroupName(e){const t=this.resolveUsableGroupName(this.resolveLocalGroupName(e.groupId),e.groupId);if(t)return t;const r=this.resolveUsableGroupName(e.groupName,e.groupId);if(r)return r;const s=this.getGroupRepository().getSessionKey();try{const t=this.getRestContextOrThrow(),r=await QC(this.getRestClient(t),t,{groupId:e.groupId}),n=this.getGroupRepository();if(n.getSessionKey()!==s)return;return n.mergeDetail(r),this.resolveUsableGroupName(r.name,e.groupId)}catch(n){return void Ks("Members joined group detail enrichment failed",{groupId:e.groupId,error:n})}}resolveUsableGroupName(e,t){const r=e?.trim();return r&&r!==t?r:void 0}writeSelfGroupNamecardCache(e,t,r){if(t.userId!==e)return;const s=this.extractGroupNamecard(t.memberAttributes);if("string"!=typeof s)return;const n=this.resolveGroupMemberAttributesUpdateTime(r,t.userId);"number"!=typeof n&&Ks("Group member attributes update response missing server update time",{groupId:t.groupId,userId:t.userId}),this.getCacheManager()?.setGroupNamecards([{groupId:t.groupId,userId:t.userId,namecard:s,namecardUpdateTime:n,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}])}resolveGroupMemberAttributesUpdateTime(e,t){const r=[];this.collectUpdateTimeCandidates(e,t,r);for(const s of r){const e=Bl("number"==typeof s?s:Number(s));if("number"==typeof e)return e}}collectUpdateTimeCandidates(e,t,r){if(!Uu(e))return;r.push(e.lastModified,e.last_modified,e.timestamp,e.updateTime,e.update_time,e.updatedAt,e.updated_at);const s=e.data;if(Uu(s)){this.collectUpdateTimeCandidates(s,t,r);const e=s[t];Uu(e)&&this.collectUpdateTimeCandidates(e,t,r)}const n=e.lastModified??e.last_modified;Uu(n)&&r.push(n[t])}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}async resolveUserInfoMap(e){return Fu(e,{cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>{const t=this.getUserInfoManager();if(0===e.length)return[];if(!t)return await this.fetchUserInfosFromRest(e);try{return await t.getUserInfoByUserId({userIds:e})}catch(r){return Ks("GroupManager user info fetch failed",{userIds:e,error:r}),[]}}})}collectEventUserIds(e){const t=e.payload,r=[t.inviterId,t.applicantId,t.accepterId,t.declinerId,t.inviteeId,t.administratorId,t.oldOwnerId,t.newOwnerId,t.userId,t.sharedFile?.fileOwner?.userId,...t.memberIds??[],...t.userIds??[]],s=[],n=new Set;for(const i of r){if("string"!=typeof i)continue;const e=i.trim();e&&!n.has(e)&&(n.add(e),s.push(e))}return s}pickEventUser(e,t){if(e)return xu(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>xu(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:xu(e.fileOwner,t.get(e.fileOwner.userId),e.fileOwner.userId)}:e}async syncRuntimeForEvent(e,t,r){switch(e){case le:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{muteAllMembers:Boolean(t.isMuted)}});case me:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{owner:this.pickEventUser(t.newOwnerId,r)}});case ee:case oe:return void this.addCurrentUserJoinedGroupFromEvent(t);case ge:{let r=!1;if(t.memberIds?.includes(this.requireClient().getCurrentUserId()??"")&&(r=await this.addCurrentUserJoinedGroupFromEvent(t)),r)return;if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0})}case fe:if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,-this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});case ne:case ie:return void(await this.removeJoinedGroupLocal(t.groupId));case ae:case ce:case de:case ue:case he:case pe:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});default:return}}getMemberEventDeltaCount(e,t){switch(e){case ge:case fe:return t.memberIds?.length??0;default:return 0}}applyMemberCountDeltaPatch(e,t,r){if(0===r)return!1;const s=this.getGroupRepository().getDetailSnapshot(e);return!(!s||"number"!=typeof s.memberCount)&&(this.getGroupEventSync().applyPatch({groupId:e,groupName:t,groupPatch:{memberCount:Math.max(0,s.memberCount+r)}}),!0)}async removeJoinedGroupLocal(e){this.getGroupRepository().markJoinedGroupRemoved(e);const t=this.getCacheManager();t&&"function"==typeof t.removeJoinedGroupPreview&&await t.removeJoinedGroupPreview(e)}async addCurrentUserJoinedGroupFromEvent(e){if(!this.addJoinedGroupIfAbsent({groupId:e.groupId,name:e.groupName??"",role:"member"}))return!1;const t=this.getGroupRepository().getSessionKey();let r;try{r=this.getRestContextOrThrow()}catch(s){return Ks("Joined group detail enrichment skipped",{groupId:e.groupId,error:s}),!1}try{return await this.enrichJoinedGroupFromDetail(e.groupId,t,r)}catch(s){return Ks("Joined group detail enrichment failed",{groupId:e.groupId,error:s}),!1}}addJoinedGroupIfAbsent(e){const t=this.getGroupRepository().addJoinedGroupIfAbsent(e,this.loadJoinedGroupPreviewSnapshot());return!!t&&(this.persistJoinedGroupSnapshot(t),!0)}async enrichJoinedGroupFromDetail(e,t,r){const s=await QC(this.getRestClient(r),r,{groupId:e}),n=this.getGroupRepository();if(n.getSessionKey()!==t)return!1;n.mergeDetail(s);const i=n.getJoinedGroupSummarySnapshot(e);if(!i)return!1;const o=n.mergeJoinedGroupSummary(e,{...i.name||!s.name?{}:{name:s.name},...void 0!==i.description||void 0===s.description?{}:{description:s.description},...void 0!==i.memberCount||void 0===s.memberCount?{}:{memberCount:s.memberCount},...void 0!==i.role||void 0===s.role?{}:{role:s.role},...void 0!==i.disabled||void 0===s.disabled?{}:{disabled:s.disabled},...i.ownerId||!s.owner?.userId?{}:{ownerId:s.owner.userId},...void 0!==i.avatarUrl||void 0===s.avatarUrl?{}:{avatarUrl:s.avatarUrl},...void 0!==i.muteAllMembers||void 0===s.muteAllMembers?{}:{muteAllMembers:s.muteAllMembers},...void 0!==i.createdAt||void 0===s.createdAt?{}:{createdAt:s.createdAt},...void 0!==i.joinedAt||void 0===s.joinedAt?{}:{joinedAt:s.joinedAt}});if(o){this.persistJoinedGroupSnapshot(o);const t=n.getJoinedGroupSummarySnapshot(e);t&&this.requireClient().refreshConversationDisplayFromJoinedGroups([{...t,name:s.name||t.name,avatarUrl:s.avatarUrl??t.avatarUrl}],"profile",{onlyWhenNameMissing:!0})}return!0}persistJoinedGroupSnapshot(e){const t=this.getCacheManager();if(t&&"function"==typeof t.applyJoinedGroupPreviewSnapshot){try{t.applyJoinedGroupPreviewSnapshot(e)}catch(r){return void Ks("Joined group preview persistence failed",{error:r})}"function"==typeof t.flushPending&&t.flushPending().catch(e=>{Ks("Joined group preview flush failed",{error:e})})}}async hydrateUserInfos(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t);return t.map(e=>r.get(e.userId)??e)}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=JT(e),s=await this.getRestClient(t).request(HT(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return eC(s,r.targets)}async hydrateEntriesWithUsers(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t.map(e=>e.user));return t.map(e=>({...e,user:r.get(e.user.userId)??e.user}))}extractGroupNamecard(e){return e.groupNamecard??e.group_namecard??e.group_name_card??e.namecard}async hydrateGroupDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveGroupContextUserInfoMap(e.groupId,[e.owner]);return{...e,owner:t.get(e.owner.userId)??e.owner}}async hydrateGroupDetailsUsers(e){const t=e.filter(e=>Boolean(e.owner?.userId)).map(e=>({groupId:e.groupId,user:e.owner}));if(0===t.length)return e;const r=await this.resolveGroupUserInfoContexts(t);return e.map(e=>e.owner?.userId?{...e,owner:r.get(yb(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),s=await Sb({groupId:e,users:t,includeNameCard:r,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return r&&this.dispatchFetchedUserInfoUpdates(s.fetchedUserInfos),s.usersById}async resolveGroupUserInfoContexts(e){const t=this.isGroupNamecardEnhancementEnabled(),r=await Cb({contexts:e,includeNameCard:t,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return t&&this.dispatchFetchedUserInfoUpdates(r.fetchedUserInfos),r.usersByContextKey}async fetchGroupUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoManager();return t?await t.getUserInfoByUserId({userIds:e}):await this.fetchUserInfosFromRest(e)}isGroupNamecardEnhancementEnabled(){const e=this.requireClient(),t=e.isUserInfoSyncEnabled;return"function"==typeof t&&t.call(e)}dispatchFetchedUserInfoUpdates(e){if(0===e.length)return;const t=this.requireClient(),r=t.getCurrentUserId(),s=e.find(e=>e.userId===r),n=e.filter(e=>e.userId!==r);s&&t.dispatchOwnInfoUpdated?.(s),t.dispatchUserInfoUpdated?.(n),t.refreshConversationDisplayFromUserInfos?.(e.map(e=>({userId:e.userId})),"profile")}createSyncController(e){return new VS(e)}};zS.key="groupManager";let HS=zS;const WS=AI(RI,{common:{},apis:{publishPresence:{range:"1100",errors:{PRESENCE_PARAM_EXCEED:{code:1100,httpStatus:400,retryable:!1}}},subscribePresences:{range:"1100,1101",errors:{cannot_subscribe_yourself:{code:1101,httpStatus:400,retryable:!1,matchField:"result",matchPattern:"you can't sub yourself"},param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},unsubscribePresence:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getSubscribedPresenceList:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}},getPresenceStatus:{range:"1100",errors:{param_length_exceed:{code:1100,httpStatus:400,retryable:!1}}}}}),JS=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.getEventContextOrThrow().addEventHandler(e,t)}removeEventHandler(e){this.getEventContextOrThrow().removeEventHandler(e)}async publishPresence(e){return this.runOperation("publishPresence",async()=>{this.validateDescription(e.customStatus);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/${t.clientResource}/1`,o={ext:e.customStatus};Vs("Call publishPresence",{customStatus:e.customStatus}),await r.request(i,{method:"POST",body:o,operation:"publishPresence"})})}async subscribePresence(e){return this.runOperation("subscribePresence",async()=>{this.validateUserIds(e.userIds),this.validateExpiry(e.expiry);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/${e.expiry}`,o={usernames:e.userIds};Vs("Call subscribePresence",{userIds:e.userIds,expiry:e.expiry});const a=await r.request(i,{method:"POST",body:o,operation:"subscribePresences"});return this.normalizeSubscribeResponse(a)})}async unsubscribePresence(e){return this.runOperation("unsubscribePresence",async()=>{this.validateUserIds(e.userIds);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence`;Vs("Call unsubscribePresence",{userIds:e.userIds}),await r.request(i,{method:"DELETE",body:e.userIds,operation:"unsubscribePresence"})})}async getSubscribedPresenceList(e){return this.runOperation("getSubscribedPresenceList",async()=>{this.validatePage(e.pageNum,e.pageSize);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence/sublist?pageNum=${e.pageNum}&pageSize=${e.pageSize}`;Vs("Call getSubscribedPresenceList",{pageNum:e.pageNum,pageSize:e.pageSize});const o=await r.request(i,{method:"GET",operation:"getSubscribedPresenceList"});return this.normalizeSubscribedListResponse(o)})}async getPresenceStatus(e){return this.runOperation("getPresenceStatus",async()=>{this.validateUserIds(e.userIds);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/presence`,o={usernames:e.userIds};Vs("Call getPresenceStatus",{userIds:e.userIds});const a=await r.request(i,{method:"POST",body:o,operation:"getPresenceStatus"});return this.normalizeSubscribeResponse(a)})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw Ks(`PresenceManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof ut?t:t instanceof Error?new ut(`PresenceManager ${e} failed: ${t.message}`,ot.UNKNOWN):new ut(`PresenceManager ${e} failed`,ot.UNKNOWN)}getEventContextOrThrow(){if(!this.eventContext)throw new mt("PresenceManager is not bound to event context",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.eventContext",message:"PresenceManager is not bound to event context",rule:"required"}]}});return this.eventContext}getClientOrThrow(){if(!this.client)throw new mt("PresenceManager is not bound to client",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"presenceManager.client",message:"PresenceManager is not bound to client",rule:"required"}]}});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Cv(e.restBaseUrl,{errorMap:WS,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError([{path:"appKey",message:"appKey is invalid",rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateDescription(e){if("string"!=typeof e)throw this.buildValidationError([{path:"description",message:"description must be a string",rule:"invalid_format"}])}validateUserIds(e){if(!Array.isArray(e))throw this.buildValidationError([{path:"userIds",message:"userIds must be an array",rule:"invalid_format"}]);if(0===e.length)throw this.buildValidationError([{path:"userIds",message:"userIds is required",rule:"required"}]);for(const t of e)if("string"!=typeof t||0===t.trim().length)throw this.buildValidationError([{path:"userIds",message:"userIds contains invalid userId",rule:"invalid_format"}])}validateExpiry(e){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"expiry",message:"expiry must be a number",rule:"invalid_format"}]);if(e<0)throw this.buildValidationError([{path:"expiry",message:"expiry must be greater than or equal to 0",rule:"range"}])}validatePage(e,t){if("number"!=typeof e||Number.isNaN(e))throw this.buildValidationError([{path:"pageNum",message:"pageNum must be a number",rule:"invalid_format"}]);if("number"!=typeof t||Number.isNaN(t))throw this.buildValidationError([{path:"pageSize",message:"pageSize must be a number",rule:"invalid_format"}]);if(e<0||t<0)throw this.buildValidationError([{path:"pageNum",message:"pageNum must be greater than or equal to 0",rule:"range"},{path:"pageSize",message:"pageSize must be greater than or equal to 0",rule:"range"}])}normalizeSubscribeResponse(e){return(e.result??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.length?{publisher:e.uid,statusList:this.normalizeStatusList(e.status),ext:"string"==typeof e.ext?e.ext:"",latestTime:"number"==typeof e.last_time?e.last_time:0,expiryTime:"number"==typeof e.expiry?e.expiry:0}:null).filter(e=>null!==e)}normalizeSubscribedListResponse(e){const t=e.result;return(t?.sublist??[]).map(e=>e&&"string"==typeof e.uid&&0!==e.uid.trim().length?e.uid:null).filter(e=>null!==e)}normalizeStatusList(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return{};var t;const r={};for(const[s,n]of Object.entries(e))if("number"==typeof n&&Number.isFinite(n))r[s]=Math.trunc(n);else if("string"==typeof n&&n.trim().length>0){const e=Number(n);Number.isFinite(e)&&(r[s]=Math.trunc(e))}return r}buildValidationError(e){return new mt("Invalid parameters",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:e}})}};JS.key="presenceManager";let QS=JS;const ZS=["apns","fcm","huawei","xiaomi","meizu","vivo","oppo","honor"],YS=(e,t,r="invalid_format")=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:r}]}}),XS=(e,t)=>{if(void 0!==e){if("string"!=typeof e||0===e.trim().length)throw YS(t,`${t} must be a non-empty string`);return e.trim()}},eE=e=>8===e?"normal":ZS[e]??"normal",tE=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.push_token&&"number"==typeof t.push_type&&Number.isInteger(t.push_type)&&t.push_type>=0&&t.push_type<=8&&"number"==typeof t.code&&"string"==typeof t.error};class rE{constructor(e){this.dependencies=e,this.config=null,this.session=null,this.state="unconfigured",this.disabledByUser=!1,this.registrationVersion=0,this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.bindingPromise=null,this.lastBindingError=null,this.lastRemovalError=null,this.removalPromise=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.pluginRegistered=!1,this.delays=new Set}configure(e){const t=(e=>{if(!e||"object"!=typeof e)throw YS("options","options is required","required");const t=e.plugin;if(!t||"object"!=typeof t)throw YS("plugin","plugin is required","required");const r=t;if("function"!=typeof r.onRegister)throw YS("plugin.onRegister","plugin.onRegister must be a function");if("function"!=typeof r.unRegister)throw YS("plugin.unRegister","plugin.unRegister must be a function");const s=e.certificates;if(!s||"object"!=typeof s)throw YS("certificates","certificates is required","required");const n=s,i={apns:XS(n.apns,"certificates.apns"),fcm:XS(n.fcm,"certificates.fcm"),huawei:XS(n.huawei,"certificates.huawei"),xiaomi:XS(n.xiaomi,"certificates.xiaomi"),meizu:XS(n.meizu,"certificates.meizu"),vivo:XS(n.vivo,"certificates.vivo"),oppo:XS(n.oppo,"certificates.oppo"),honor:XS(n.honor,"certificates.honor")};if(!ZS.some(e=>void 0!==i[e]))throw YS("certificates","at least one native push certificate is required");return{plugin:t,certificates:i,signature:ZS.map(e=>`${e}:${i[e]??""}`).join("|")}})(e),r=null!==this.config&&"disabled"!==this.state,s=this.config?.plugin===t.plugin&&this.config.signature===t.signature;if(r&&!s)throw new mt("Native push is enabled; call removePushToken() before replacing its configuration",{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:"options",message:"removePushToken() must succeed before replacing native push config",rule:"conflict"}]}});r&&s&&"failed"!==this.state||(this.invalidateRegistration(),this.safeUnregister(),this.config=t,this.disabledByUser=!1,this.exhaustedKey=null,this.state="configured",this.session&&this.startRegistration())}onSessionReady(e){this.invalidateRegistration(),this.safeUnregister(),this.session=e,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.config&&!this.disabledByUser&&(this.state="configured",this.startRegistration())}async onSessionEnding(e){if(this.session&&this.session.generation===e.generation){if(this.sessionEndingGeneration=e.generation,this.invalidateRegistration(),this.removalPromise)try{await this.removalPromise}catch{}if(this.isSessionGenerationActive(e.generation)&&(this.bindingPromise&&await this.bindingPromise,this.isSessionGenerationActive(e.generation))){for(const t of this.collectRemovalTargets(e.generation)){const r=await this.removeWithRetry(t,e.generation);if(!this.isSessionGenerationActive(e.generation))return;if(!r){this.emitFailure(Ge.TOKEN_REMOVE_FAILED,"remove",t.channel,t.notifierName,this.lastRemovalError??void 0);break}}this.isSessionGenerationActive(e.generation)&&(this.safeUnregister(),this.clearSessionRuntime())}}}resetSessionRuntime(){this.invalidateRegistration(),this.safeUnregister(),this.clearSessionRuntime()}removePushToken(){return this.session?(this.removalPromise||(this.removalPromise=this.performManualRemoval().finally(()=>{this.removalPromise=null})),this.removalPromise):Promise.reject(new ut("User is not logged in",ot.AUTH_NOT_LOGIN))}startRegistration(){if(!this.config||!this.session||this.disabledByUser)return;const e=this.config,t=this.session.generation,r=++this.registrationVersion;this.state="registering",this.pluginRegistered=!0;try{e.plugin.onRegister(s=>{if(!this.isRegistrationActive(t,r))return;const n=((e,t)=>{if(!tE(e)||200!==e.code||0===e.push_token.trim().length)return null;const r=eE(e.push_type);if("normal"===r)return null;const s=t.certificates[r];return s?{token:e.push_token,channel:r,notifierName:s}:null})(s,e);if(!n){this.state="failed";const t=tE(s)?eE(s.push_type):void 0,r=tE(s)&&200===s.code&&s.push_token.trim().length>0&&void 0!==t&&"normal"!==t&&void 0===e.certificates[t];return void this.emitFailure(Ge.TOKEN_BIND_FAILED,r?"bind":"register",t)}this.enqueueBinding(n)})}catch{this.safeUnregister(),this.state="failed",this.emitFailure(Ge.TOKEN_BIND_FAILED,"register")}}enqueueBinding(e){const t=this.createBindingKey(e);t!==this.successfulKey&&t!==this.exhaustedKey&&t!==this.activeBindingKey&&(this.pendingCandidate=e,this.manualRemovalInProgress||this.bindingPromise||(this.bindingPromise=this.drainBindingQueue().finally(()=>{this.bindingPromise=null,this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress&&this.enqueueBinding(this.pendingCandidate)})))}async drainBindingQueue(){for(;this.pendingCandidate&&this.session&&!this.disabledByUser&&!this.manualRemovalInProgress;){const e=this.pendingCandidate;this.pendingCandidate=null;const t=this.session.generation,r=this.createBindingKey(e);this.activeBindingKey=r,this.state="binding";const s=await this.bindWithRetry(e,t);if(this.activeBindingKey=null,!this.session||this.session.generation!==t||this.disabledByUser)return;s?(this.binding={...e,generation:t,userId:this.session.userId,deviceId:this.session.clientResource},this.successfulKey=r,this.exhaustedKey=null,this.state="bound",this.sessionEndingGeneration===t||this.manualRemovalInProgress||this.dependencies.dispatch(Ge.TOKEN_BOUND,{channel:e.channel,notifierName:e.notifierName})):(this.exhaustedKey=r,this.state="failed",this.sessionEndingGeneration===t||this.manualRemovalInProgress||this.emitFailure(Ge.TOKEN_BIND_FAILED,"bind",e.channel,e.notifierName,this.lastBindingError??void 0))}}async bindWithRetry(e,t){this.lastBindingError=null;for(let s=0;s<=2;s+=1)try{const r=this.session;return!(!r||r.generation!==t)&&(this.lastAttemptedBinding={...e,generation:t,userId:r.userId,deviceId:r.clientResource},await this.dependencies.requestToken({deviceId:r.clientResource,deviceToken:e.token,notifierName:e.notifierName,timeout:5e3}),!0)}catch(r){if(this.lastBindingError=this.toSdkError(r),!this.session||this.session.generation!==t)return!1;if(!this.isRetryable(r)||2===s)return!1;const e=Yr[s]??0;if(!(await this.wait(e)))return!1}return!1}async performManualRemoval(){if(!this.session)throw new ut("User is not logged in",ot.AUTH_NOT_LOGIN);const e=this.session.generation;if(this.manualRemovalInProgress=!0,this.cancelDelays(),this.bindingPromise&&await this.bindingPromise,!this.isSessionGenerationActive(e))throw this.manualRemovalInProgress=!1,new ut("User is not logged in",ot.AUTH_NOT_LOGIN);const t=this.collectRemovalTargets(e);if(0!==t.length)try{for(const r of t)if(await this.dependencies.requestToken({deviceId:r.deviceId,deviceToken:"",notifierName:r.notifierName}),!this.isSessionGenerationActive(e))return;this.disableByUser()}catch(r){const s=this.toSdkError(r),n=t[0];throw n&&this.isSessionGenerationActive(e)&&this.emitFailure(Ge.TOKEN_REMOVE_FAILED,"remove",n.channel,n.notifierName,s),this.manualRemovalInProgress=!1,this.resumePendingBinding(e),s}else this.disableByUser()}async removeWithRetry(e,t){this.lastRemovalError=null;for(let s=0;s<=1;s+=1)try{return await this.dependencies.requestToken({deviceId:e.deviceId,deviceToken:"",notifierName:e.notifierName,timeout:2500}),!0}catch(r){if(this.lastRemovalError=this.toSdkError(r),!this.isSessionGenerationActive(t))return!1;if(!this.isRetryable(r)||1===s)return!1;if(!(await this.wait(500)))return!1}return!1}disableByUser(){this.disabledByUser=!0,this.manualRemovalInProgress=!1,this.invalidateRegistration(),this.safeUnregister(),this.binding=null,this.lastAttemptedBinding=null,this.successfulKey=null,this.exhaustedKey=null,this.state="disabled"}clearSessionRuntime(){this.session=null,this.binding=null,this.lastAttemptedBinding=null,this.manualRemovalInProgress=!1,this.sessionEndingGeneration=null,this.successfulKey=null,this.exhaustedKey=null,this.activeBindingKey=null,this.pendingCandidate=null,this.state=this.disabledByUser?"disabled":this.config?"configured":"unconfigured"}invalidateRegistration(){this.registrationVersion+=1,this.pendingCandidate=null,this.cancelDelays()}cancelDelays(){for(const e of this.delays)clearTimeout(e.timer),e.resolve(!1);this.delays.clear()}collectRemovalTargets(e){const t=[this.binding,this.lastAttemptedBinding].filter(t=>t?.generation===e);return t.filter((e,r)=>t.findIndex(t=>t.deviceId===e.deviceId&&t.notifierName===e.notifierName)===r)}resumePendingBinding(e){if(!this.pendingCandidate||!this.isSessionGenerationActive(e)||this.disabledByUser||this.sessionEndingGeneration===e)return;const t=this.pendingCandidate;this.pendingCandidate=null,this.enqueueBinding(t)}isSessionGenerationActive(e){return this.session?.generation===e}safeUnregister(){if(this.pluginRegistered){this.pluginRegistered=!1;try{this.config?.plugin.unRegister()}catch{Ks("Native push plugin unregister failed")}}}isRegistrationActive(e,t){return this.session?.generation===e&&this.registrationVersion===t&&!this.disabledByUser}createBindingKey(e){const t=this.session;return t?`${t.generation}\0${t.userId}\0${t.clientResource}\0${e.token}\0${e.notifierName}`:""}wait(e){return new Promise(t=>{const r={timer:setTimeout(()=>{this.delays.delete(r),t(!0)},e),resolve:t};this.delays.add(r)})}isRetryable(e){return!(e instanceof ut)||(!0===e.details?.retryable||[ot.REST_NETWORK_ERROR,ot.REST_TIMEOUT,ot.REST_HTTP_ERROR,ot.SERVER_BUSY].includes(e.code))}toSdkError(e){return e instanceof ut?e:new ut("Native push operation failed",ot.UNKNOWN)}emitFailure(e,t,r,s,n){const i=!!n&&this.isRetryable(n);this.dependencies.dispatchFailure(e,{stage:t,...r?{channel:r}:{},...s?{notifierName:s}:{},...n?{code:n.code}:{},retryable:i}),Ks("Native push operation failed",{stage:t,...r?{channel:r}:{},...s?{notifierName:s}:{},...n?{code:n.code}:{},retryable:i})}}const sE=AI(RI,{common:{},apis:{setGlobalSilentMode:{range:"110,1501",localErrors:{setGlobalSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setConversationSilentMode:{range:"110,1501",localErrors:{setConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,httpStatus:400,retryable:!1}}},setPushLanguage:{range:"110,1502",localErrors:{setPushLanguage:{validation_invalid:{code:110,retryable:!1}}},errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,httpStatus:400,retryable:!1}}},uploadPushToken:{range:"110,201,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,retryable:!1}},setNativePush:{validation_invalid:{code:110,retryable:!1}},removePushToken:{auth_not_login:{code:201,retryable:!1}}},errors:{TOKEN_UPLOAD_FAILED:{code:1500,httpStatus:400,retryable:!0}}},getGlobalSilentMode:{range:"1501",errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentMode:{range:"110,1501",localErrors:{getConversationSilentMode:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},clearConversationRemindType:{range:"110,1501",localErrors:{clearConversationRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationSilentModes:{range:"110,1501",localErrors:{getConversationSilentModes:{validation_invalid:{code:110,retryable:!1}}},errors:{SILENT_MODE_OPERATION_FAILED:{code:1501,retryable:!1}}},getConversationListByRemindType:{range:"110",localErrors:{getConversationListByRemindType:{validation_invalid:{code:110,retryable:!1}}},errors:{}},getPushLanguage:{range:"1502",errors:{PUSH_LANGUAGE_OPERATION_FAILED:{code:1502,retryable:!1}}}}}),nE=["singleChat","groupChat"],iE=["ALL","AT","NONE","DEFAULT"],oE=["ALL","AT","NONE"],aE=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),cE=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.eventContext=null,this.nativePushController=new rE({requestToken:async e=>{await this.requestNativePushToken(e)},dispatch:(e,t)=>{this.eventContext?.dispatch?.(e,t)},dispatchFailure:(e,t)=>{this.eventContext?.dispatch?.(e,t)}})}bind(e,t){this.client=e,this.eventContext=t??null}onSessionReady(e){this.nativePushController.onSessionReady(e)}async onSessionEnding(e){await this.nativePushController.onSessionEnding(e)}resetSessionRuntime(){this.nativePushController.resetSessionRuntime()}setNativePush(e){this.nativePushController.configure(e)}removePushToken(){return this.nativePushController.removePushToken()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async uploadPushToken(e){return this.runOperation(async()=>{this.validateUploadPushTokenParams(e),await this.requestNativePushToken(e)})}async requestNativePushToken(e){const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey);Vs("Call native push token operation",{deviceId:e.deviceId,notifierName:e.notifierName,removing:0===e.deviceToken.length}),await r.request(`/${s}/${n}/users/${t.userId}`,{method:"PUT",body:{device_id:e.deviceId,device_token:e.deviceToken,notifier_name:e.notifierName},operation:"uploadPushToken",...void 0!==e.timeout?{timeout:e.timeout}:{}})}async setGlobalSilentMode(e){return this.runOperation(async()=>{this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/notification/user/${t.userId}?resource=${encodeURIComponent(t.clientResource)}`,o=this.buildSilentModePayload(e.rule);Vs("Call setGlobalSilentMode",{mode:e.rule.mode});const a=await r.request(i,{method:"PUT",body:o,operation:"setGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),e.rule)}})}async getGlobalSilentMode(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:r,appName:s}=this.parseAppKey(e.appKey),n=`/${r}/${s}/users/${e.userId}/notification/user/${e.userId}`;Vs("Call getGlobalSilentMode");const i=await t.request(n,{method:"GET",operation:"getGlobalSilentMode"});return{scope:"global",rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(i))}})}async setConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType"),this.validateRuleInput(e.rule,"rule");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`,a=this.buildSilentModePayload(e.rule);Vs("Call setConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType,mode:e.rule.mode});const c=await r.request(o,{method:"PUT",body:a,operation:"setConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(c),e.rule)}})}async getConversationSilentMode(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}`;Vs("Call getConversationSilentMode",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await r.request(o,{method:"GET",operation:"getConversationSilentMode"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a))}})}async clearConversationRemindType(e){return this.runOperation(async()=>{this.validateConversationId(e.conversationId,"conversationId"),this.validateConversationType(e.conversationType,"conversationType");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=this.mapConversationTypeToPath(e.conversationType),o=`/${s}/${n}/users/${t.userId}/notification/${i}/${encodeURIComponent(e.conversationId)}?resource=${encodeURIComponent(t.clientResource)}`;Vs("Call clearConversationRemindType",{conversationId:e.conversationId,conversationType:e.conversationType});const a=await r.request(o,{method:"PUT",body:{type:"DEFAULT"},operation:"clearConversationRemindType"});return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(this.resolveSilentModeRuleSource(a),{remindType:"DEFAULT"})}})}async getConversationSilentModes(e){return this.runOperation(async()=>{this.validateConversationList(e.conversationList,"conversationList");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=e.conversationList.filter(e=>"singleChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),o=e.conversationList.filter(e=>"groupChat"===e.conversationType).map(e=>encodeURIComponent(e.conversationId)).join(","),a=`/${s}/${n}/users/${t.userId}/notification?user=${i}&group=${o}`;Vs("Call getConversationSilentModes",{count:e.conversationList.length});const c=await r.request(a,{method:"GET",operation:"getConversationSilentModes"}),d=this.resolveConversationRuleMap(c,"user"),u=this.resolveConversationRuleMap(c,"group");return{conversations:e.conversationList.map(e=>{const t="singleChat"===e.conversationType?d[e.conversationId]:u[e.conversationId];return{conversationId:e.conversationId,conversationType:e.conversationType,rule:this.normalizeRuleView(t)}})}})}async setPushLanguage(e){await this.runOperation(async()=>{this.validateLanguage(e.language,"language");const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}/notification/language`;Vs("Call setPushLanguage",{language:e.language}),await r.request(i,{method:"PUT",body:{translationLanguage:e.language},operation:"setPushLanguage"})})}async getPushLanguage(e={}){return this.runOperation(async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),{orgName:r,appName:s}=this.parseAppKey(e.appKey),n=`/${r}/${s}/users/${e.userId}/notification/language`;Vs("Call getPushLanguage");const i=await t.request(n,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(i,"")}})}getConversationListByRemindType(e){return this.runOperation(()=>{Vs("Call getConversationListByRemindType",{pageSize:e.pageSize,hasCursor:Boolean(e.cursor)});const t=this.getClientOrThrow(),r=iv({items:t.getCacheManager()?.loadSessionList()??[],pageSize:e.pageSize,cursor:e.cursor});return Promise.resolve(r)})}async runOperation(e){try{return await e()}catch(t){throw this.normalizeSdkError(t)}}normalizeSdkError(e){return e instanceof ut?e:e instanceof Error?new ut(`PushManager operation failed: ${e.message}`,ot.UNKNOWN):new ut("PushManager operation failed",ot.UNKNOWN)}getRestContextOrThrow(){if(!this.client)throw this.buildValidationError("PushManager is not bound to client",[{path:"pushManager.client",message:"PushManager is not bound to client",rule:"required"}]);return this.client.getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Cv(e.restBaseUrl,{errorMap:sE,requestAdapter:this.getClientOrThrow().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}getClientOrThrow(){if(!this.client)throw new ut("PushManager is not bound to client",ot.VALIDATION_REQUIRED);return this.client}parseAppKey(e){const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw this.buildValidationError("Invalid appKey format",[{path:"appKey",message:'appKey must be in format "org#app"',rule:"invalid_format"}]);return{orgName:t[0],appName:t[1]}}validateUploadPushTokenParams(e){this.validateNonEmptyString(e.deviceId,"deviceId"),this.validateNonEmptyString(e.deviceToken,"deviceToken"),this.validateNonEmptyString(e.notifierName,"notifierName")}validateConversationId(e,t){this.validateNonEmptyString(e,t)}validateConversationType(e,t){if("string"!=typeof e||!nE.includes(e))throw this.buildValidationError("Conversation type is not supported",[{path:t,message:"Only singleChat and groupChat are supported",rule:"invalid_format"}])}validateConversationList(e,t){if(!Array.isArray(e)||0===e.length)throw this.buildValidationError("conversationList must be a non-empty array",[{path:t,message:"conversationList must be a non-empty array",rule:"required"}]);if(e.length>20)throw this.buildValidationError("conversationList length must be <= 20",[{path:t,message:"conversationList length exceeds 20",rule:"range"}]);e.forEach((e,r)=>{this.validateConversationId(e.conversationId,`${t}[${r}].conversationId`),this.validateConversationType(e.conversationType,`${t}[${r}].conversationType`)})}validateLanguage(e,t){this.validateNonEmptyString(e,t)}validateNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw this.buildValidationError(`${t} must be a non-empty string`,[{path:t,message:`${t} must be a non-empty string`,rule:"invalid_format"}])}validateRuleInput(e,t){if(!aE(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);switch(e.mode){case"REMIND_TYPE":if(!oE.includes(e.remindType))throw this.buildValidationError("rule.remindType is invalid",[{path:`${t}.remindType`,message:"remindType must be one of ALL/AT/NONE",rule:"invalid_format"}]);this.ensureNoConflictFields(e,t,["mode","remindType"]);break;case"DURATION":if(!Number.isInteger(e.duration)||e.duration<=0)throw this.buildValidationError("rule.duration must be a positive integer",[{path:`${t}.duration`,message:"duration must be a positive integer",rule:"range"}]);this.ensureNoConflictFields(e,t,["mode","duration"]);break;case"INTERVAL":this.validateTimePoint(e.startTime,`${t}.startTime`),this.validateTimePoint(e.endTime,`${t}.endTime`),this.ensureNoConflictFields(e,t,["mode","startTime","endTime"]);break;default:throw this.buildValidationError("rule.mode is invalid",[{path:`${t}.mode`,message:"mode must be one of REMIND_TYPE/DURATION/INTERVAL",rule:"invalid_format"}])}}ensureNoConflictFields(e,t,r){const s=Object.keys(e).find(e=>!r.includes(e));if(s)throw this.buildValidationError("Silent mode rule contains conflicting fields",[{path:`${t}.${s}`,message:`${s} is not allowed when mode is ${e.mode}`,rule:"conflict"}])}validateTimePoint(e,t){if(!aE(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);if(!Number.isInteger(e.hours)||e.hours<0||e.hours>23)throw this.buildValidationError("hours must be between 0 and 23",[{path:`${t}.hours`,message:"hours must be between 0 and 23",rule:"range"}]);if(!Number.isInteger(e.minutes)||e.minutes<0||e.minutes>59)throw this.buildValidationError("minutes must be between 0 and 59",[{path:`${t}.minutes`,message:"minutes must be between 0 and 59",rule:"range"}])}buildSilentModePayload(e){switch(e.mode){case"REMIND_TYPE":return{type:e.remindType};case"DURATION":return{ignoreDuration:6e4*e.duration};case"INTERVAL":return{ignoreInterval:`${this.formatIntervalSegment(e.startTime)}-${this.formatIntervalSegment(e.endTime)}`}}}normalizeRuleView(e,t){const r=this.parseRuleView(e);return r?t?{...this.toRuleViewFromFallback(t),...r}:r:t?this.toRuleViewFromFallback(t):{}}parseRuleView(e){if(!aE(e))return null;const t={},r=this.normalizeRemindType(e.type);null!==r&&(t.remindType=r);const s=e.ignoreDuration;"number"==typeof s&&Number.isInteger(s)&&s>0&&(t.expireTimestamp=s);const n=e.ignoreInterval;if("string"==typeof n){const e=this.parseInterval(n);e&&(t.silentModeStartTime=e.startTime,t.silentModeEndTime=e.endTime)}return void 0!==t.remindType||void 0!==t.expireTimestamp||void 0!==t.silentModeStartTime&&void 0!==t.silentModeEndTime?t:null}parseInterval(e){const t=e.match(/^(\d{1,2}):(\d{1,2})-(\d{1,2}):(\d{1,2})$/);if(!t)return null;const r=Number(t[1]),s=Number(t[2]),n=Number(t[3]),i=Number(t[4]);return Number.isInteger(r)&&Number.isInteger(s)&&Number.isInteger(n)&&Number.isInteger(i)?r<0||r>23||n<0||n>23||s<0||s>59||i<0||i>59?null:{startTime:{hours:r,minutes:s},endTime:{hours:n,minutes:i}}:null}toRuleViewFromFallback(e){if("mode"in e)switch(e.mode){case"REMIND_TYPE":return{remindType:e.remindType};case"DURATION":return{};case"INTERVAL":return{silentModeStartTime:e.startTime,silentModeEndTime:e.endTime}}return e}formatIntervalSegment(e){return`${String(e.hours).padStart(2,"0")}:${String(e.minutes).padStart(2,"0")}`}resolveConversationRuleMap(e,t){if(aE(e.data)){const r=e.data[t];if(aE(r))return r}const r=e[t];return aE(r)?r:{}}resolveSilentModeRuleSource(e){if(!aE(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return aE(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":iE.includes(e)?e:null}resolvePushLanguage(e,t){if("string"==typeof e.translationLanguage&&e.translationLanguage.length>0)return e.translationLanguage;if("string"==typeof e.language&&e.language.length>0)return e.language;if(aE(e.data)){const t=e.data.translationLanguage;if("string"==typeof t&&t.length>0)return t;const r=e.data.language;if("string"==typeof r&&r.length>0)return r}return t}mapConversationTypeToPath(e){return"singleChat"===e?"user":"chatgroup"}buildValidationError(e,t){return new mt(e,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:t}})}};cE.key="pushManager";let dE=cE;const uE=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},lE=(e,t="params.userIds")=>KT(e,t),hE=e=>{const t=lE(e);if(t.length>100)throw((e,t,r,s=ot.VALIDATION_INVALID_FORMAT)=>new mt(e,{code:s,details:{fields:[{path:t,message:e,rule:r}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",ot.SERVICE_LIMIT_EXCEEDED);return{usernames:t}},pE=(e,t)=>{const r=(e=>lE(e))(t);return`${uE(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},mE=(e,t)=>{switch(e){case"nickname":return"string"==typeof t?{nickname:t}:null;case"avatarurl":case"avatarUrl":return"string"==typeof t?{avatarUrl:t}:null;case"mail":return"string"==typeof t?{mail:t}:null;case"phone":return"string"==typeof t?{phone:t}:null;case"gender":return"string"==typeof t||"number"==typeof t||"boolean"==typeof t?{gender:t}:null;case"sign":return"string"==typeof t?{sign:t}:null;case"birth":return"string"==typeof t?{birth:t}:null;case"ext":return"string"==typeof t?{ext:t}:null;default:return null}},gE=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],fE=AI(RI,{common:{},apis:{updateOwnUserInfo:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfo:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfoByAttribute:{range:"4,110,204,303,505,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{service_not_enabled:{code:505,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"user metadata service not allow"},data_length_exceed:{code:901,httpStatus:403,retryable:!1,matchField:"desc",matchPattern:"exceeds"},concurrent_update_conflict:{code:303,httpStatus:409,retryable:!0,matchField:"desc",matchPattern:"Concurrent"},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByUserId:{range:"4,110,204,900",localErrors:{getUserInfoByUserId:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},getUserInfoByAttribute:{range:"4,110,204,900",localErrors:{getUserInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{usercount_exceed:{code:900,httpStatus:400,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},subscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},unsubscribeUsersInfo:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}},getSubscribedUsers:{range:"4,202,210,303,1600,1601",errors:{unauthorized:{code:202,httpStatus:401,retryable:!0},forbidden:{code:210,httpStatus:403,aliases:["operation forbidden"],matchField:"error_description",matchPattern:"metadata subscription not allow",retryable:!1},subscriber_limit_exceeded:{code:1600,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscription count exceeds limit",retryable:!1},target_limit_exceeded:{code:1601,httpStatus:400,matchField:"error_description",matchPattern:"metadata subscribed count exceeds limit",retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0},server_unknown_error:{code:303,httpStatus:500,retryable:!0}}}}}),yE=class{constructor(){this.capabilities=["userInfo:read","rawNotify:userInfo"],this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e,this.eventContext=t??null}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}handleRawNotify(e){if("userInfo"!==e.type)return;const t=this.client,r=t?.getCacheManager();if(!t||!r||!t.getCurrentUserId())return;const s=e.payload,n=(e=>{const t={};for(const[r,s]of Object.entries(e.metadata)){const e=mE(r,s);e&&Object.assign(t,e)}return{userId:e.userId,attributes:t,lastModified:e.lastModified,source:"subscribe_metadata_updated"===e.notifyType?"subscription":"contact_metadata_updated"===e.notifyType?"contact":"own"}})(s);if(!n)return;const i=r.applyUserInfoNotifyPatch(n);if(!i.applied)return void Vs("User-info notify ignored",{userId:n.userId,notifyType:s.notifyType,reason:i.reason,lastModified:n.lastModified});if(r.updateUserInfoSummaryFromRuntime(n.userId),t.refreshConversationDisplayFromUserInfos?.([{userId:n.userId,lastModified:n.lastModified}]),"subscription"===n.source)return void this.eventContext?.dispatch?.("onUserInfoUpdated",[i.record.profile]);if("own"===n.source)return void this.eventContext?.dispatch?.("onOwnInfoUpdated",i.record.profile);const o=t.getContactSnapshot()?.items.find(e=>e.userId===n.userId);this.eventContext?.dispatch?.(Z,{userInfo:i.record.profile,contact:o})}async getUserInfoByUserId(e){return this.runOperation("getUserInfoByUserId",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=JT(KT(e.userIds,"params.userIds")),n=HT(t);Vs("UserInfoManager getUserInfoByUserId",{userIds:s.targets});const i=await r.request(n,{method:"POST",body:s,operation:"getUserInfoByUserId"}),o=this.normalizeFetchEnvelope(i,s.targets);return this.writeCache(o),this.completeFetchedProfiles(o,s.targets)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(n=KT(e.userIds,"params.userIds"),i=zT(e.attributes,"params.attributes"),{targets:KT(n),properties:zT(i).map(e=>VT(e,"params.attributes"))});var n,i;const o=HT(t);Vs("UserInfoManager getUserInfoByAttribute",{userIds:s.targets,attributes:s.properties});const a=await r.request(o,{method:"POST",body:s,operation:"getUserInfoByAttribute"}),c=this.normalizeFetchEnvelope(a,s.targets);return this.writeCache(c),this.completeFetchedProfiles(c,s.targets)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>uE(e))(t),n=hE(e.userIds);Vs("UserInfoManager subscribeUsersInfo",{userIds:n.usernames}),await r.request(s,{method:"POST",body:n,operation:"subscribeUsersInfo"})})}async unsubscribeUsersInfo(e){return this.runOperation("unsubscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=pE(t,e.userIds);Vs("UserInfoManager unsubscribeUsersInfo",{userIds:KT(e.userIds,"params.userIds")}),await r.request(s,{method:"DELETE",operation:"unsubscribeUsersInfo"})})}async getSubscribedUsers(){return this.runOperation("getSubscribedUsers",async()=>{const e=this.getRestContextOrThrow(),t=this.getRestClient(e),r=(e=>uE(e))(e);Vs("UserInfoManager getSubscribedUsers",{userId:e.userId});const s=(e=>{const t=e&&"object"==typeof e?e:null;if(!t||!Array.isArray(t.data))return[];const r=[],s=new Set;for(const n of t.data){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),r.push(e))}return r})(await t.request(r,{method:"GET",operation:"getSubscribedUsers"}));return 0===s.length?[]:await this.getUserInfoByUserId({userIds:s})})}async updateOwnInfo(e){return this.runOperation("updateOwnInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>{const t=[];if(tC(t,"nickname",e.nickname,"params.nickname"),tC(t,"avatarurl",e.avatarUrl,"params.avatarUrl"),tC(t,"mail",e.mail,"params.mail"),tC(t,"phone",e.phone,"params.phone"),tC(t,"gender",e.gender,"params.gender"),tC(t,"sign",e.sign,"params.sign"),tC(t,"birth",e.birth,"params.birth"),tC(t,"ext",e.ext,"params.ext"),0===t.length)throw qT("params must include at least one updatable field","params","required");return rC(t)})(e),n=WT(t);Vs("UserInfoManager updateOwnInfo",{userId:t.userId,fields:this.getUpdatedFieldNames(e)});const i=await r.request(n,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s,operation:"updateOwnInfo"}),o=this.normalizeUpdateEnvelope(i,t.userId,this.buildFallbackProfile(t.userId,e));return this.writeCache([o]),this.dispatchSelfUpdate(o.profile),o.profile})}async updateOwnInfoByAttribute(e,t){return this.runOperation("updateOwnInfoByAttribute",async()=>{const r=this.getRestContextOrThrow(),s=this.getRestClient(r),n=((e,t)=>{const r=VT(e,"attribute"),s=jT(t,"value");if("gender"!==r&&"string"!=typeof s)throw qT("value must be a string","value","invalid_format");return rC([[r,String(s)]])})(e,t),i=WT(r);Vs("UserInfoManager updateOwnInfoByAttribute",{userId:r.userId,attribute:e});const o=await s.request(i,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n,operation:"updateOwnInfoByAttribute"}),a=this.normalizeUpdateEnvelope(o,r.userId,{userId:r.userId,[e]:t});return this.writeCache([a]),this.dispatchSelfUpdate(a.profile),a.profile})}async runOperation(e,t){try{return await t()}catch(r){throw this.normalizeOperationError(e,r)}}normalizeOperationError(e,t){return t instanceof ut?t:(Ks("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new ut(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new mt("UserInfoManager is not bound to client",{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:"userInfoManager.client",message:"client is required",rule:"required"}]}})}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new Cv(e.restBaseUrl,{errorMap:fE,requestAdapter:this.client?.getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}normalizeFetchEnvelope(e,t){return XT(e,t)}completeFetchedProfiles(e,t){const r=new Map(e.map(e=>[e.profile.userId,e.profile]));return t.map(e=>r.get(e)??{userId:e})}normalizeUpdateEnvelope(e,t,r){const s=Uu(e)?e:null,n=(s&&Uu(s.data)?s.data:null)??(s&&this.looksLikeUserInfoAttributes(s)?s:null),i=s&&"number"==typeof s.lastModified?s.lastModified:void 0;return{profile:n?this.toUserInfo(t,n):{userId:t,...r??{}},lastModified:i}}toUserInfo(e,t){const r={userId:e};return"string"==typeof t.nickname&&(r.nickname=t.nickname),"string"==typeof t.avatarurl?r.avatarUrl=t.avatarurl:"string"==typeof t.avatarUrl&&(r.avatarUrl=t.avatarUrl),"string"==typeof t.mail&&(r.mail=t.mail),"string"==typeof t.phone&&(r.phone=t.phone),"string"!=typeof t.gender&&"number"!=typeof t.gender&&"boolean"!=typeof t.gender||(r.gender=t.gender),"string"==typeof t.sign&&(r.sign=t.sign),"string"==typeof t.birth&&(r.birth=t.birth),"string"==typeof t.ext&&(r.ext=t.ext),r}looksLikeUserInfoAttributes(e){return!!Uu(e)&&("nickname"in e||"avatarurl"in e||"avatarUrl"in e||"mail"in e||"phone"in e||"gender"in e||"sign"in e||"birth"in e||"ext"in e)}buildFallbackProfile(e,t){const r={userId:e},s=r;for(const n of gE)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return gE.filter(t=>t in e)}projectToSummary(e){const t=Date.now(),r=Bl(e.lastModified);return{userId:e.profile.userId,nickname:e.profile.nickname,avatarUrl:e.profile.avatarUrl,sign:e.profile.sign,ext:e.profile.ext,userInfoUpdateTime:r,lastSyncAt:t,lastAccess:t,lastUpdate:e.lastModified??t}}writeCache(e){if(!this.client||0===e.length)return;const t=this.client.getCacheManager();t&&("function"==typeof t.upsertRuntimeUserInfos&&t.upsertRuntimeUserInfos(e.map(e=>({profile:e.profile,lastModified:e.lastModified,source:e.profile.userId===this.client?.getRestContext().userId?"update":"fetch"}))),t.setUserInfoSummaries(e.map(e=>this.projectToSummary(e))))}dispatchSelfUpdate(e){this.client?.dispatchOwnInfoUpdated?.(e)}};yE.key="userInfoManager";let vE=yE;return e.AuthenticationError=pt,e.CONVERSATION_MARK={MARK_0:0,MARK_1:1,MARK_2:2,MARK_3:3,MARK_4:4,MARK_5:5,MARK_6:6,MARK_7:7,MARK_8:8,MARK_9:9,MARK_10:10,MARK_11:11,MARK_12:12,MARK_13:13,MARK_14:14,MARK_15:15,MARK_16:16,MARK_17:17,MARK_18:18,MARK_19:19},e.CacheManager=fy,e.ChatClient=XI,e.ChatManager=w_,e.ChatRoom=H_,e.ChatRoomManager=oC,e.ChatThread=A_,e.ChatThreadManager=z_,e.ConnectionError=ht,e.ContactManager=xC,e.Group=FC,e.GroupManager=HS,e.ImageType={ORIGINAL:"original",LARGE:"large"},e.LogEventName=V,e.MessageReceiveError=ft,e.MessageSendError=gt,e.NetworkError=lt,e.PresenceManager=QS,e.PushEventName=Ge,e.PushManager=dE,e.RUNTIME_PLATFORMS=Qs,e.RestBusinessError=It,e.RestTransportError=vt,e.SDKError=ut,e.StorageError=yt,e.StreamMessageStatus=nt,e.UploadError=bt,e.UserInfoManager=vE,e.ValidationError=mt,e.createPlatformAdapter=xd,e.detectRuntimePlatform=(e,t)=>Mn(t,e).platform,e.isSDKError=function(e){if(e instanceof ut)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},e.setConsoleLogEnabled=function(e){!function(e){Bs instanceof Fs&&Bs.setConsoleEnabled(e)}(e)},e.setLogLevel=function(e){!function(e){Bs instanceof Fs&&Bs.setLevel(e)}(e)},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
|