easemob-websdk 5.1.1 → 5.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/bundle/im-sdk-web.iife.js +1 -1
  2. package/cache/cache-manager.d.ts +11 -3
  3. package/cache/cache-types.d.ts +13 -2
  4. package/chat-client.d.ts +48 -8
  5. package/chunks/{chat-manager-QJCNq-in.cjs → chat-manager-BI-6bEor.cjs} +1 -1
  6. package/chunks/{chat-manager-QxcfwVLg.js → chat-manager-nXOTpJ01.js} +2 -2
  7. package/chunks/common-DHQukb7J.js +1 -0
  8. package/chunks/common-tHGz9VBk.cjs +1 -0
  9. package/chunks/event-system-DguqwFpc.js +1 -0
  10. package/chunks/{event-system-COBJFEIq.cjs → event-system-TYhmgy4K.cjs} +1 -1
  11. package/chunks/group-user-info-resolver-B-dyr__b.cjs +1 -0
  12. package/chunks/group-user-info-resolver-D6AQAHEE.js +1 -0
  13. package/chunks/index-CneY58NJ.js +1 -0
  14. package/chunks/{index-DIV5mZP8.cjs → index-DJPAjXAp.cjs} +1 -1
  15. package/chunks/index-DtWkVcfb.cjs +1 -0
  16. package/chunks/index-DxjmfFL7.js +1 -0
  17. package/chunks/push-manager-CSIKhoPe.js +1 -0
  18. package/chunks/push-manager-D7RDsKuv.cjs +1 -0
  19. package/chunks/session-list-query-C3iQvQxK.cjs +1 -0
  20. package/chunks/session-list-query-Cdpiw_IZ.js +1 -0
  21. package/chunks/{user-info-DfbCp80h.js → user-info-7QzMa7bR.js} +1 -1
  22. package/chunks/{user-info-DsDDTJrw.cjs → user-info-DH3aE1gm.cjs} +1 -1
  23. package/config/timeouts.d.ts +11 -0
  24. package/core/connection/connection-manager.d.ts +18 -1
  25. package/core/connection/login-deadline.d.ts +22 -0
  26. package/core/events/event-hub.d.ts +1 -0
  27. package/core/index.d.ts +8 -1
  28. package/core/message/attachment-downloader.d.ts +1 -1
  29. package/core/session-list-sync/session-list-message-events.d.ts +9 -0
  30. package/core/session-list-sync/session-list-sync-controller.d.ts +5 -0
  31. package/index.cjs +1 -1
  32. package/index.d.ts +11 -9
  33. package/index.js +2 -2
  34. package/log.d.ts +27 -0
  35. package/managers/chat/index.cjs +1 -1
  36. package/managers/chat/index.js +1 -1
  37. package/managers/chat-thread/index.cjs +1 -1
  38. package/managers/chat-thread/index.js +1 -1
  39. package/managers/chatroom/chatroom.d.ts +1 -1
  40. package/managers/chatroom/index.cjs +1 -1
  41. package/managers/chatroom/index.js +1 -1
  42. package/managers/chatroom-manager.d.ts +6 -1
  43. package/managers/contact/index.cjs +1 -1
  44. package/managers/contact/index.js +1 -1
  45. package/managers/group/index.cjs +1 -1
  46. package/managers/group/index.js +1 -1
  47. package/managers/presence/index.cjs +1 -1
  48. package/managers/presence/index.js +1 -1
  49. package/managers/push/index.cjs +1 -1
  50. package/managers/push/index.d.ts +2 -0
  51. package/managers/push/index.js +1 -1
  52. package/managers/push/native-push-controller.d.ts +62 -0
  53. package/managers/push/native-push-normalizer.d.ts +15 -0
  54. package/managers/push-manager.d.ts +63 -4
  55. package/managers/user-info/index.cjs +1 -1
  56. package/managers/user-info/index.js +1 -1
  57. package/managers/user-info-manager.d.ts +3 -2
  58. package/message/combine-payload-codec.d.ts +2 -1
  59. package/message/message-snapshot.d.ts +8 -0
  60. package/package.json +1 -1
  61. package/platform/index.d.ts +1 -1
  62. package/platform/request/default-request-adapter.d.ts +7 -0
  63. package/platform/socket/default-socket-adapter.d.ts +6 -0
  64. package/platform/types.d.ts +22 -2
  65. package/platform/upload/legacy-multipart-upload.d.ts +14 -0
  66. package/platform/upload/legacy-simple-upload.d.ts +3 -0
  67. package/protocol/msync/codec.d.ts +6 -21
  68. package/protocol/msync/message-identity.d.ts +2 -0
  69. package/protocol/msync/message-payload-decoder.d.ts +35 -0
  70. package/protocol/session-list/gateway.d.ts +8 -1
  71. package/protocol/session-list/payload-decoder.d.ts +12 -0
  72. package/rest/client.d.ts +0 -4
  73. package/rest/contact-management.d.ts +1 -0
  74. package/rest/dns-config.d.ts +6 -1
  75. package/rest/error-maps/chatroom.d.ts +6 -0
  76. package/rest/error-maps/common.d.ts +3 -0
  77. package/rest/error-maps/contact.d.ts +8 -3
  78. package/rest/error-maps/push.d.ts +13 -1
  79. package/rest/error-maps/user-info.d.ts +51 -3
  80. package/rest/service-url.d.ts +6 -0
  81. package/types/chat-client.d.ts +16 -9
  82. package/types/chatroom.d.ts +3 -34
  83. package/types/conversation.d.ts +27 -20
  84. package/types/event-system.d.ts +52 -1
  85. package/types/index.d.ts +5 -7
  86. package/types/log.d.ts +19 -0
  87. package/types/manager.d.ts +31 -0
  88. package/types/push.d.ts +77 -0
  89. package/upload/attachment-uploader.d.ts +1 -5
  90. package/upload/multipart-upload.d.ts +4 -14
  91. package/upload/simple-upload.d.ts +4 -3
  92. package/upload/types.d.ts +2 -1
  93. package/utils/error-codes.generated.d.ts +1 -0
  94. package/utils/log-reporter.d.ts +1 -7
  95. package/utils/logger.d.ts +28 -2
  96. package/utils/session-message-recipient.d.ts +11 -0
  97. package/validators/chat-client.d.ts +22 -50
  98. package/validators/message-create.d.ts +18 -18
  99. package/chunks/common-BIpcR2uQ.cjs +0 -1
  100. package/chunks/common-D_DfwSd3.js +0 -1
  101. package/chunks/event-system-D6IJA0C4.js +0 -1
  102. package/chunks/group-user-info-resolver-Ds35Z1Uf.cjs +0 -1
  103. package/chunks/group-user-info-resolver-lEtRdWli.js +0 -1
  104. package/chunks/index-Baofxzfc.cjs +0 -1
  105. package/chunks/index-CKbroPac.js +0 -1
  106. package/chunks/index-DPi6gEFw.js +0 -1
  107. package/chunks/session-list-query-C4OQMvPf.cjs +0 -1
  108. package/chunks/session-list-query-rynxSxtv.js +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",b="__internal:onMessageSent",I="login",w="reconnect",C="online",S="offline-recover",T="heartbeat-failed",_="send-timeout",R="close",A="error",M="limit",E="offline",U="token-expired",N="onMessage",k="onStreamMessage",O="onConversationListUpdate",x="onMessageReadReceipts",L="onMessageDelivered",P="onMessageRecalled",D="onMessageUpdated",q="onReactionChanged",B="onPinnedMessageChanged",$="onMultiDeviceContact",F="onMultiDeviceConversation",G="onSyncDataStart",j="onSyncDataFinished",z="onPresenceStatusChange",K="onContactInvited",H="onContactDeleted",V="onContactAdded",W="onContactRefuse",J="onContactAgreed",Z="onContactInfoUpdated",Q="onInvitationReceived",Y="onRequestToJoinReceived",X="onRequestToJoinAccepted",ee="onRequestToJoinDeclined",te="onInvitationAccepted",re="onInvitationDeclined",se="onUserRemoved",ne="onGroupDestroyed",ie="onAutoAcceptInvitationFromGroup",oe="onMuteListAdded",ae="onMuteListRemoved",ce="onAllowListAdded",de="onAllowListRemoved",ue="onAllMemberMuteStateChanged",le="onAdminAdded",he="onAdminRemoved",pe="onOwnerChanged",me="onMembersJoined",fe="onMembersExited",ge="onAnnouncementChanged",ye="onSharedFileAdded",ve="onSharedFileDeleted",be="onGroupInfoChanged",Ie="onGroupDisabledChanged",we="onGroupMemberAttributeChanged",Ce="onUserGroupNamecardUpdated",Se="__chatroom:onChatRoomDestroyed",Te="__chatroom:onMembersJoined",_e="__chatroom:onMembersExited",Re="__chatroom:onRemovedFromChatRoom",Ae="__chatroom:onMuteListAdded",Me="__chatroom:onMuteListRemoved",Ee="__chatroom:onAllowListAdded",Ue="__chatroom:onAllowListRemoved",Ne="__chatroom:onAllMemberMuteStateChanged",ke="__chatroom:onAdminAdded",Oe="__chatroom:onAdminRemoved",xe="__chatroom:onOwnerChanged",Le="__chatroom:onAnnouncementChanged",Pe="__chatroom:onChatRoomInfoChanged",De="__chatroom:onAttributesUpdate",qe="__chatroom:onAttributesRemoved",Be="onChatRoomDestroyed",$e="onMembersJoined",Fe="onMembersExited",Ge="onRemovedFromChatRoom",je="onMuteListAdded",ze="onMuteListRemoved",Ke="onAllowListAdded",He="onAllowListRemoved",Ve="onAllMemberMuteStateChanged",We="onAdminAdded",Je="onAdminRemoved",Ze="onOwnerChanged",Qe="onAnnouncementChanged",Ye="onChatRoomInfoChanged",Xe="onAttributesUpdate",et="onAttributesRemoved",rt={START:"STREAM_START",START_COMPLETED:"STREAM_START_COMPLETED",IN_PROGRESS:"STREAM_IN_PROGRESS",COMPLETED:"STREAM_COMPLETED",FULL:"STREAM_FULL",ERROR:"STREAM_ERROR"};function st(e){return"object"==typeof e.stream&&null!==e.stream}const nt=110,it=110,ot=110,at=200,ct=201,dt=202,ut=210,lt=108,ht=213,pt=214,mt=215,ft=301,gt=300,yt=1,vt=301,bt=202,It=300,wt=304,Ct=3,St=300,Tt=301,_t=303,Rt=1,At=500,Mt=500,Et=222,Ut=111,Nt=302,kt=400,Ot=401,xt=407,Lt=501,Pt=502,Dt=504,qt=505,Bt=506,$t=507,Ft=508,Gt=509,jt=510,zt=511,Kt=206,Ht=207,Vt=216,Wt=217,Jt=218,Zt=219,Qt=220,Yt=221,Xt=305,er=403,tr=405,rr=406,sr=1200,nr=1299,ir=303,or=110,ar=4,cr=4,dr=500,ur=2,lr=500,hr=2,pr=301,mr=303,fr=303,gr=602,yr=603,vr=606,br=607,Ir=703,wr=1700,Cr=1701,Sr=1702,Tr=1703,_r=1704,Rr=1110,Ar=1111,Mr=1112,Er=1113,Ur=407,Nr=408,kr=409,Or=410,xr=411,Lr=110,Pr=100,Dr=405,qr=402,Br=301,$r=1,Fr=4,Gr=1,jr="[REDACTED]",zr=e=>{if(!e)return"";const t=e.includes("?"),r=e.includes("#");try{return((e,t,r)=>(e.username&&(e.username=jr),e.password&&(e.password=jr),e.search=t?`?${jr}`:"",e.hash=r?`#${jr}`:"",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)}?${jr}`}},Kr=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>"url"===e.toLowerCase()&&"string"==typeof t?[e,zr(t)]:[e,t]));class Hr extends Error{constructor(e,t=Gr,r){super(e),this.name="SDKError",this.code=t,this.details=r?.details?Kr(r.details):void 0,Error.captureStackTrace&&Error.captureStackTrace(this,Hr)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class Vr extends Hr{constructor(e,t){super(e,t?.code??hr,t),this.name="NetworkError"}}class Wr extends Hr{constructor(e,t){super(e,t?.code??gt,t),this.name="ConnectionError"}}class Jr extends Hr{constructor(e,t){super(e,t?.code??dt,t),this.name="AuthenticationError"}}class Zr extends Hr{constructor(e,t){super(e,t?.code??ot,t),this.name="ValidationError"}}class Qr extends Hr{constructor(e,t){super(e,t?.code??_t,t),this.name="MessageSendError"}}class Yr extends Hr{constructor(e,t){super(e,t?.code??Mt,t),this.name="MessageReceiveError"}}class Xr extends Hr{constructor(e,t){super(e,t?.code??Ct,t),this.name="StorageError"}}class es extends Hr{constructor(e,t){super(e,t?.code??hr,t),this.name="RestTransportError"}}class ts extends Hr{constructor(e,t){super(e,t?.code??fr,t),this.name="RestBusinessError"}}class rs extends Hr{constructor(e,t){super(e,t?.code??qr,t),this.name="UploadError"}}const ss=0,ns=1,is=2,os=3,as=4,cs=0,ds=1,us=2,ls=3,hs=4,ps=5,ms=6,fs=7,gs=8,ys=0,vs=1,bs=2,Is=3,ws=4,Cs=5,Ss=6,Ts=7,_s=8,Rs=0,As=1,Ms=2,Es=3,Us=4,Ns=0,Os=1,xs=2,Ls=3,Ps=5,Ds=0,qs=1,Bs=2,$s=0,Fs=0,Gs=2,js=0,zs=1,Ks=2,Hs=3,Vs=4,Ws=5,Js=6,Zs=7,Qs=8,Ys=9,Xs=10,en=11,tn=12,rn=13,sn=14,nn=15,on=16,an=17,cn=18,dn=19,un=20,ln=1,hn=2,pn=3,mn=4,fn=5,gn=6,yn=7,vn=8,bn="Sorry, user register limit",In="Sorry, user register rate limit",wn="Sorry, token expired",Cn="Sorry, token or password does not match login info",Sn="Sorry, user not found",Tn="Sorry, the app month live count limit",_n="Sorry, the app day live count limit",Rn="Sorry, the app online count limit",An={[zs]:dt,[Ks]:dt,[Hs]:nt,[Vs]:it,[Ws]:gt,[Js]:lt,[Zs]:ut,[dn]:ut,[Qs]:gt,[Ys]:Gr,[Xs]:Gr,[en]:ht,[tn]:ut,[rn]:pt,[sn]:Fr,[nn]:mt,[on]:Gr,[an]:Gr,[cn]:Mt,[un]:Qt},Mn=new Set([zs,Ks,Hs,Vs,Js,Zs,dn,Ys,Xs,en,tn,rn,sn,nn,on,an,cn,un]),En={[bn]:Fr,[In]:Fr,[wn]:lt,[Cn]:dt,[Sn]:dt,blocked:Et,"group not found":vr,"illegal chatroom tag":nt,"not in group or chatroom":gr,"exceed recall time limit":Dt,"message recall disabled":qt,"group ack not open":qt,"group ack msg permission denied":yr,"the message has expired":Bt,"limit send group ack msg":Fr,"not in group or chatroom white list":$t,nonroster:Yt,"group is disabled":br,"roaming is not open":qt,"Sorry, message does not exist":nt,"Sorry, edit limit reached":Fr,"Sorry, You do not have permission":ut,"Sorry, format is incorrect":nt,"Sorry, edit is not available":Xt,"Sorry, edit fail":zt},Un=[["limit directed users",Fr],["no permission to recall message",ut]],Nn={[Tn]:Fr,[_n]:Fr,[Rn]:Fr,"sensitive words":Lt,"blocked by mod_antispam":Lt,"user is mute":Zt,"traffic limit":Gt,"Sorry, data is too large":jt},kn=(e,t)=>{if("number"!=typeof e)return{code:Gr,retryable:!0};const r=((e,t)=>{if(t){if(e===zs){const e=En[t];if(void 0!==e)return e;for(const[r,s]of Un)if(t.includes(r))return s;try{const e=JSON.parse(t);if("moderation"===e.error_type)return sr;if("string"==typeof e.error_type)return nr}catch{}return}return e===Zs?Nn[t]:e===dn?Ft:e===nn?mt:void 0}})(e,t);return{code:r??(An[e]??Gr),retryable:!Mn.has(e)}},On={[Fr]:"Message operation exceeded a service limit",[lt]:"Message cannot be sent because the authentication token expired",[nt]:"Message cannot be sent because the request is invalid",[dt]:"Message cannot be sent because authentication failed",[ut]:"Message operation is forbidden",[ht]:"Message cannot be sent because the account is bound to another device",[pt]:"Message cannot be sent because the account is logged in on too many devices",[mt]:"Message cannot be sent because the user is muted in the group or chat room",[Et]:"Message cannot be sent because you are blocked by the recipient",[Zt]:"Message cannot be sent because the user is globally muted",[Qt]:"Message cannot be sent because the current device has changed",[Yt]:"Message cannot be sent because the recipient is not in your contact list",[gt]:"Message cannot be sent because the server is unreachable",[Xt]:"Message editing is not available",[Mt]:"Message processing failed",[Lt]:"Message contains prohibited content",[Pt]:"Message sending traffic limit exceeded",[Dt]:"The message recall time limit has been exceeded",[qt]:"The required messaging service is not enabled",[Bt]:"The message has expired",[$t]:"The user is not in the group or chat room allowlist",[Ft]:"The message was blocked by external logic",[Gt]:"Message sending rate limit exceeded",[jt]:"Message size exceeds the limit",[zt]:"Message editing failed",[gr]:"The user is not in the group or chat room",[yr]:"The user does not have permission to perform this group message operation",[vr]:"The group does not exist",[br]:"The group is disabled",[sr]:"The message was rejected by content moderation",[nr]:"The message was rejected by a third-party service"},xn=3e5,Ln={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"},Pn=e=>"undefined"!=typeof Blob&&e instanceof Blob,Dn=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),r=t.length>0?t[t.length-1]:void 0;if(r)return r},qn=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const r=e.slice(t+1).toLowerCase();return Ln[r]},Bn=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t&&t.length>0)return t}},$n=e=>{const t=e.file,r=e.sourceMeta,s=t.name||(r?Bn(r,["name","fileName","filename"]):void 0),n=e.file.type||(r?Bn(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=Fn({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}},Fn=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),Gn=e=>{const{file:t,fallbackName:r,fallbackMimeType:s,fallbackSize:n}=e,i=(e=>{if(Pn(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(Pn(e))return e}})(t);if(i)return $n({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=Dn(t.path),i=Fn({fileName:t.name??e,fileType:t.type??qn(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=Dn(t.uri),i=Fn({fileName:t.name??e,fileType:t.type??qn(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=Fn({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}},jn=5242880,zn=5242880,Kn="CHAT",Hn="GROUP",Vn="ROOM",Wn="original",Jn="large",Zn=e=>/^https?:\/\//i.test(e),Qn=e=>{const t=e.split("#");if(2!==t.length||!t[0]||!t[1])throw new rs("Invalid appKey for upload",{code:Pr,details:{appKey:e}});return{orgName:t[0],appName:t[1]}},Yn=e=>"singleChat"===e?Kn:"groupChat"===e?Hn:Vn,Xn=(e,t)=>ti(e,{size:t}),ei=e=>{try{return decodeURIComponent(e)}catch{return e}},ti=(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&&ei(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}`:""}`},ri=(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:ti(e,r)},si=e=>{const t=(r=e.messageType,s=e.imageType,"image"!==r?"attachment":s===Wn?"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"}},ni=(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=ei(t),n=ei(r);return"size"!==s||!["big","large","thumbnail","small"].includes(n)}).join("&");return`${s}${i?`?${i}`:""}${r?`#${r}`:""}`})(e);return{originalImageUrl:r,bigImageUrl:Xn(r,"large"),thumbnailUrl:Xn(r,"small")}},ii=e=>e===Wn?"origin":"large",oi=e=>2===e?Jn:Wn,ai=e=>{const t=e.response.entities?.[0];if(!t?.uuid)throw new rs("Upload response missing uuid",{code:qr,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??Jn)===Wn;return{...ni(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}},ci=e=>new Promise(t=>{setTimeout(t,e)});const di=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 ci(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=Qn(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}}},ui="[MASKED]",li=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),hi=e=>!!e&&li.has((e=>e.toLowerCase())(e)),pi=(e,t,r)=>{const s=r??new WeakSet;if("string"==typeof e)return((e,t)=>hi(t)?ui: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=>pi(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))hi(r)?t[r]=ui:t[r]=pi(n,r,s);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},mi="undefined"!=typeof document,fi={DEBUG:0,WARN:1,ERROR:2};class gi{constructor(e="WARN"){this.level=e}setLevel(e){this.level=e}shouldLog(e){return fi[e]>=fi[this.level]}emit(e,t,r){const s=(e=>{const t=new WeakSet;return e.map(e=>pi(e,void 0,t))})(r),n=((e,t,r)=>({timestamp:(new Date).toISOString(),level:e,message:t,args:r}))(e,t,s);di.append(n);const i=new Date,o=`[Chat][${e}][${`${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}:${String(i.getSeconds()).padStart(2,"0")}.${String(i.getMilliseconds()).padStart(3,"0")}`}]`;mi?console.log(`%c${o}`,"color: rgb(0, 157, 255); font-weight: bold",t,...s):console.log(o,t,...s)}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 yi=new gi;function vi(e){di.setState(e)}function bi(e){di.updateContext(e)}async function Ii(){await di.reportNow()}function wi(){di.stop()}const Ci=(e,...t)=>yi.debug(e,...t),Si=(e,...t)=>yi.warn(e,...t),Ti=(e,...t)=>yi.error(e,...t),_i=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)},Ri=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 Ai{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 Mi={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"},Ei="init",Ui="request",Ni="upload",ki="socket",Oi="proto",xi="runtime",Li="PLATFORM_INIT_FAILED",Pi="PLATFORM_MISSING_CAPABILITY",Di="PLATFORM_REQUEST_FAILED",qi="PLATFORM_UPLOAD_FAILED",Bi="PLATFORM_SOCKET_FAILED",$i="PLATFORM_PROTO_FAILED",Fi=(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=Kr(t.details)),r},Gi=0,ji=1,zi=2,Ki=3,Hi=["__uniConfig","skipWaiting","registration","navigator","process","window","document","localStorage","fetch","WebSocket","XMLHttpRequest","FormData","TextEncoder","TextDecoder","crypto"],Vi=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 Hi)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}:{}})},Wi={web:Mi.WEB,"mp-weixin":Mi.WECHAT_MINIAPP,"mp-alipay":Mi.ALIPAY_MINIAPP,"mp-baidu":Mi.BAIDU_MINIAPP,"mp-toutiao":Mi.TOUTIAO_MINIAPP,"mp-lark":Mi.LARK_MINIAPP,"mp-qq":Mi.QQ_MINIAPP,"mp-kuaishou":Mi.KUAISHOU_MINIAPP,"mp-jd":Mi.JD_MINIAPP,"mp-360":Mi.MINIAPP_360,"mp-harmony":Mi.HARMONY_MINIAPP,"quickapp-webview":Mi.QUICKAPP,"quickapp-webview-union":Mi.QUICKAPP,"quickapp-webview-huawei":Mi.QUICKAPP},Ji=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},Zi=e=>(e=>Ji(e,"canIUse")&&Ji(e,"getSystemInfo"))(e)||(e=>Ji(e,"request")&&Ji(e,"connectSocket"))(e),Qi=e=>Ji(e,"request")&&Ji(e,"connectSocket")&&Ji(e,"uploadFile"),Yi=(e,t)=>t===Mi.WECHAT_MINIAPP?e.wx:t===Mi.QQ_MINIAPP?e.qq:t===Mi.TOUTIAO_MINIAPP?e.tt:t===Mi.BAIDU_MINIAPP?e.swan:t===Mi.ALIPAY_MINIAPP?e.my:t===Mi.DINGTALK_MINIAPP?e.dd:t===Mi.JD_MINIAPP?e.jd:t===Mi.KUAISHOU_MINIAPP?e.ks:t===Mi.UNIAPP?e.uni:void 0,Xi=e=>{const t=e?.miniGlobal;return Zi(t)?t:e},eo=e=>{const t=Xi(e);return Qi(t)?t:void 0},to=e=>void 0!==e.window&&void 0!==e.document,ro=e=>!(void 0!==e.window||void 0!==e.document)&&"function"==typeof e.fetch&&("function"==typeof e.skipWaiting||void 0!==e.registration),so=e=>{const t=e.uni;if(void 0!==e.__uniConfig)return!0;if(Zi(t))return!0;try{if(!Ji(t,"getSystemInfoSync"))return!1;const e=t.getSystemInfoSync();return"object"==typeof e&&null!==e&&"string"==typeof e.uniPlatform}catch{return!1}},no=e=>Qi(e.wx)?Mi.WECHAT_MINIAPP:Qi(e.my)?Mi.ALIPAY_MINIAPP:Qi(e.dd)?Mi.DINGTALK_MINIAPP:Qi(e.swan)?Mi.BAIDU_MINIAPP:Qi(e.tt)?Mi.TOUTIAO_MINIAPP:Qi(e.qq)?Mi.QQ_MINIAPP:Qi(e.jd)?Mi.JD_MINIAPP:Qi(e.ks)?Mi.KUAISHOU_MINIAPP:void 0,io=e=>void 0!==no(e),oo=e=>{const t=no(e);if(t)return t;try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;if("string"==typeof r)return Wi[r]??Mi.UNIAPP}catch{return Mi.UNIAPP}return to(e)?Mi.WEB:Mi.UNIAPP},ao=(e,t)=>{const r=eo(Yi(e,t));if(r)return r;const s=eo(e.uni);return s||(e.uni??e)},co=(e,t)=>{const r=e??Vi();if(t){const e=t===Mi.UNIAPP||so(r),s=e?oo(r):t;return{platform:t,hostPlatform:s,framework:e?"uniapp":to(r)?"web":"native",global:e?ao(r,s):Xi(Yi(r,t))??r}}if(so(r)){const e=oo(r);return{platform:Mi.UNIAPP,hostPlatform:e,framework:"uniapp",global:ao(r,e)}}return Zi(r.swan)?{platform:Mi.BAIDU_MINIAPP,hostPlatform:Mi.BAIDU_MINIAPP,framework:"native",global:Xi(r.swan)??r.swan}:Zi(r.tt)?{platform:Mi.TOUTIAO_MINIAPP,hostPlatform:Mi.TOUTIAO_MINIAPP,framework:"native",global:Xi(r.tt)??r.tt}:Zi(r.dd)?{platform:Mi.DINGTALK_MINIAPP,hostPlatform:Mi.DINGTALK_MINIAPP,framework:"native",global:Xi(r.dd)??r.dd}:Zi(r.my)?{platform:Mi.ALIPAY_MINIAPP,hostPlatform:Mi.ALIPAY_MINIAPP,framework:"native",global:Xi(r.my)??r.my}:Zi(r.wx)?{platform:Mi.WECHAT_MINIAPP,hostPlatform:Mi.WECHAT_MINIAPP,framework:"native",global:Xi(r.wx)??r.wx}:Zi(r.qq)?{platform:Mi.QQ_MINIAPP,hostPlatform:Mi.QQ_MINIAPP,framework:"native",global:Xi(r.qq)??r.qq}:Zi(r.jd)?{platform:Mi.JD_MINIAPP,hostPlatform:Mi.JD_MINIAPP,framework:"native",global:Xi(r.jd)??r.jd}:Zi(r.ks)?{platform:Mi.KUAISHOU_MINIAPP,hostPlatform:Mi.KUAISHOU_MINIAPP,framework:"native",global:Xi(r.ks)??r.ks}:(e=>"ReactNative"===e.navigator?.product)(r)?{platform:Mi.REACT_NATIVE,hostPlatform:Mi.REACT_NATIVE,framework:"react-native",global:r}:(e=>"string"==typeof e.process?.versions?.electron)(r)?{platform:to(r)?Mi.ELECTRON_RENDERER:Mi.ELECTRON_MAIN,hostPlatform:to(r)?Mi.ELECTRON_RENDERER:Mi.ELECTRON_MAIN,framework:"electron",global:r}:ro(r)||to(r)?{platform:Mi.WEB,hostPlatform:Mi.WEB,framework:ro(r)?"worker":"web",global:r}:{platform:Mi.UNKNOWN,hostPlatform:Mi.UNKNOWN,framework:"native",global:r}},uo=e=>e===Mi.WECHAT_MINIAPP||e===Mi.QQ_MINIAPP||e===Mi.TOUTIAO_MINIAPP||e===Mi.BAIDU_MINIAPP||e===Mi.ALIPAY_MINIAPP||e===Mi.DINGTALK_MINIAPP||e===Mi.LARK_MINIAPP||e===Mi.KUAISHOU_MINIAPP||e===Mi.JD_MINIAPP||e===Mi.MINIAPP_360||e===Mi.HARMONY_MINIAPP||e===Mi.QUICKAPP||e===Mi.UNIAPP,lo=["request","upload","socket","proto"],ho=(e,t=lo)=>{const r=((e,t=lo)=>t.filter(t=>!e[t]))(e,t);if(0!==r.length)throw Fi("Platform missing required capabilities.",{code:Pi,stage:Ei,retryable:!1,details:{required:[...t],missing:r}})};var po=null;try{po=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 mo(e,t,r){this.low=0|e,this.high=0|t,this.unsigned=!!r}function fo(e){return!0===(e&&e.__isLong__)}function go(e){var t=Math.clz32(e&-e);return e?31-t:t}mo.prototype.__isLong__,Object.defineProperty(mo.prototype,"__isLong__",{value:!0}),mo.isLong=fo;var yo={},vo={};function bo(e,t){var r,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=vo[e])?s:(r=wo(e,0,!0),n&&(vo[e]=r),r):(n=-128<=(e|=0)&&e<128)&&(s=yo[e])?s:(r=wo(e,e<0?-1:0,!1),n&&(yo[e]=r),r)}function Io(e,t){if(isNaN(e))return t?Uo:Eo;if(t){if(e<0)return Uo;if(e>=Ro)return Lo}else{if(e<=-Ao)return Po;if(e+1>=Ao)return xo}return e<0?Io(-e,t).neg():wo(e%_o|0,e/_o|0,t)}function wo(e,t,r){return new mo(e,t,r)}mo.fromInt=bo,mo.fromNumber=Io,mo.fromBits=wo;var Co=Math.pow;function So(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?Uo:Eo;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 So(e.substring(1),t,r).neg();for(var n=Io(Co(r,8)),i=Eo,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=Io(Co(r,a));i=i.mul(d).add(Io(c))}else i=(i=i.mul(n)).add(Io(c))}return i.unsigned=t,i}function To(e,t){return"number"==typeof e?Io(e,t):"string"==typeof e?So(e,t):wo(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}mo.fromString=So,mo.fromValue=To;var _o=4294967296,Ro=_o*_o,Ao=Ro/2,Mo=bo(1<<24),Eo=bo(0);mo.ZERO=Eo;var Uo=bo(0,!0);mo.UZERO=Uo;var No=bo(1);mo.ONE=No;var ko=bo(1,!0);mo.UONE=ko;var Oo=bo(-1);mo.NEG_ONE=Oo;var xo=wo(-1,2147483647,!1);mo.MAX_VALUE=xo;var Lo=wo(-1,-1,!0);mo.MAX_UNSIGNED_VALUE=Lo;var Po=wo(0,-2147483648,!1);mo.MIN_VALUE=Po;var Do=mo.prototype;Do.toInt=function(){return this.unsigned?this.low>>>0:this.low},Do.toNumber=function(){return this.unsigned?(this.high>>>0)*_o+(this.low>>>0):this.high*_o+(this.low>>>0)},Do.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(Po)){var t=Io(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=Io(Co(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}},Do.getHighBits=function(){return this.high},Do.getHighBitsUnsigned=function(){return this.high>>>0},Do.getLowBits=function(){return this.low},Do.getLowBitsUnsigned=function(){return this.low>>>0},Do.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Po)?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},Do.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&(-1===e&&!(0===this.low&&-2097152===this.high))},Do.isZero=function(){return 0===this.high&&0===this.low},Do.eqz=Do.isZero,Do.isNegative=function(){return!this.unsigned&&this.high<0},Do.isPositive=function(){return this.unsigned||this.high>=0},Do.isOdd=function(){return!(1&~this.low)},Do.isEven=function(){return!(1&this.low)},Do.equals=function(e){return fo(e)||(e=To(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},Do.eq=Do.equals,Do.notEquals=function(e){return!this.eq(e)},Do.neq=Do.notEquals,Do.ne=Do.notEquals,Do.lessThan=function(e){return this.comp(e)<0},Do.lt=Do.lessThan,Do.lessThanOrEqual=function(e){return this.comp(e)<=0},Do.lte=Do.lessThanOrEqual,Do.le=Do.lessThanOrEqual,Do.greaterThan=function(e){return this.comp(e)>0},Do.gt=Do.greaterThan,Do.greaterThanOrEqual=function(e){return this.comp(e)>=0},Do.gte=Do.greaterThanOrEqual,Do.ge=Do.greaterThanOrEqual,Do.compare=function(e){if(fo(e)||(e=To(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},Do.comp=Do.compare,Do.negate=function(){return!this.unsigned&&this.eq(Po)?Po:this.not().add(No)},Do.neg=Do.negate,Do.add=function(e){fo(e)||(e=To(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,wo((u&=65535)<<16|(l&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},Do.subtract=function(e){return fo(e)||(e=To(e)),this.add(e.neg())},Do.sub=Do.subtract,Do.multiply=function(e){if(this.isZero())return this;if(fo(e)||(e=To(e)),po)return wo(po.mul(this.low,this.high,e.low,e.high),po.get_high(),this.unsigned);if(e.isZero())return this.unsigned?Uo:Eo;if(this.eq(Po))return e.isOdd()?Po:Eo;if(e.eq(Po))return this.isOdd()?Po:Eo;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(Mo)&&e.lt(Mo))return Io(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,wo((l&=65535)<<16|(h&=65535),(d&=65535)<<16|(u&=65535),this.unsigned)},Do.mul=Do.multiply,Do.divide=function(e){if(fo(e)||(e=To(e)),e.isZero())throw Error("division by zero");var t,r,s;if(po)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?wo((this.unsigned?po.div_u:po.div_s)(this.low,this.high,e.low,e.high),po.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Uo:Eo;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Uo;if(e.gt(this.shru(1)))return ko;s=Uo}else{if(this.eq(Po))return e.eq(No)||e.eq(Oo)?Po:e.eq(Po)?No:(t=this.shr(1).div(e).shl(1)).eq(Eo)?e.isNegative()?No:Oo:(r=this.sub(e.mul(t)),s=t.add(r.div(e)));if(e.eq(Po))return this.unsigned?Uo:Eo;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=Eo}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:Co(2,n-48),o=Io(t),a=o.mul(e);a.isNegative()||a.gt(r);)a=(o=Io(t-=i,this.unsigned)).mul(e);o.isZero()&&(o=No),s=s.add(o),r=r.sub(a)}return s},Do.div=Do.divide,Do.modulo=function(e){return fo(e)||(e=To(e)),po?wo((this.unsigned?po.rem_u:po.rem_s)(this.low,this.high,e.low,e.high),po.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},Do.mod=Do.modulo,Do.rem=Do.modulo,Do.not=function(){return wo(~this.low,~this.high,this.unsigned)},Do.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},Do.clz=Do.countLeadingZeros,Do.countTrailingZeros=function(){return this.low?go(this.low):go(this.high)+32},Do.ctz=Do.countTrailingZeros,Do.and=function(e){return fo(e)||(e=To(e)),wo(this.low&e.low,this.high&e.high,this.unsigned)},Do.or=function(e){return fo(e)||(e=To(e)),wo(this.low|e.low,this.high|e.high,this.unsigned)},Do.xor=function(e){return fo(e)||(e=To(e)),wo(this.low^e.low,this.high^e.high,this.unsigned)},Do.shiftLeft=function(e){return fo(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?wo(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):wo(0,this.low<<e-32,this.unsigned)},Do.shl=Do.shiftLeft,Do.shiftRight=function(e){return fo(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?wo(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):wo(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Do.shr=Do.shiftRight,Do.shiftRightUnsigned=function(e){return fo(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?wo(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):wo(32===e?this.high:this.high>>>e-32,0,this.unsigned)},Do.shru=Do.shiftRightUnsigned,Do.shr_u=Do.shiftRightUnsigned,Do.rotateLeft=function(e){var t;return fo(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?wo(this.high,this.low,this.unsigned):e<32?(t=32-e,wo(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),wo(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},Do.rotl=Do.rotateLeft,Do.rotateRight=function(e){var t;return fo(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?wo(this.high,this.low,this.unsigned):e<32?(t=32-e,wo(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),wo(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},Do.rotr=Do.rotateRight,Do.toSigned=function(){return this.unsigned?wo(this.low,this.high,!1):this},Do.toUnsigned=function(){return this.unsigned?this:wo(this.low,this.high,!0)},Do.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Do.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]},Do.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]},mo.fromBytes=function(e,t,r){return r?mo.fromBytesLE(e,t):mo.fromBytesBE(e,t)},mo.fromBytesLE=function(e,t){return new mo(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},mo.fromBytesBE=function(e,t){return new mo(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&&(mo.fromBigInt=function(e,t){return wo(Number(BigInt.asIntN(32,e)),Number(BigInt.asIntN(32,e>>BigInt(32))),t)},mo.fromValue=function(e,t){return"bigint"==typeof e?mo.fromBigInt(e,t):To(e,t)},Do.toBigInt=function(){var e=BigInt(this.low>>>0);return BigInt(this.unsigned?this.high>>>0:this.high)<<BigInt(32)|e});var qo="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Bo(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 $o,Fo,Go={exports:{}},jo={},zo={};function Ko(){if(Fo)return $o;return Fo=1,$o=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))}})},$o}var Ho,Vo,Wo,Jo,Zo,Qo={};var Yo,Xo,ea,ta,ra,sa={};var na,ia,oa,aa,ca,da,ua,la,ha,pa,ma={exports:{}};ma.exports;function fa(){return na||(na=1,e=ma,t=ma.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?b:v;if(t){if(e<0)return b;if(e>=f)return T}else{if(e<=-g)return _;if(e+1>=g)return S}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?b: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 b=a(0,!0);r.UZERO=b;var I=a(1);r.ONE=I;var w=a(1,!0);r.UONE=w;var C=a(-1);r.NEG_ONE=C;var S=d(-1,2147483647,!1);r.MAX_VALUE=S;var T=d(-1,-1,!0);r.MAX_UNSIGNED_VALUE=T;var _=d(0,-2147483648,!1);r.MIN_VALUE=_;var R=r.prototype;R.toInt=function(){return this.unsigned?this.low>>>0:this.low},R.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},R.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(_)){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}},R.getHighBits=function(){return this.high},R.getHighBitsUnsigned=function(){return this.high>>>0},R.getLowBits=function(){return this.low},R.getLowBitsUnsigned=function(){return this.low>>>0},R.getNumBitsAbs=function(){if(this.isNegative())return this.eq(_)?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},R.isSafeInteger=function(){var e=this.high>>21;return!e||!this.unsigned&&-1===e&&!(0===this.low&&-2097152===this.high)},R.isZero=function(){return 0===this.high&&0===this.low},R.eqz=R.isZero,R.isNegative=function(){return!this.unsigned&&this.high<0},R.isPositive=function(){return this.unsigned||this.high>=0},R.isOdd=function(){return!(1&~this.low)},R.isEven=function(){return!(1&this.low)},R.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},R.eq=R.equals,R.notEquals=function(e){return!this.eq(e)},R.neq=R.notEquals,R.ne=R.notEquals,R.lessThan=function(e){return this.comp(e)<0},R.lt=R.lessThan,R.lessThanOrEqual=function(e){return this.comp(e)<=0},R.lte=R.lessThanOrEqual,R.le=R.lessThanOrEqual,R.greaterThan=function(e){return this.comp(e)>0},R.gt=R.greaterThan,R.greaterThanOrEqual=function(e){return this.comp(e)>=0},R.gte=R.greaterThanOrEqual,R.ge=R.greaterThanOrEqual,R.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},R.comp=R.compare,R.negate=function(){return!this.unsigned&&this.eq(_)?_:this.not().add(I)},R.neg=R.negate,R.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)},R.subtract=function(e){return s(e)||(e=h(e)),this.add(e.neg())},R.sub=R.subtract,R.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?b:v;if(this.eq(_))return e.isOdd()?_:v;if(e.eq(_))return this.isOdd()?_: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,I=0;return g+=(I+=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|(I&=65535),(m&=65535)<<16|(f&=65535),this.unsigned)},R.mul=R.multiply,R.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?b:v;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return b;if(e.gt(this.shru(1)))return w;i=b}else{if(this.eq(_))return e.eq(I)||e.eq(C)?_:e.eq(_)?I:(r=this.shr(1).div(e).shl(1)).eq(v)?e.isNegative()?I:C:(n=this.sub(e.mul(r)),i=r.add(n.div(e)));if(e.eq(_))return this.unsigned?b: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=I),i=i.add(l),n=n.sub(p)}return i},R.div=R.divide,R.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))},R.mod=R.modulo,R.rem=R.modulo,R.not=function(){return d(~this.low,~this.high,this.unsigned)},R.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},R.clz=R.countLeadingZeros,R.countTrailingZeros=function(){return this.low?n(this.low):n(this.high)+32},R.ctz=R.countTrailingZeros,R.and=function(e){return s(e)||(e=h(e)),d(this.low&e.low,this.high&e.high,this.unsigned)},R.or=function(e){return s(e)||(e=h(e)),d(this.low|e.low,this.high|e.high,this.unsigned)},R.xor=function(e){return s(e)||(e=h(e)),d(this.low^e.low,this.high^e.high,this.unsigned)},R.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)},R.shl=R.shiftLeft,R.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)},R.shr=R.shiftRight,R.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)},R.shru=R.shiftRightUnsigned,R.shr_u=R.shiftRightUnsigned,R.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))},R.rotl=R.rotateLeft,R.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))},R.rotr=R.rotateRight,R.toSigned=function(){return this.unsigned?d(this.low,this.high,!1):this},R.toUnsigned=function(){return this.unsigned?this:d(this.low,this.high,!0)},R.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},R.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]},R.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)},R.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),ma.exports;var e,t,r}function ga(){return ia||(ia=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=Ko(),s.base64=(Ho||(Ho=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)}}(Qo)),Qo),s.EventEmitter=function(){if(Wo)return Vo;function e(){this._listeners=Object.create(null)}return Wo=1,Vo=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},Vo}(),s.float=function(){if(Zo)return Jo;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 Zo=1,Jo=e(e)}(),s.utf8=(Yo||(Yo=1,r=65533,(t=sa).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}),sa),s.pool=ea?Xo:(ea=1,Xo=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(ra)return ta;ra=1,ta=t;var e=ga();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},ta}(),s.isUnsafeProperty=n,s.isNode=Boolean(void 0!==qo&&qo&&qo.process&&qo.process.versions&&qo.process.versions.node),s.global=s.isNode&&qo||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||zo,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=fa();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}}(zo)),zo}function ya(){if(aa)return oa;aa=1,oa=c;var e,t=ga(),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()},oa}function va(){if(la)return ua;la=1,ua=i;var e,t=ga(),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)}})},ua}var ba,Ia,wa,Ca,Sa,Ta,_a={};function Ra(){return wa||(wa=1,_a.Service=function(){if(Ia)return ba;Ia=1,ba=t;var e=ga();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},ba}()),_a}function Aa(){return Sa?Ca:(Sa=1,Ca=Object.create(null))}function Ma(){return Ta||(Ta=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=ya(),t.BufferWriter=function(){if(da)return ca;da=1,ca=r;var e=ya();(r.prototype=Object.create(e.prototype)).constructor=r;var t=ga();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(),ca}(),t.Reader=va(),t.BufferReader=function(){if(pa)return ha;pa=1,ha=r;var e=va();(r.prototype=Object.create(e.prototype)).constructor=r;var t=ga();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(),ha}(),t.util=ga(),t.rpc=Ra(),t.roots=Aa(),t.configure=r,r()}(jo)),jo}var Ea,Ua,Na={},ka={exports:{}};function Oa(){if(Ua)return Ea;Ua=1,Ea=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,Ea}const xa=Bo(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var La,Pa,Da,qa;function Ba(){if(qa)return Da;qa=1,Da=r;var e=Ko(),t=function(){if(Pa)return La;Pa=1;var e=null;try{(e=xa)&&e.readFile&&e.readFileSync||(e=null)}catch(t){}return La=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()},Da}var $a,Fa={};var Ga,ja,za,Ka,Ha,Va,Wa,Ja,Za,Qa,Ya,Xa,ec,tc,rc,sc,nc,ic={};function oc(){if(Ha)return Ka;Ha=1,Ka=c;var e=zc();((c.prototype=Object.create(e.prototype)).constructor=c).className="Namespace";var t,r,s,n=Gc(),i=$c(),o=jc();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},Ka}function ac(){if(Wa)return Va;Wa=1,Va=s;var e=Gc();((s.prototype=Object.create(e.prototype)).constructor=s).className="MapField";var t=Fc(),r=$c();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))}},Va}function cc(){if(Za)return Ja;Za=1,Ja=r;var e=zc();((r.prototype=Object.create(e.prototype)).constructor=r).className="Method";var t=$c();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))},Ja}function dc(){if(Ya)return Qa;Ya=1,Qa=n;var e=oc();((n.prototype=Object.create(e.prototype)).constructor=n).className="Service";var t=cc(),r=$c(),s=Ra();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},Qa}function uc(){if(ec)return Xa;ec=1,Xa=t;var e=ga();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)},Xa}function lc(){if(rc)return tc;rc=1,tc=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=Kc(),t=Fc(),r=$c();function s(e){return"missing required '"+e.name+"'"}return tc}function hc(){if(nc)return sc;nc=1,sc=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=Kc(),t=$c();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 sc}var pc,mc={};function fc(){return pc||(pc=1,function(e){var t=e,r=Kc(),s=$c();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")}}(mc)),mc}var gc,yc,vc,bc,Ic,wc,Cc,Sc,Tc,_c,Rc,Ac,Mc,Ec,Uc,Nc,kc,Oc,xc,Lc,Pc={};function Dc(){return gc||(gc=1,e=Pc,t=uc(),r=ga(),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)}}),Pc;var e,t,r}function qc(){if(vc)return yc;vc=1,yc=f;var e=oc();((f.prototype=Object.create(e.prototype)).constructor=f).className="Type";var t=Kc(),r=jc(),s=Gc(),n=ac(),i=dc(),o=uc(),a=va(),c=ya(),d=$c(),u=Hc(),l=lc(),h=hc(),p=fc(),m=Dc();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)}},yc}function Bc(){if(Ic)return bc;Ic=1,bc=c;var e=oc();((c.prototype=Object.create(e.prototype)).constructor=c).className="Root";var t,r,s,n=Gc(),i=Kc(),o=jc(),a=$c();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},bc}function $c(){if(wc)return ka.exports;wc=1;var e,t,r,s,n,i,o=ka.exports=ga(),a=Aa();o.codegen=Oa(),o.fetch=Ba(),o.path=($a||($a=1,s=(r=Fa).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)}),Fa),o.patterns=(Ga||(Ga=1,(i=ic).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)$/),ic);var c=o.patterns.reservedRe;o.fs=function(){if(za)return ja;za=1;var e=null;try{(e=xa)&&e.readFile&&e.readFileSync||(e=null)}catch(t){}return ja=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=qc());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=Kc());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(Bc()))}}),ka.exports}function Fc(){return Cc||(Cc=1,function(e){var t=e,r=$c(),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])}(Na)),Na}function Gc(){if(Tc)return Sc;Tc=1,Sc=o;var e=zc();((o.prototype=Object.create(e.prototype)).constructor=o).className="Field";var t,r=Kc(),s=Fc(),n=$c(),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},Sc}function jc(){if(Rc)return _c;Rc=1,_c=s;var e=zc();((s.prototype=Object.create(e.prototype)).constructor=s).className="OneOf";var t=Gc(),r=$c();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)})}},_c}function zc(){if(Mc)return Ac;Mc=1,Ac=o,o.className="ReflectionObject";const e=jc();var t,r=$c(),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},Ac}function Kc(){if(Uc)return Ec;Uc=1,Ec=s;var e=zc();((s.prototype=Object.create(e.prototype)).constructor=s).className="Enum";var t=oc(),r=$c();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)},Ec}function Hc(){if(kc)return Nc;kc=1,Nc=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=Kc(),t=Fc(),r=$c();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 Nc}var Vc=Lc?xc:(Lc=1,xc=function(){if(Oc)return Go.exports;Oc=1;var e=Go.exports=Ma();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=Hc(),e.decoder=lc(),e.verifier=hc(),e.converter=fc(),e.ReflectionObject=zc(),e.Namespace=oc(),e.Root=Bc(),e.Enum=Kc(),e.Type=qc(),e.Field=Gc(),e.OneOf=jc(),e.MapField=ac(),e.Service=dc(),e.Method=cc(),e.Message=uc(),e.wrappers=Dc(),e.types=Fc(),e.util=$c(),e.ReflectionObject._configure(e.Root),e.Namespace._configure(e.Type,e.Service,e.Enum),e.Root._configure(e.Type),e.Field._configure(e.Type),Go.exports}());const Wc={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}}}}}}}}}},Jc=e=>{if(!e||0===e.trim().length)throw Fi("Proto type name is required.",{code:$i,stage:Oi,retryable:!1,details:{typeName:e}})};class Zc{constructor(){this.codecMap=new Map}register(e,t){Jc(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 Fi("Proto payload must be an object.",{code:$i,stage:Oi,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 Jc(e),this.codecMap.get(e)}getOrThrow(e){const t=this.get(e);if(t)return t;throw Fi("Proto codec not found.",{code:$i,stage:Oi,retryable:!1,details:{typeName:e}})}}const Qc=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Yc=e=>{class t extends Vc.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},Xc=e=>mo.isLong(e),ed=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"number"==typeof e.byteLength,td=e=>Object.prototype.hasOwnProperty.call(Vc.types.packed,e),rd=e=>{const t=e.resolve();return t.resolvedType instanceof Vc.Enum||td(t.type)},sd=(e,t)=>t in e?e[t]:void 0,nd=e=>{const t=e.resolve();return t.resolvedType instanceof Vc.Enum?0:(r=t.type,Object.prototype.hasOwnProperty.call(Vc.types.basic,r)?Vc.types.basic[t.type]:2);var r},id=(e,t)=>Xc(e)||"number"==typeof e||"string"==typeof e?e:Qc(e)&&"number"==typeof e.low&&"number"==typeof e.high?new mo(e.low,e.high,t):t?mo.UZERO:mo.ZERO,od=(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(id(r,!1));case"uint64":return e.uint64(id(r,!0));case"sint64":return e.sint64(id(r,!1));case"fixed64":return e.fixed64(id(r,!0));case"sfixed64":return e.sfixed64(id(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:ed(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}`)}},ad=(e,t,r)=>{if(t<0||e.pos+t>r)throw RangeError(`index out of range: ${e.pos} + ${t} > ${r}`)},cd=(e,t)=>{const r=e.uint32();return ad(e,r,t),r},ud=(e,t,r)=>{const s=e.len;e.len=r;try{switch(t){case 0:return void e.skip();case 1:return ad(e,8,r),void e.skip(8);case 2:{const t=cd(e,r);return void e.skip(t)}case 5:return ad(e,4,r),void e.skip(4);default:throw new Error(`Unsupported protobuf wire type: ${String(t)}`)}}finally{e.len=s}},ld=(e,t,r)=>{const s=t.resolve(),n=s.resolvedType;if(n instanceof Vc.Type){const t=e.fork();return pd(n,Qc(r)?r:{},t),t.ldelim(),e}return n instanceof Vc.Enum?(e.int32("number"==typeof r?r:Number(r)),e):od(e,s.type,r)},hd=(e,t,r)=>{if(0===r.length)return e;const s=t.resolve();if(td(s.type)&&t.packed){e.uint32(t.id<<3|2).fork();for(const s of r)ld(e,t,s);return e.ldelim(),e}const n=nd(t);for(const i of r)e.uint32(t.id<<3|n),ld(e,t,i);return e},pd=(e,t,r=Vc.Writer.create())=>{const s=e.fieldsArray.slice().sort(Vc.util.compareFieldsById);for(const n of s){const e=sd(t,n.name);null!=e&&(n.repeated?hd(r,n,Array.isArray(e)?e:[]):(r.uint32(n.id<<3|nd(n)),ld(r,n,e)))}return r},md=(e,t,r,s)=>{const n=t.resolve(),i=n.resolvedType;return i instanceof Vc.Type?2!==r?void ud(e,r,s):fd(i,e,cd(e,s)):i instanceof Vc.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)},fd=(e,t,r)=>{const s=t instanceof Vc.Reader?t:Vc.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){ud(s,d,n);continue}if(c.repeated){const e=Array.isArray(i[c.name])?i[c.name]:[];if(rd(c)&&2===d){const t=cd(s,n)+s.pos;for(;s.pos<t;)e.push(md(s,c,0,t))}else{const t=md(s,c,d,n);void 0!==t&&e.push(t)}i[c.name]=e;continue}const e=md(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},gd=(e,t)=>t?.longs===String?e.toString():t?.longs===Number?e.toNumber():e,yd=(e,t)=>{const r=e.resolve();if(r.resolvedType instanceof Vc.Type)return null;if(r.resolvedType instanceof Vc.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&&Xc(r.typeDefault)?gd(r.typeDefault,t):r.typeDefault},vd=(e,t,r)=>{const s=e.resolve();if(void 0!==t)return s.resolvedType instanceof Vc.Type?Qc(t)?bd(s.resolvedType,t,r):t:s.resolvedType instanceof Vc.Enum?r?.enums===String&&"number"==typeof t?s.resolvedType.valuesById[t]??t:t:s.long&&Xc(t)?gd(t,r):"bytes"===s.type&&ed(t)?((e,t)=>t?.bytes===String?Vc.util.base64.encode(e,0,e.length):t?.bytes===Array?Array.prototype.slice.call(e):e)(t,r):t},bd=(e,t,r)=>{const s={};for(const n of e.fieldsArray.slice().sort(Vc.util.compareFieldsById)){const e=sd(t,n.name);n.repeated?Array.isArray(e)?s[n.name]=e.map(e=>vd(n,e,r)):(r?.arrays||r?.defaults)&&(s[n.name]=[]):null==e?r?.defaults&&(s[n.name]=yd(n,r)):s[n.name]=vd(n,e,r)}return s},Id=e=>{const t=e;t.__reflectionCodecInstalled||(t.__reflectionCodecInstalled=!0,e.encode=(t,r)=>pd(e,Qc(t)?t:{},r),e.decode=(t,r)=>fd(e,t,r),e.fromObject=e=>Qc(e)?e:{},e.toObject=(t,r)=>bd(e,Qc(t)?t:{},r),e.create=e=>e?{...e}:{},e.verify=()=>null)},wd=e=>{Id(e);for(const t of e.nestedArray)if(t instanceof Vc.Type)wd(t);else if(t instanceof Vc.Namespace)for(const e of t.nestedArray)e instanceof Vc.Type&&wd(e)},Cd=e=>{for(const t of e.nestedArray)t instanceof Vc.Type?wd(t):t instanceof Vc.Namespace&&Cd(t)},Sd=()=>{const e=Vc.Type;e.__reflectionRuntimeInstalled||(e.generateConstructor=e=>()=>Yc(e),Vc.Type.prototype.setup=function(){return Id(this),this},Vc.Type.prototype.create=function(e){return e?{...e}:{}},Vc.Type.prototype.encode=function(e,t){return pd(this,Qc(e)?e:{},t)},Vc.Type.prototype.decode=function(e,t){return fd(this,e,t)},Vc.Type.prototype.fromObject=function(e){return Qc(e)?e:{}},Vc.Type.prototype.toObject=function(e,t){return bd(this,Qc(e)?e:{},t)},Vc.Type.prototype.verify=function(){return null},e.__reflectionRuntimeInstalled=!0)};let Td=!1,_d=null,Rd=null,Ad=null;const Md=e=>e.startsWith(".")?e.slice(1):e,Ed=e=>e instanceof Vc.Namespace,Ud=e=>e instanceof Vc.Type,Nd=e=>{for(const t of e.nestedArray)Ud(t)?wd(t):Ed(t)&&Nd(t)},kd=()=>{Td||(Vc.util.Long=mo,Vc.configure(),Td=!0),Sd();const e=Vc.Root.fromJSON(Wc);return Nd(e),e},Od=(e,t)=>{const r=e.nestedArray;for(const s of r){if(Ud(s)){const e=Md(s.fullName);wd(s),t.registerType(e,s);continue}Ed(s)&&Od(s,t)}},xd=(e,t,r)=>{const s=t instanceof Error?t.message:String(t);return Fi(`Static proto ${r} failed.`,{code:$i,stage:Oi,retryable:!1,details:{typeName:e,operation:r,cause:s}})},Ld=()=>_d||(_d=kd(),_d),Pd=()=>{if(Ad)return Ad;const e=(()=>{if(Rd)return Rd;const e=new Zc,t=Ld();return Od(t,e),Rd=e,e})();return Ad={encode(t,r){try{return e.getOrThrow(Md(t)).encode(r)}catch(s){throw xd(t,s,"encode")}},decode(t,r){try{return e.getOrThrow(Md(t)).decode(r)}catch(s){throw xd(t,s,"decode")}}},Ad},Dd=e=>{const 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},qd=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,a=setTimeout(()=>{i.abort()},o),c=((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:c,signal:r.signal??i.signal});let o;if("arraybuffer"===r.responseType)o=await e.arrayBuffer();else if("text"===r.responseType)o=await e.text();else{const t=e.headers.get("content-type")??"",r=await e.text();o=t.includes("application/json")&&r?JSON.parse(r):r}return{status:e.status,headers:Dd(e.headers),data:o}}catch(d){throw Fi("Request adapter execution failed.",{code:Di,stage:Ui,retryable:!0,details:{url:r.url,method:s,cause:d instanceof Error?d.message:String(d)}})}finally{clearTimeout(a)}}}},Bd=e=>"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,$d=e=>"function"==typeof e.on&&"function"==typeof e.off,Fd=(e,t,r)=>{if(Bd(e))return e.addEventListener(t,r),()=>{e.removeEventListener(t,r)};if($d(e)){const s=e;return s.on(t,r),()=>{s.off(t,r)}}throw Fi("Socket event listener API is unsupported.",{code:Bi,stage:ki,retryable:!1,details:{event:t}})},Gd=(e,t,r)=>{if(Bd(e)){const s=(...n)=>{e.removeEventListener(t,s),r(...n)};return e.addEventListener(t,s),()=>{e.removeEventListener(t,s)}}if($d(e)){const s=e;if("function"==typeof s.once)return s.once?.(t,r),()=>{s.off(t,r)};let n=()=>{};return n=Fd(e,t,(...e)=>{n(),r(...e)}),n}throw Fi("Socket one-time listener API is unsupported.",{code:Bi,stage:ki,retryable:!1,details:{event:t}})},zd=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?zd(e.data):null;var t},Kd=e=>{const t=new Set,r=new Set,s=new Set,n=new Set;return Fd(e,"open",()=>{t.forEach(e=>{e()})}),Fd(e,"message",(...e)=>{const t=zd(e[0]);null!==t&&r.forEach(e=>{e(t)})}),Fd(e,"error",(...e)=>{const t=e[0];s.forEach(e=>{e(t)})}),Fd(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!==ji)throw Fi("Socket is not open.",{code:Bi,stage:ki,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)})}},Hd=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(Fi("Socket creation failed.",{code:Bi,stage:ki,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(Fi("Socket connection timed out.",{code:Bi,stage:ki,retryable:!0,details:{url:e.url,reason:"timeout"}})))};o=Gd(n,"open",()=>{c||(c=!0,o(),a(),d(),r(Kd(n)))}),a=Gd(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(Fi("Socket connection failed before open.",{code:Bi,stage:ki,retryable:!0,details:{eventType:t}}))}),"number"==typeof e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(u,e.timeoutMs))})}},Vd=(e,t)=>{throw Fi("Upload adapter execution failed.",{code:qi,stage:Ni,retryable:"abort"!==e,details:{reason:e,url:t.url}})},Wd=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 Fi("Web upload adapter only supports web-file source.",{code:qi,stage:Ni,retryable:!1,details:{sourceType:t.source.sourceType}});const r=t.source.file;if(!r)throw Fi("Upload source file is required for web-file uploads.",{code:qi,stage:Ni,retryable:!1,details:{sourceType:t.source.sourceType}});const s="undefined"!=typeof Blob&&r instanceof Blob,n=t.source.name??"upload.bin";s?e.append("file",r,n):e.append("file",r)})(t,e),t},Jd=(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{Vd("abort",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("timeout",()=>{try{Vd("timeout",r)}catch(e){n(e instanceof Error?e:new Error(String(e)))}}),i.addEventListener("error",()=>{try{Vd("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=Wd(r);i.timeout=o,i.open("POST",r.url),((e,t)=>{Object.entries(t??{}).forEach(([t,r])=>{e.setRequestHeader(t,r)})})(i,r.headers),i.send(e)}catch(a){n(Fi("Upload adapter execution failed.",{code:qi,stage:Ni,retryable:!1,details:{url:r.url,reason:"invalid-config",cause:a instanceof Error?a.message:String(a)}}))}}),Zd=(e,t)=>e?"timeout":"abort",Qd=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 Jd(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=Wd(r),s=await e(r.url,{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 Fi("Upload adapter execution failed.",{code:qi,stage:Ni,retryable:!e,details:{reason:e?Zd(n):"network",url:r.url,cause:c instanceof Error?c.message:String(c)}})}finally{o&&clearTimeout(o)}})(r,e,s);throw Fi("Upload adapter execution failed.",{code:qi,stage:Ni,retryable:!1,details:{reason:"missing-upload-runtime",url:s.url}})}}},Yd=(e,t)=>{const r=new e;return Object.entries(t.fields??{}).forEach(([e,t])=>{r.append(e,t)}),r.append("file",(e=>{const t=e.source;if("rn-uri"!==t.sourceType||!t.uri)throw Fi("React Native upload adapter only supports rn-uri source.",{code:qi,stage:Ni,retryable:!1,details:{sourceType:t.sourceType}});return{uri:t.uri,name:t.name??"upload.bin",type:t.mimeType??"application/octet-stream"}})(t)),r},Xd=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=Yd(r,s),n=await t(s.url,{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===qi&&t.stage===Ni})(c))throw c;const e=c instanceof Error&&"AbortError"===c.name;throw Fi("React Native upload adapter execution failed.",{code:qi,stage:Ni,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)}}}},eu=(e,t)=>e+t&4294967295,tu=(e,t,r,s,n,i)=>{return eu((o=eu(eu(t,e),eu(s,i)))<<(a=n)|o>>>32-a,r);var o,a},ru=(e,t,r,s,n,i,o)=>tu(t&r|~t&s,e,t,n,i,o),su=(e,t,r,s,n,i,o)=>tu(t&s|r&~s,e,t,n,i,o),nu=(e,t,r,s,n,i,o)=>tu(t^r^s,e,t,n,i,o),iu=(e,t,r,s,n,i,o)=>tu(r^(t|~s),e,t,n,i,o),ou=(e,t)=>{let[r,s,n,i]=e;r=ru(r,s,n,i,t[0]??0,7,-680876936),i=ru(i,r,s,n,t[1]??0,12,-389564586),n=ru(n,i,r,s,t[2]??0,17,606105819),s=ru(s,n,i,r,t[3]??0,22,-1044525330),r=ru(r,s,n,i,t[4]??0,7,-176418897),i=ru(i,r,s,n,t[5]??0,12,1200080426),n=ru(n,i,r,s,t[6]??0,17,-1473231341),s=ru(s,n,i,r,t[7]??0,22,-45705983),r=ru(r,s,n,i,t[8]??0,7,1770035416),i=ru(i,r,s,n,t[9]??0,12,-1958414417),n=ru(n,i,r,s,t[10]??0,17,-42063),s=ru(s,n,i,r,t[11]??0,22,-1990404162),r=ru(r,s,n,i,t[12]??0,7,1804603682),i=ru(i,r,s,n,t[13]??0,12,-40341101),n=ru(n,i,r,s,t[14]??0,17,-1502002290),s=ru(s,n,i,r,t[15]??0,22,1236535329),r=su(r,s,n,i,t[1]??0,5,-165796510),i=su(i,r,s,n,t[6]??0,9,-1069501632),n=su(n,i,r,s,t[11]??0,14,643717713),s=su(s,n,i,r,t[0]??0,20,-373897302),r=su(r,s,n,i,t[5]??0,5,-701558691),i=su(i,r,s,n,t[10]??0,9,38016083),n=su(n,i,r,s,t[15]??0,14,-660478335),s=su(s,n,i,r,t[4]??0,20,-405537848),r=su(r,s,n,i,t[9]??0,5,568446438),i=su(i,r,s,n,t[14]??0,9,-1019803690),n=su(n,i,r,s,t[3]??0,14,-187363961),s=su(s,n,i,r,t[8]??0,20,1163531501),r=su(r,s,n,i,t[13]??0,5,-1444681467),i=su(i,r,s,n,t[2]??0,9,-51403784),n=su(n,i,r,s,t[7]??0,14,1735328473),s=su(s,n,i,r,t[12]??0,20,-1926607734),r=nu(r,s,n,i,t[5]??0,4,-378558),i=nu(i,r,s,n,t[8]??0,11,-2022574463),n=nu(n,i,r,s,t[11]??0,16,1839030562),s=nu(s,n,i,r,t[14]??0,23,-35309556),r=nu(r,s,n,i,t[1]??0,4,-1530992060),i=nu(i,r,s,n,t[4]??0,11,1272893353),n=nu(n,i,r,s,t[7]??0,16,-155497632),s=nu(s,n,i,r,t[10]??0,23,-1094730640),r=nu(r,s,n,i,t[13]??0,4,681279174),i=nu(i,r,s,n,t[0]??0,11,-358537222),n=nu(n,i,r,s,t[3]??0,16,-722521979),s=nu(s,n,i,r,t[6]??0,23,76029189),r=nu(r,s,n,i,t[9]??0,4,-640364487),i=nu(i,r,s,n,t[12]??0,11,-421815835),n=nu(n,i,r,s,t[15]??0,16,530742520),s=nu(s,n,i,r,t[2]??0,23,-995338651),r=iu(r,s,n,i,t[0]??0,6,-198630844),i=iu(i,r,s,n,t[7]??0,10,1126891415),n=iu(n,i,r,s,t[14]??0,15,-1416354905),s=iu(s,n,i,r,t[5]??0,21,-57434055),r=iu(r,s,n,i,t[12]??0,6,1700485571),i=iu(i,r,s,n,t[3]??0,10,-1894986606),n=iu(n,i,r,s,t[10]??0,15,-1051523),s=iu(s,n,i,r,t[1]??0,21,-2054922799),r=iu(r,s,n,i,t[8]??0,6,1873313359),i=iu(i,r,s,n,t[15]??0,10,-30611744),n=iu(n,i,r,s,t[6]??0,15,-1560198380),s=iu(s,n,i,r,t[13]??0,21,1309151649),r=iu(r,s,n,i,t[4]??0,6,-145523070),i=iu(i,r,s,n,t[11]??0,10,-1120210379),n=iu(n,i,r,s,t[2]??0,15,718787259),s=iu(s,n,i,r,t[9]??0,21,-343485551),e[0]=eu(r,e[0]),e[1]=eu(s,e[1]),e[2]=eu(n,e[2]),e[3]=eu(i,e[3])},au=(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},cu=e=>{let t="";for(let r=0;r<4;r+=1){t+=(e>>8*r&255).toString(16).padStart(2,"0")}return t},du=e=>{const t=[1732584193,-271733879,-1732584194,271733878];let r=0;for(;r+64<=e.length;r+=64)ou(t,au(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&&(ou(t,s),s.fill(0));const o=8*e.length;return s[14]=4294967295&o,s[15]=Math.floor(o/4294967296),ou(t,s),t.map(cu).join("")},uu=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 Fi("Image decode capability is missing for current platform",{code:Pi,stage:xi,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(Fi("Image decode failed",{code:qi,stage:xi,retryable:!1,details:{reason:"image load error"}}))},s.src=t})},lu=e=>{if(!(e=>"web-file"===e.sourceType&&"undefined"!=typeof Blob&&e.file instanceof Blob)(e))throw Fi("Web image processor only supports web file source",{code:Pi,stage:xi,retryable:!1,details:{sourceType:e.sourceType}});return e.file},hu=()=>({async getImageInfo(e){const t=lu(e),r=await uu(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=lu(e),s=await uu(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 Fi("Canvas capability is missing for current platform",{code:Pi,stage:xi,retryable:!1,details:{reason:"canvas unavailable"}})})(r.width,r.height),o=i.getContext("2d");if(!o)throw Fi("Canvas 2d context is missing",{code:Pi,stage:xi,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(Fi("Image encode failed",{code:qi,stage:xi,retryable:!1,details:{reason:"canvas toBlob returned null"}}))},t,r)});throw Fi("Canvas encode capability is missing for current platform",{code:Pi,stage:xi,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=lu(e),r=await(async e=>{if("function"==typeof e.arrayBuffer)return e.arrayBuffer();if("undefined"==typeof FileReader)throw Fi("Binary read capability is missing for current platform",{code:Pi,stage:xi,retryable:!1,details:{reason:"blob.arrayBuffer unavailable"}});return new Promise((t,r)=>{const s=new FileReader;s.onerror=()=>{r(Fi("Binary read failed",{code:qi,stage:xi,retryable:!1}))},s.onload=()=>{s.result instanceof ArrayBuffer?t(s.result):r(Fi("Binary read returned invalid result",{code:qi,stage:xi,retryable:!1}))},s.readAsArrayBuffer(e)})})(t);return du(new Uint8Array(r))}}),pu=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)},mu=e=>{if(!(e=>"miniapp-path"===e.sourceType&&"string"==typeof e.path&&e.path.length>0)(e))throw Fi("Miniapp image processor only supports miniapp path source",{code:Pi,stage:xi,retryable:!1,details:{sourceType:e.sourceType}});return e.path},fu=e=>{const t=e.getFileSystemManager?.();if(t)return t;throw Fi("Miniapp file system capability is missing",{code:Pi,stage:xi,retryable:!1,details:{capability:"getFileSystemManager"}})},gu=e=>{if(!e)return;const t=e.toLowerCase();return t.startsWith("image/")?t:`image/${t}`},yu=async(e,t)=>new Promise((r,s)=>{e.getImageInfo({src:t,success:e=>{r(e)},fail:e=>{s(e instanceof Error?e:new Error(pu(e)))}})}).catch(e=>{throw Fi("Miniapp image info read failed",{code:qi,stage:xi,retryable:!1,details:{src:t,cause:pu(e)}})}),vu=(e,t)=>"string"==typeof t.path&&t.path.length>0?t.path:e,bu=async(e,t)=>{if(!(e=>/^https?:\/\/tmp\//i.test(e))(t))return t;const r=await yu(e,t);return vu(t,r)},Iu=e=>({async getImageInfo(t){const r=mu(t),s=await yu(e,r),n=gu(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=mu(t);if("function"!=typeof e.compressImage)throw Fi("Miniapp image compress capability is missing",{code:Pi,stage:xi,retryable:!1,details:{capability:"compressImage"}});const n=await yu(e,s),i=vu(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(pu(e)))}})}).catch(e=>{throw Fi("Miniapp image compress failed",{code:qi,stage:xi,retryable:!1,details:{src:i,cause:pu(e)}})}),c=await bu(e,a),d=await yu(e,c),u=gu(d.type)??t.mimeType,l=await(async(e,t,r)=>{const s=fu(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(pu(e)))}})}).catch(e=>{throw Fi("Miniapp file info read failed",{code:qi,stage:xi,retryable:!1,details:{filePath:t,cause:pu(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=mu(t),s=await bu(e,r),n=await(async(e,t)=>{const r=fu(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(pu(e)))}})}).catch(e=>{throw Fi("Miniapp file read failed",{code:qi,stage:xi,retryable:!1,details:{filePath:t,cause:pu(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 du(n)}}),wu=new Set(["quotaexceedederror","ns_error_dom_quota_reached"]),Cu=[/\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],Su=(e,t)=>{if("object"!=typeof e||null===e)return null;const r=e[t];return"string"==typeof r?r:null},Tu=e=>{if(!e)return!1;const t=Su(e,"name");if(t&&wu.has(t.toLowerCase()))return!0;return["string"==typeof e?e:null,Su(e,"message"),Su(e,"errMsg")].some(e=>null!==e&&Cu.some(t=>t.test(e)))},_u=e=>{if(e instanceof Error)return e;const t=Su(e,"message")??Su(e,"errMsg")??"Storage quota exceeded";return Object.assign(new Error(t),{name:"QuotaExceededError",cause:e})},Ru="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Au=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),Mu=e=>e===Mi.ALIPAY_MINIAPP||e===Mi.DINGTALK_MINIAPP,Eu=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=Ru.indexOf(t[o]??""),r=Ru.indexOf(t[o+1]??""),a=t[o+2]??"=",c=t[o+3]??"=",d="="===a?0:Ru.indexOf(a),u="="===c?0:Ru.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},Uu=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),Nu=e=>{const t=new Uint8Array(e.byteLength);return t.set(e),t},ku=(e,t=0)=>{if(t>3||"object"!=typeof e||null===e||Array.isArray(e))return e;if(Uu(e)||ArrayBuffer.isView(e))return e;const r=e;return"data"in r&&r.data!==e?ku(r.data,t+1):e},Ou=(e,t=0)=>{if(t>3||null==e)return;if(e instanceof Uint8Array)return Nu(e);if(Uu(e))try{return Nu(new Uint8Array(e))}catch{return}if(ArrayBuffer.isView(e))return Nu(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=Ou(r.data,t+1);if(e)return e}if("buffer"in r&&r.buffer!==e){const e=Ou(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)}},xu=(e,t)=>{if("string"==typeof e)return e;const r=e instanceof Uint8Array?e:new Uint8Array(e);if(Mu(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+=Ru[o>>18&63],t+=Ru[o>>12&63],t+=void 0===n?"=":Ru[o>>6&63],t+=void 0===i?"=":Ru[63&o]}return t})(r);return Si("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:Au(r.subarray(0,8))}),s}const s=new ArrayBuffer(r.byteLength);return new Uint8Array(s).set(r),s},Lu=(e,t)=>"string"!=typeof e&&Mu(t),Pu=(e,t)=>{const r=ku(e.data);if("string"==typeof r){if(!Mu(t))return r;const s=Eu(r),n=new Uint8Array(s);return Si("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:Au(n.subarray(0,8)),decodedSuffixHex:Au(n.subarray(Math.max(0,n.length-8)))}),s}const s=Ou(r);if(!s){const s="object"==typeof e.data&&null!==e.data?e.data:void 0;return void Si("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(!Mu(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 Si("Mini program socket binary frame preserved",{operation:"platform.socket.frame.preserve-binary",hostPlatform:t,sourceType:Object.prototype.toString.call(r),sourceBytes:s.byteLength,sourcePrefixHex:Au(s.subarray(0,8))}),s.buffer;const i=Eu(n),o=new Uint8Array(i);return Si("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:Au(o.subarray(0,8)),decodedSuffixHex:Au(o.subarray(Math.max(0,o.length-8)))}),i},Du=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),qu=(e,t)=>("object"==typeof e||"function"==typeof e)&&null!==e&&"function"==typeof e[t],Bu=e=>e instanceof Error?e.message:Du(e)&&"string"==typeof e.errMsg?e.errMsg:Du(e)&&"string"==typeof e.errorMessage?e.errorMessage:String(e),$u=e=>e?{...e}:{},Fu=e=>"number"==typeof e&&Number.isInteger(e)&&e>=100&&e<=599,Gu=e=>Fu(e.statusCode)?e.statusCode:Fu(e.status)?e.status:void 0,ju=e=>{if(!Du(e))return{};const t={};return Object.entries(e).forEach(([e,r])=>{"string"==typeof r&&(t[e]=r)}),t},zu=e=>({...ju(e.headers),...ju(e.header)}),Ku=(e,t)=>{if(!e)return()=>{};if(e.aborted)return t(),()=>{};const r=()=>{t()};return e.addEventListener("abort",r,{once:!0}),()=>{e.removeEventListener("abort",r)}},Hu=e=>{try{e.close()}catch{}},Vu=(e,t)=>new Promise((r,s)=>{let n=!1,i=()=>{};const o=(e,r,o)=>{n||(n=!0,i(),s(Fi(e,{code:Di,stage:Ui,retryable:o,details:{url:t.url,method:"GET",cause:Bu(r)}})))},a=e.downloadFile?.({url:t.url,header:$u(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=Ou(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(),Si("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=Ku(t.signal,()=>{a?.abort(),o("Mini program file download aborted.","abort",!1)})}),Wu=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:$u(t.headers),data:t.body,timeout:t.timeoutMs??15e3,responseType:"arraybuffer"===t.responseType?"arraybuffer":"text",success:e=>{n();const i=Gu(e);void 0!==i?r({status:i,headers:zu(e),data:e.data}):s(Fi("Mini program request response status is invalid.",{code:Di,stage:Ui,retryable:!1,details:{url:t.url,method:t.method??"GET",statusCode:e.statusCode,status:e.status}}))},fail:e=>{n(),s(Fi("Mini program request failed.",{code:Di,stage:Ui,retryable:!0,details:{url:t.url,method:t.method??"GET",cause:Bu(e)}}))}});n=Ku(t.signal,()=>{i.abort(),s(Fi("Mini program request aborted.",{code:Di,stage:Ui,retryable:!1,details:{url:t.url,method:t.method??"GET",reason:"abort"}}))})}):Vu(e,t)}),Ju=(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&&Hu(i),n(Fi(t,{code:Bi,stage:ki,retryable:s,details:{url:r.url,cause:Bu(e)}})))},u=e=>{if(!(qu(r=e,"send")&&qu(r,"close")&&qu(r,"onOpen")&&qu(r,"onMessage")&&qu(r,"onError")&&qu(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 Hu(n);i=n;const o=()=>{n.offOpen?.(u),n.offError?.(l)},u=()=>{a?Hu(n):(a=!0,c(),o(),s(((e,t,r=Gi)=>{const s=new Set,n=new Set,i=new Set,o=new Set;let a=r;return e.onOpen(()=>{a=ji,s.forEach(e=>{e()})}),e.onMessage(e=>{const r=Pu(e,t);void 0!==r&&n.forEach(e=>{e(r)})}),e.onError(e=>{i.forEach(t=>{t(e)})}),e.onClose(e=>{a=Ki,o.forEach(t=>{t({code:e.code,reason:e.reason})})}),{get readyState(){return a},send(r){if(a!==ji)throw Fi("Mini program socket is not open.",{code:Bi,stage:ki,retryable:!0,details:{readyState:a}});return new Promise((s,n)=>{e.send({data:xu(r,t),...Lu(r,t)?{isBuffer:!0}:{},success:s,fail:e=>{n(Fi("Mini program socket send failed.",{code:Bi,stage:ki,retryable:!0,details:{cause:Bu(e)}}))}})})},close(t,r){a=zi,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,ji)))},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===Mi.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))})}),Zu=e=>({upload:t=>new Promise((r,s)=>{const n=(e=>{if("miniapp-path"!==e.sourceType||!e.path)throw Fi("Mini program upload only supports miniapp-path source.",{code:qi,stage:Ni,retryable:!1,details:{sourceType:e.sourceType}});return e})(t.source);let i=()=>{};const o=e.uploadFile({url:t.url,filePath:n.path,name:"file",header:$u(t.headers),formData:t.fields,timeout:t.timeoutMs??3e4,success:e=>{i();const o=Gu(e);void 0!==o?r({status:o,body:e.data}):s(Fi("Mini program upload response status is invalid.",{code:qi,stage:Ni,retryable:!1,details:{url:t.url,path:n.path,statusCode:e.statusCode,status:e.status}}))},fail:e=>{i(),s(Fi("Mini program upload failed.",{code:qi,stage:Ni,retryable:!0,details:{url:t.url,path:n.path,cause:Bu(e)}}))}});o.onProgressUpdate?.(e=>{t.onProgress?.({loaded:e.totalBytesSent,total:e.totalBytesExpectedToSend,percent:e.progress})}),i=Ku(t.signal,()=>{o.abort(),s(Fi("Mini program upload aborted.",{code:qi,stage:Ni,retryable:!1,details:{url:t.url,path:n.path,reason:"abort"}}))})})}),Qu=(e,t)=>{const r=(e=>e===Mi.ALIPAY_MINIAPP||e===Mi.DINGTALK_MINIAPP)(t);return{async getItem(t){if(qu(e,"getStorageSync"))try{const s=(e=>Du(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 qu(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(qu(e,"setStorageSync"))try{r?e.setStorageSync({key:t,data:s}):e.setStorageSync(t,s)}catch(n){if(Tu(n))throw _u(n)}else if(qu(e,"setStorage"))return new Promise((r,i)=>{try{e.setStorage({key:t,data:s,success:r,fail:e=>{Tu(e)?i(_u(e)):r()}})}catch(n){if(Tu(n))return void i(_u(n));r()}})},async removeItem(t){if(qu(e,"removeStorageSync"))try{e.removeStorageSync(r?{key:t}:t)}catch{}else if(qu(e,"removeStorage"))return new Promise(r=>{try{e.removeStorage({key:t,success:r,fail:()=>{r()}})}catch{r()}})}}},Yu=(e,t)=>({getPlatform:()=>t,getNetworkType:()=>qu(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 qu(e,"onNetworkStatusChange")&&e.onNetworkStatusChange(r),qu(e,"getNetworkType")&&e.getNetworkType({success:e=>{t("none"!==e.networkType)}}),()=>{qu(e,"offNetworkStatusChange")&&e.offNetworkStatusChange(r)}},onAppVisibilityChange(t){const r=()=>{t(!0)},s=()=>{t(!1)};return qu(e,"onAppShow")&&e.onAppShow(r),qu(e,"onAppHide")&&e.onAppHide(s),t(!0),()=>{qu(e,"offAppShow")&&e.offAppShow(r),qu(e,"offAppHide")&&e.offAppHide(s)}}}),Xu=(e,t=Mi.WECHAT_MINIAPP,r=t)=>{const s=(e=>{if(qu(e,"request")&&qu(e,"connectSocket")&&qu(e,"uploadFile"))return e;throw Fi("Mini program platform capability is missing.",{code:Pi,stage:Ei,retryable:!1,details:{capability:"request/connectSocket/uploadFile"}})})(e),n="function"==typeof s.getImageInfo?Iu(s):void 0;return{request:Wu(s),socket:Ju(s,r),upload:Zu(s),runtime:Yu(s,t),storage:Qu(s,r),imageProcessor:n}},el=[Mi.WEB,Mi.ELECTRON_RENDERER,Mi.REACT_NATIVE],tl=(e,t)=>{if("object"!=typeof e&&"function"!=typeof e||null===e)return!1;return"function"==typeof e[t]},rl=e=>el.includes(e),sl=(e,t)=>e!==Mi.UNIAPP?rl(e):!io(t)&&!il(t)&&to(t),nl=e=>tl(e,"getImageInfo")&&tl(e,"getFileSystemManager"),il=e=>!io(e)&&"app"===(e=>{try{const t=e.uni?.getSystemInfoSync?.(),r=t?.uniPlatform;return"string"==typeof r?r:void 0}catch{return}})(e),ol=(e,t)=>{if(rl(e)&&e!==Mi.REACT_NATIVE)return hu();if(uo(e)&&nl(t))return Iu(t);if(e===Mi.UNIAPP&&"object"==typeof t&&null!==t){const e=t;if(to(e))return hu();if(nl(e.uni))return Iu(e.uni);if(nl(e.wx))return Iu(e.wx)}},al=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())}},cl=(e,t,r,s)=>{if(e===Mi.UNIAPP&&il(r)&&void 0!==r.uni&&Zi(r.uni))return{...Xu(r.uni,e,t),proto:Pd()};if(((e,t)=>!sl(e,t)&&uo(e))(e,r)&&Zi(s))return{...Xu(s,e,t),proto:Pd()};const n=r.XMLHttpRequest,i=sl(e,r),o=i?qd({fetchImpl:r.fetch}):void 0,a=i?Hd({webSocketCtor:r.WebSocket}):void 0,c=e===Mi.REACT_NATIVE?Xd({fetchImpl:r.fetch,formDataCtor:r.FormData}):i?Qd({xhrFactory:"function"==typeof n?()=>new n:void 0,fetchImpl:r.fetch}):void 0,d=i&&e!==Mi.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:Pd(),storage:al(r),imageProcessor:i&&e!==Mi.REACT_NATIVE?hu():ol(e,s)}},dl=(e,t)=>{if(void 0!==e)return e;throw Fi("Platform adapter initialization failed.",{code:Li,stage:Ei,retryable:!1,details:{capability:t}})},ul=e=>{const t=Vi(e?.runtimeInput),r=co(t,e?.prefer),s=r.platform,n=cl(s,r.hostPlatform,t,r.global),i=((e,t)=>e?"function"==typeof e?e(t):e:{})(e?.overrides,n),o={...n,...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);ho(a);return{platform:s,platformId:s,capability:a,request:dl(o.request,"request"),upload:dl(o.upload,"upload"),socket:dl(o.socket,"socket"),runtime:dl(o.runtime,"runtime"),proto:dl(o.proto,"proto"),storage:dl(o.storage,"storage"),imageProcessor:o.imageProcessor}},ll=e=>{if(e instanceof rs)return e;if((e=>"object"==typeof e&&null!==e)(e)){const t=e.details;if(e.code===Pi){const r=t?.capability;if(e.stage===xi&&"string"==typeof r&&r.includes("FileSystem")){const r=e instanceof Error?e.message:"Upload failed";return new rs(r,{code:qr,details:t})}return new rs("Upload capability is missing for current platform",{code:Lr,details:t})}if(e.stage===Ni)return(e=>{const t=e?.reason;return!("string"!=typeof t||!t.toLowerCase().includes("abort"))})(t)?new rs("Upload canceled",{code:$r,details:t}):(e=>{const t=e?.reason;return!("string"!=typeof t||!t.toLowerCase().includes("timeout"))})(t)?new rs("Upload timeout",{code:Br,details:t}):new rs("Upload failed",{code:qr,details:t})}const t=e instanceof Error?e.message:"Upload failed";return new rs(t,{code:qr,details:{cause:e}})},hl={maxAttempts:10,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,randomSource:Math.random};class pl{constructor(e={}){this.attemptCount=0,this.config={...hl,...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 Ci(`Waiting ${e}ms before retry (attempt ${this.attemptCount})`),new Promise(t=>setTimeout(t,e))}}const ml={interval:3e4,timeout:6e4},fl="function"==typeof TextDecoder?new TextDecoder:null;class gl{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(!gl.isRecord(r))return;"pong"===gl.readString(r.type)&&(this.markAlive(),Ci("Pong received"))},this.config={...ml,...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),Ci("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),Ci("Heartbeat stopped")}sendPingInternal(){if(this.websocket&&this.websocket.readyState===ji)try{if(this.sendPing)this.sendPing();else{const e=JSON.stringify({type:"ping",timestamp:Date.now()});Promise.resolve(this.websocket.send(e)).catch(e=>{Ti("Failed to send ping:",e),this.resolveProbe(!1)})}this.resetTimeout(),Ci("Ping sent")}catch(e){Ti("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)?fl?.decode(t)??Ri(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(()=>{Si("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!==ji)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 Si("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 yl=null;function vl(){return yl||(yl=Ld()),yl}const bl="websdk2:device-info",Il="webim",wl="web",Cl=e=>{const t=Date.now(),r=e.deviceId,s=e.customOSPlatform,n=void 0!==s?e.customDeviceName:void 0,i=Vi().localStorage,o=()=>{if(!i)return null;try{const t=i.getItem(bl);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(bl,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===Il){const e=`${wl}_${t}`,s=c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e});return a(s),s}if(void 0!==s){const e=c({deviceId:`webim_${wl}_${r}`,deviceName:r,deviceUuid:`${wl}_${t}`});return a(e),e}const n={deviceId:`webim_${wl}_${r}`,deviceName:`webim_${wl}_${r}`,deviceUuid:`webim_${wl}_${r}`};return a(n),n}if(r===Il){const e=`random_${wl}_${t}`;return c({deviceId:`${r}_${e}`,deviceName:r,deviceUuid:e})}if(void 0!==s){return c({deviceId:`webim_${wl}_${r}`,deviceName:r,deviceUuid:`random_${wl}_${t}`})}return{deviceId:`webim_${wl}_${r}`,deviceName:`webim_${wl}_${r}`,deviceUuid:`webim_${wl}_${r}`}},Sl=e=>({appKey:e.appKey,name:e.name,domain:e.domain,clientResource:e.clientResource}),Tl=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 mo(t.low,t.high,Boolean(t.unsigned)).toString()}return e&&"function"==typeof e.toString?e.toString():""},_l=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:vn,stringValue:JSON.stringify(s)})}catch{t.push({key:r,type:yn,stringValue:Object.prototype.toString.call(s)})}else t.push({key:r,type:yn,stringValue:s});else Number.isInteger(s)?t.push({key:r,type:hn,varintValue:s}):t.push({key:r,type:gn,doubleValue:s});else t.push({key:r,type:ln,varintValue:s?1:0});return t},Rl=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:yn;if(s!==ln)if(s!==hn&&s!==pn&&s!==mn)if(s!==fn)if(s!==gn){if(s!==vn)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},Al=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,Ml="X-Request-Id",El=new Set(["mute"]),Ul={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext"},Nl=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},kl=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},Ol=(e,t)=>{const r=e?.map(e=>Nl(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},xl=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=kl(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},Ll=e=>{const t=kl(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=Ul[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},Pl=e=>{const t=kl(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:Nl(t.operator)??Nl(t.username)}},Dl=(e,t)=>({eventName:e,payload:t}),ql=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},r=Nl(e.from?.name),s=(n=e.to,Nl(n?.[0]?.name));var n;switch(e.operation){case 1:return Dl(Be,t);case 10:return Dl(Ge,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:s??r});case 17:return Dl($e,{...t,memberIds:Ol(e.members,r),ext:e.ext??e.eventExt});case 18:return Dl(Fe,{...t,memberIds:Ol(e.members,r)});case 20:return Dl(Ze,{...t,oldOwnerId:r,newOwnerId:s});case 21:return Dl(We,{...t,adminId:s??r});case 22:return Dl(Je,{...t,adminId:s??r});case 23:{const r=(e=>{const t=kl(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):Ol(e.members,s),i=46388736e5;return Dl(je,{...t,userIds:n,muteMembers:r??Object.fromEntries(n.map(e=>[e,i])),muteExpire:xl(e.reason,e.eventExt)??i})}case 24:return Dl(ze,{...t,userIds:Ol(e.members,s)});case 25:return Dl(Qe,{...t,announcement:e.reason??""});case 26:return Dl(Qe,{...t,announcement:""});case 29:return Dl(Ke,{...t,userIds:Ol(e.members,s)});case 30:return Dl(He,{...t,userIds:Ol(e.members,s)});case 31:return Dl(Ve,{...t,isMuted:!0});case 32:return Dl(Ve,{...t,isMuted:!1});case 14:return Dl(Ye,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:Ll(e.eventExt)});case 43:{const s=Pl(e.eventExt);return Dl(Xe,{...t,attributes:s.attributes,from:s.from??r})}case 44:{const s=Pl(e.eventExt);return Dl(et,{...t,keyList:s.keyList,from:s.from??r})}default:return null}},Bl=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),$l=(e,t)=>{if(!e)return t;try{return JSON.parse(e)}catch{return t}},Fl=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Gl=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),jl=e=>({userId:e}),zl=(e,t,r)=>{const s={userId:r};for(const n of Fl){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},Kl=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,Gl(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,jl(o));return s},Hl=e=>Bl(e)?e:null,Vl=e=>{if("string"==typeof e)return e},Wl=e=>{const t=Vl(e)?.trim();return t||void 0},Jl=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}},Zl=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},Ql=e=>{const t=Hl(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},Yl=e=>{const t=Hl(e);return t?Hl(t.data)?t.data:t:null},Xl=(e,t)=>{const r=Hl(e),s=r&&Hl(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return Jl(n[0])},eh=(e,t)=>{const r=(e=>{const t=Hl(e);return t?Jl(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},th=e=>Wl(e.groupId)??Wl(e.groupid)??Wl(e.id)??"",rh=e=>Vl(e.name)??Vl(e.groupname)??Vl(e.groupName)??"",sh=e=>{const t=Ql(e),r=Hl(t[0])??Yl(e)??{},s=(e=>{const t=Hl(e);if(!t)return null;const r=th(t);return r?{groupId:r,name:rh(t),description:Vl(t.description),memberCount:Jl(t.memberCount)??Jl(t.affiliations_count),public:Zl(t.public),joinApprovalRequired:Zl(t.joinApprovalRequired)??Zl(t.approval)??Zl(t.membersonly)??Zl(t.members_only),allowInvites:Zl(t.allowInvites)??Zl(t.allowinvites)??Zl(t.allow_user_invites),maxMembers:Jl(t.maxMembers)??Jl(t.maxusers),role:Wl(t.role)??Wl(t.permission),disabled:Zl(t.disabled)}:null})(r)??{groupId:th(r),name:rh(r)},n=Wl(r.owner)??Wl(r.admin)??Wl(r.member),i=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>Hl(e)).filter(e=>null!==e).map(e=>Jl(e.joined_time)).find(e=>void 0!==e);return{...s,owner:n?jl(n):void 0,inviteNeedConfirm:Zl(r.inviteNeedConfirm)??Zl(r.invite_need_confirm),muteAllMembers:Zl(r.mute),ext:Vl(r.ext)??Vl(r.custom),createdAt:Jl(r.createdAt)??Jl(r.created),joinedAt:i,avatarUrl:Vl(r.avatar),messageBlocked:Zl(r.messageBlocked)??Zl(r.isMessageBlocked)??Zl(r.shieldgroup)}},nh=e=>jl(e),ih=e=>Ql(e).map(e=>Wl(e)).filter(e=>Boolean(e)).map(e=>nh(e)),oh=e=>{const t=Hl(e);if(!t)return null;const r=Wl(t.fileId)??Wl(t.file_id);if(!r)return null;const s=Vl(t.fileName)??Vl(t.file_name)??r,n=Wl(t.fileOwner)??Wl(t.file_owner);return{fileId:r,fileName:s,fileOwner:n?nh(n):void 0,fileSize:Jl(t.fileSize)??Jl(t.file_size),createdAt:Jl(t.createdAt)??Jl(t.created)}},ah=new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),ch={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},dh=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},uh=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},lh=(e,t)=>{const r=e?.map(e=>dh(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},hh=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=uh(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},ph=e=>{const t=uh(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=ch[s];if(!e)continue;let t=n;if(ah.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},mh=(e,t)=>{const r=uh(t)??uh(e);return oh(r??void 0)??void 0},fh=(e,t)=>{const r=uh(t)??uh(e);return dh(r?.fileId)??dh(r?.file_id)??dh(e)??""},gh=(e,t)=>({eventName:e,payload:t}),yh=e=>{const t={groupId:e.groupId,groupName:e.groupName},r=dh(e.from?.name),s=(n=e.to,dh(n?.[0]?.name));var n;switch(e.operation){case 4:return gh(Y,{...t,applicantId:r,reason:e.reason});case 5:return gh(X,{...t,accepterId:r});case 6:return gh(ee,{...t,declinerId:r,applicantId:s,reason:e.reason});case 7:return gh(Q,{...t,inviterId:r,reason:e.reason});case 8:return gh(te,{...t,inviteeId:r,reason:e.reason});case 9:return gh(re,{...t,inviteeId:r,reason:e.reason});case 10:return gh(se,t);case 1:return gh(ne,t);case 19:return gh(ie,{...t,inviterId:r,reason:e.reason});case 23:{const r=(e=>{const t=uh(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=dh(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):lh(e.members,s);return gh(oe,{...t,userIds:n,muteExpire:n.map(e=>r?.[e]).find(e=>void 0!==e)??hh(e.reason,e.eventExt)})}case 24:return gh(ae,{...t,userIds:lh(e.members,s)});case 29:return gh(ce,{...t,userIds:lh(e.members,s)});case 30:return gh(de,{...t,userIds:lh(e.members,s)});case 31:return gh(ue,{...t,isMuted:!0});case 32:return gh(ue,{...t,isMuted:!1});case 21:return gh(le,{...t,administratorId:s??r});case 22:return gh(he,{...t,administratorId:s??r});case 20:return gh(pe,{...t,oldOwnerId:r,newOwnerId:s});case 17:{const s=lh(e.members,r);return gh(me,{...t,memberIds:s})}case 18:{const s=lh(e.members,r);return gh(fe,{...t,memberIds:s})}case 25:return gh(ge,{...t,announcement:e.reason??""});case 26:return gh(ge,{...t,announcement:""});case 27:return gh(ye,{...t,sharedFile:mh(e.reason,e.eventExt)});case 28:return gh(ve,{...t,fileId:fh(e.reason,e.eventExt)});case 14:return gh(be,{...t,shouldFetchGroupDetail:!0,groupPatch:ph(e.eventExt)});case 41:return gh(Ie,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return gh(Ie,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const s=(e=>{const t=uh(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:dh(t.username),attribute:s}})(e.eventExt);return gh(we,{...t,userId:s.userId,attribute:s.attribute,from:r,source:e.source??"direct"})}default:return null}},vh=new WeakMap,bh=(e,t)=>{vh.set(e,t)},Ih=e=>vh.get(e)??null,wh=(e,t)=>{const r=Ih(e);r&&bh(t,r)},Ch=new WeakMap,Sh=e=>Ch.get(e),Th=new WeakMap,_h=e=>Th.get(e),Rh=(e,t)=>{const r=Th.get(e);r&&Th.set(t,r)},Ah="singleChat",Mh="groupChat",Eh=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},Uh=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}},Nh=e=>{if(!Array.isArray(e))return;const t=e.map(e=>Eh(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},kh=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Oh=(...e)=>{for(const t of e){const e=Eh(t);if(e)return e}},xh=(e,t)=>Boolean(e&&t&&e===t),Lh=(e,t,r)=>Boolean(e&&e===r.userId&&t&&r.clientResource&&t!==r.clientResource),Ph=(e,t,r)=>{const s=Nh(e);if(s&&s.length>0)return s;const n=(t??[]).map(e=>Eh(e.name)).filter(e=>"string"==typeof e);if(n.length>0)return n;const i=Eh(r?.name);return i?[i]:[]},Dh=e=>{const t=Uh(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}}},qh=(e,t)=>{const r=Oh(e.to?.[0]?.clientResource);if(1!==e.to?.length||Eh(e.to[0]?.name)!==t.userId||!Lh(t.userId,r,t))return null;const s=(n=e.from,Eh(n?.name)??"");var n;if(!s)return Si("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 Si("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}},Bh=(e,t)=>{if(!e.groupId)return Si("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const r=Oh(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Lh(Eh(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 Si("Discarded unknown MultiDevice group operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===s)return null;const n=Ph(e.members,e.to,e.from);return{category:"group",operation:s,groupId:e.groupId,userIds:n.length>0?n:void 0,operatorId:Eh(e.from?.name),groupName:e.groupName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},$h=(e,t)=>{if(!e.threadId)return Si("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const r=Oh(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!Lh(Eh(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 Si("Discarded unknown MultiDevice thread operation",{operation:e}),"UNKNOWN"}})(e.operation);if("UNKNOWN"===s)return null;const n=Ph(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:Eh(e.from?.name),threadName:e.threadName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},Fh=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const r=Oh(e.res,e.raw?.resource,e.raw?.clientResource);if(xh(r,t.clientResource))return Ci("Discarded same-device MultiDevice conversation echo",{operation:e.operation,conversationId:e.id}),null;const s="chat"===(n=e.type)||"singleChat"===n?Ah:Mh;var n;const i=Eh(e.id)??(s===Ah?Eh(e.from):void 0);if(!i)return Si("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 Si("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?Dh(e.ext):void 0,operatorId:Eh(e.from),deviceId:r,timestamp:Uh(e.ts),raw:e.raw}},Gh=(e,t)=>{const r=Oh(e.resource,e.raw?.resource,e.raw?.clientResource);if(xh(r,t.clientResource))return Ci("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const s=Eh(e.to);if(!s)return Si("Discarded MultiDevice roaming delete event without conversationId",{}),null;const n=Eh(e.lastMsgId),i=Nh(e.msgIdList)??(n?[n]:void 0),o=Uh(e.deleteTime);if(!i&&void 0===o)return Si("Discarded MultiDevice roaming delete event without messageIds or beforeTimestamp",{conversationId:s}),null;const a=(e=>e&&"deleteRoaming"!==e&&"MESSAGE_REMOVED"!==e?(Si("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?Mh:Ah,messageIds:i,beforeTimestamp:o,deviceId:r,raw:e.raw}},jh=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}},zh=2147483647,Kh=e=>{const t=Number(e);if(!Number.isFinite(t)||t<=0)return;const r=Math.floor(t);return r<=0||r>zh?void 0:r},Hh=e=>{if("number"!=typeof e||!Number.isFinite(e)||e<=0)return;const t=e>zh?Math.floor(e/1e3):Math.floor(e);return Kh(t)};var Vh=4096,Wh=65547,Jh=15,Zh=2113929216,Qh=65536,Yh=65536,Xh=10485760,ep={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},tp={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function rp(e){if(!(e>0))return Yh;if(e<=Yh)return Yh;if(e>1073741823)return e;for(var t=Yh;t<e;)t*=2;return t}var sp={byU16:0,byU32:1},np=0,ip=1,op=2,ap=0,cp=1;function dp(e,t){return e[t]|e[t+1]<<8}function up(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function lp(e,t,r){e[t]=255&r,e[t+1]=r>>>8&255}var hp="fast";function pp(e){return 2654435761*(e>>>0)>>>20&4095}function mp(e){return 2654435761*(e>>>0)>>>19&8191}function fp(e,t,r){if("fast"===hp){var s=up(e,t);return r===sp.byU16?mp(s):pp(s)}throw new Error("Unsupported hash strategy: "+hp)}function gp(e,t,r,s,n){r[t]=e-n}function yp(e,t,r,s,n){gp(t,fp(e,t,s),r,0,n)}function vp(e,t,r,s){return t[e]+s}function bp(e,t,r,s,n){return vp(fp(e,t,s),r,0,n)}function Ip(e,t,r,s){for(var n=t;t<s-3;){if(up(e,t)!==up(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 wp(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,b=e.dictSize>0?v-s:0,I=s,w=s+n,C=w-12,S=w-5,T=0,_=i>0?i:r.length,R=0;if(n>Zh)return 0;switch(c){case np:default:u=s,l=s;break;case ip:u=s-e.currentOffset,l=s-e.dictSize;break;case op:u=s-e.currentOffset,l=s}if(a===sp.byU16&&n>=Wh)return 0;if(n<13)return Tp(t,r,I,w,T,_,o);yp(t,m,p,a,u),h=fp(t,++m,a);e:for(;;){var A,M,E=m,U=1,N=64;do{var k=h;if(m=E,E+=U,U=N++>>>6,E>C)return Tp(t,r,I,w,T,_,o);A=vp(k,p,0,u),c===op&&(A<s?(R=b,l=y):(R=0,l=s)),h=fp(t,E,a),gp(m,k,p,0,u)}while(d===cp&&A<f||a!==sp.byU16&&A+65535<m||!Cp(t,g,m,A,R,c,s));for(;m>I&&A+R>l;){var O=A+R-1;if(t[m-1]!==(c===op&&A<s?g[O-y+e.dictionaryStart]:t[O]))break;m--,A--}var x=m-I;if(M=T++,o&&T+x+8+Math.floor(x/255)>_)return 0;if(x>=Jh){var L=x-Jh;for(r[M]=240;L>=255;)r[T++]=255,L-=255;r[T++]=L}else r[M]=x<<4;if(x>=16&&r.set&&t.subarray)r.set(t.subarray(I,I+x),T),T+=x;else for(var P=0;P<x;P++)r[T++]=t[I+P];t:for(;;){var D;if(lp(r,T,m-A),T+=2,c===op&&A<s){var q=m+(v-(A+R));if(q>S&&(q=S),(m+=4+(D=Sp(t,g,m+4,A+R+4-y+e.dictionaryStart,q,v-y)))===q&&q<S){var B=Ip(t,m,s,S);D+=B,m+=B}}else m+=4+(D=Ip(t,m+4,A+4,S));if(o&&T+6+(D>>>8)>_)return 0;if(D>=15){for(r[M]+=15,D-=15;D>=510;)r[T++]=255,r[T++]=255,D-=510;D>=255&&(D-=255,r[T++]=255),r[T++]=D}else r[M]+=D;if(I=m,m>C)break e;if(yp(t,m-2,p,a,u),A=bp(t,m,p,a,u),c===op&&(A<s?(R=b,l=y):(R=0,l=s)),yp(t,m,p,a,u),!((d!==cp||A>=f)&&A+65535>=m&&Cp(t,g,m,A,R,c,s)))break t;r[M=T++]=0}h=fp(t,++m,a)}return Tp(t,r,I,w,T,_,o)}function Cp(e,t,r,s,n,i,o){var a,c=up(e,r);i===op&&s+n<o?a=up(t,s+n):a=up(e,s+n);return c===a}function Sp(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 Tp(e,t,r,s,n,i,o){var a=s-r;if(o&&n+a+1+Math.floor((a+255-Jh)/255)>i)return 0;if(a>=Jh){for(t[n++]=240,a-=Jh;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 _p(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 Rp(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,b=h<65536;if(0===i)return 1===s&&0===e[p]?0:-1;if(0===s)return-1;for(;;){var I,w,C,S;if(p>=m)return-(p-r)-1;if((w=(I=e[p++])>>>4)===Jh){var T=_p(e,A={ip:p},m-Jh,!0);if(p=A.ip,-1===T)return-(p-r)-1;if(f+(w+=T)<f)return-(p-r)-1;if(p+w<p)return-(p-r)-1}if(C=f+w,o&&(C>g-12||p+w>m-8)||!o&&C>g-8){if(!o&&C!==g)return-(p-r)-1;if(o&&(p+w!==m||C>g))return-(p-r)-1;if(w>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+w),f);else for(var _=0;_<w;_++)t[f+_]=e[p+_];p+=w,f+=w;break}if(w>=16&&t.set&&e.subarray)t.set(e.subarray(p,p+w),f);else for(_=0;_<w;_++)t[f+_]=e[p+_];if(f=C,(p+=w)+2>m)return-(p-r)-1;var R=dp(e,p);if(p+=2,S=C-R,b&&S+h<u)return-(p-r)-1;if(0===R)return-(p-r)-1;if(15===(w=15&I)){var A;T=_p(e,A={ip:p},m-5+1,!1);if(p=A.ip,-1===T)return-(p-r)-1;if(f+(w+=T)<f)return-(p-r)-1}if(w+=4,d===op&&S<u){if(f+w>g-5)return-(p-r)-1;if(w<=u-S){var M=v-(u-S);for(_=0;_<w;_++)t[f+_]=t[M+_];f+=w}else{var E=u-S;for(M=v-E,_=0;_<E;_++)t[f+_]=t[M+_];var U=w-E;if(U>(f+=E)-u)for(var N=u,k=f+U;f<k;)t[f++]=t[N++];else{for(_=0;_<U;_++)t[f+_]=t[u+_];f+=U}}}else{if(S<y)return-(p-r)-1;if(C=f+w,f-S<8)for(t[f]=t[S],t[f+1]=t[S+1],t[f+2]=t[S+2],t[f+3]=t[S+3],f+=4,S+=4;f<C;)t[f++]=t[S++];else for(;f<C;)t[f++]=t[S++]}}return o?f-n:p-r}function Ap(){return{hashTable:new Uint32Array(Vh),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function Mp(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function Ep(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?cp:ap;return e.dictionary&&c===s?(u=wp(e,t,r,s,n,o||0,a||!1,sp.byU32,ip,h),e.dictSize+=n,e.currentOffset+=n,u):(u=wp(e,t,r,s,n,o||0,a||!1,sp.byU32,op,h),e.dictionary=t,e.dictionaryStart=s,e.dictSize=n,e.currentOffset+=n,u)}function Up(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 Np(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function kp(e,t,r,s){return e.prefixSize=s,e.prefixEnd=r+s,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function Op(e,t,r,s,n,i,o){var a;if(e.prefixEnd===i){if((a=Rp(t,r,s,n,i,o,!0,0,0,op,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=Rp(t,r,s,n,i,o,!0,0,0,op,i,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=i+a}return a}function xp(e){var t=(e=e||{}).minWorkArea||Yh,r=e.maxWorkArea||Xh,s=e.shrinkThreshold||t;t<Yh&&(t=Yh),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Qh+t,this.maxBufferSize=Qh+r,this.shrinkThreshold=Qh+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:ep.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=Ap()}function Lp(e){var t=(e=e||{}).minWorkArea||Yh,r=e.maxWorkArea||Xh,s=e.shrinkThreshold||t;t<Yh&&(t=Yh),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Qh+t,this.maxBufferSize=Qh+r,this.shrinkThreshold=Qh+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:ep.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}xp.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Qh?this.offset:Qh,n=this.offset>Qh?this.offset-Qh:0;t.set(this.ringBuffer.subarray(n,n+s),0),Up(this.stream,t,0,s),r=s}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},xp.prototype.compress=function(e,t){var r=e.length;if(r<=0)return tp.PARAM_ERROR;if(r>this.maxBufferSize-Qh)return tp.PARAM_ERROR;if(r>this.ringBufferSize-Qh){var s=rp(r),n=Qh+s;if(n>this.maxBufferSize&&(n=this.maxBufferSize),!this._resizeBuffer(n))return tp.BUFFER_RESIZE_FAILED}this.offset+r>this.ringBufferSize&&(Up(this.stream,this.ringBuffer,0,Qh),this.offset=Qh);var i=this.offset;this.ringBuffer.set(e,i);var o=Ep(this.stream,this.ringBuffer,t,i,r,0,t.length,!0);return o<=0?tp.COMPRESS_FAILED:(this.offset+=r,this._tryAutoShrink(),o)},xp.prototype.reset=function(){this.offset=0,Mp(this.stream)},xp.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},xp.prototype._tryAutoShrink=function(){this.shrinkMode!==ep.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===ep.AUTO_IMMEDIATE||this.shrinkMode===ep.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},xp.prototype.getWorkArea=function(){return this.ringBufferSize-Qh},xp.prototype.getRingBufferSize=function(){return this.ringBufferSize},xp.prototype.getBaseBufferSize=function(){return this.minBufferSize},xp.prototype.getMaxBufferSize=function(){return this.maxBufferSize},xp.prototype.getCurrentOffset=function(){return this.offset},xp.prototype.getShrinkMode=function(){return this.shrinkMode},xp.prototype.setShrinkMode=function(e){this.shrinkMode=e},xp.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},xp.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Qh,r=this.maxBufferSize-Qh;if(e<t||e>r)return tp.PARAM_ERROR;this.shrinkThreshold=Qh+e},Lp.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Qh?this.offset:Qh,n=this.offset>Qh?this.offset-Qh:0;t.set(this.ringBuffer.subarray(n,n+s),0),r=s,kp(this.streamDecode,0,0,s)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},Lp.prototype.decompress=function(e,t,r){var s=e.length;if(s<=0||r<=0)return tp.PARAM_ERROR;if(r>this.maxBufferSize-Qh)return tp.PARAM_ERROR;if(r>this.ringBufferSize-Qh){var n=rp(r),i=Qh+n;if(i>this.maxBufferSize&&(i=this.maxBufferSize),!this._resizeBuffer(i))return tp.BUFFER_RESIZE_FAILED}if(this.offset+r>this.ringBufferSize){var o=this.offset-Qh;o>0&&this.ringBuffer.set(this.ringBuffer.subarray(o,o+Qh),0),kp(this.streamDecode,this.ringBuffer,0,Qh),this.offset=Qh}var a=Op(this.streamDecode,e,this.ringBuffer,0,s,this.offset,r);return a<=0?tp.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},Lp.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},Lp.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},Lp.prototype._tryAutoShrink=function(){this.shrinkMode!==ep.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===ep.AUTO_IMMEDIATE||this.shrinkMode===ep.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},Lp.prototype.getWorkArea=function(){return this.ringBufferSize-Qh},Lp.prototype.getRingBufferSize=function(){return this.ringBufferSize},Lp.prototype.getBaseBufferSize=function(){return this.minBufferSize},Lp.prototype.getMaxBufferSize=function(){return this.maxBufferSize},Lp.prototype.getCurrentOffset=function(){return this.offset},Lp.prototype.getShrinkMode=function(){return this.shrinkMode},Lp.prototype.setShrinkMode=function(e){this.shrinkMode=e},Lp.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},Lp.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Qh,r=this.maxBufferSize-Qh;if(e<t||e>r)return tp.PARAM_ERROR;this.shrinkThreshold=Qh+e};const Pp={LZ4_MAX_INPUT_SIZE:Zh,BLOCK_MAX_SIZE:65536,DICT_SIZE:Qh,DEFAULT_WORK_AREA:Yh,DEFAULT_MAX_WORK:Xh,SHRINK_MODE:ep,LZ4_ERROR:tp,alignToPowerOf2:rp,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".');hp=e},getHashStrategy:function(){return hp},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>Zh)return 0;if(0===s)return t.length>n?(t[n]=0,1):0;var i=s<Wh?sp.byU16:sp.byU32;return wp({hashTable:new Uint32Array(i===sp.byU16?8192:Vh),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,0,!1,i,np,ap)},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>Zh)return 0;if(i<1)return 0;if(0===s)return t[n]=0,1;var o=s<Wh?sp.byU16:sp.byU32;return wp({hashTable:new Uint32Array(o===sp.byU16?8192:Vh),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,i,!0,o,np,ap)},compressBound:function(e){return e<0||e>Zh?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:Rp(e,t,r,s,n,i,!0,0,0,np,n,null,0))},decompressFast:function(e,t,r,s,n){return Rp(e,t,r=r||0,0,s=s||0,n,!1,0,0,ip,s-65536,0,65536)},createStream:Ap,resetStream:Mp,loadDict:function(e,t,r,s){if(e.initCheck&&Mp(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;)yp(t,i,e.hashTable,sp.byU32,n),i+=3;return s},compressContinue:Ep,saveDict:Up,createStreamDecode:Np,setStreamDecode:kp,decompressSafeContinue:Op,RingBufferEncoder:xp,RingBufferDecoder:Lp,_hashU16:mp,_hashU32:pp,_TABLE_TYPE:sp},Dp=268435455,qp=new Uint32Array(256);let Bp=!1;function $p(e){!function(){if(!Bp){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;qp[e]=t>>>0}Bp=!0}}();let t=4294967295;for(let r=0;r<e.length;r+=1){const s=e[r]??0;t=t>>>8^(qp[255&(t^255&s)]??0)}return(4294967295^t)>>>0}var Fp=(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))(Fp||{});const Gp=268435455;class jp{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:Pp.DEFAULT_WORK_AREA,maxWorkArea:Pp.DEFAULT_MAX_WORK,shrinkMode:Pp.SHRINK_MODE.MANUAL};this.encoder=new Pp.RingBufferEncoder(e),this.decoder=new Pp.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>Gp)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const r=Pp.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>Dp)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=$p(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>Gp)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=$p(o);if(c!==n)throw new Error(`CRC32 checksum mismatch: expected ${n}, got ${c}`);return o}reset(){this.encoder.reset(),this.decoder.reset()}}const zp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Kp=(e,t)=>pd(e,t).finish();class Hp{constructor(e){this.compressor=null,this.compressionFailureCount=0,this.maxCompressionFailures=1,this.context=(e=>{const t=Cl({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:[$s],compressType:[Fs],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=vl(),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:[Fs],encryptType:[$s],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=Kp(t,s),i={version:0,guid:Sl({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),command:os,deviceId:0,encryptType:[$s],payload:n,traceId:Al()};return Kp(r,i)}encodeHeartbeat(){const e=vl(),t=e.lookupType("easemob.pb.CommUnreadUL"),r=e.lookupType("easemob.pb.MSync"),s=Kp(t,{}),n={version:0,encryptType:[$s],command:ns,payload:s,traceId:Al()};return Kp(r,n)}encodeStatisticRebuild(){const e=vl(),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=Kp(t,{operation:0}),o=r.decode(new Uint8Array);o.id=Date.now(),o.ns=Ns,o.payload=i;const a=s.decode(new Uint8Array);a.meta=o;const c=Kp(s,a);return Kp(n,{version:0,encryptType:[$s],command:ss,payload:c,traceId:Al()})}decodeProvision(e){const t=vl().lookupType("easemob.pb.Provision").decode(e),r=t.status??{},s="number"==typeof r.errorCode?r.errorCode:zs,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===js,statusCode:s,reason:n,resource:i,authToken:o,protocolCompressType:a,protocolCompressDirection:c}}decodeLogout(e){const t=vl().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=vl().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=vl().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=vl(),r=t.lookupType("easemob.pb.CommSyncDL"),s=t.lookupType("easemob.pb.MessageBody"),n=r.decode(e);Ci("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=Tl(n.metaId),c=Tl(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)!==Os)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)!==Os)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:cs;if(i!==hs&&i!==ms&&i!==fs&&i!==gs&&i!==ps)return null;const o=this.readJid(r.to),a=Number(Tl(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===fs)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===hs){Ci("Received READ_ACK MessageBody",s);const e=(Array.isArray(s.ackMessageIds)?s.ackMessageIds:[]).map(e=>Tl(e)).filter(e=>Boolean(e)),t=Tl(s.ackMessageId);if(0===e.length&&t&&e.push(t),0===e.length||!l)return null;const r=Rl(Array.isArray(s.ext)?s.ext.filter(zp):void 0),n=zp(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===ps){const e=Tl(s.ackMessageId);return e&&l?{type:"message_delivered",data:{messageId:e,from:d,to:u,conversationId:l,conversationType:"singleChat"}}:null}if(i===ms){const e=Tl(s.ackMessageId);return e&&l?{type:"message_recalled",data:{messageId:e,conversationId:l,conversationType:c,timestamp:a}}:null}const h=Tl(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:Rl(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!==Ps&&r!==Ls&&r!==xs&&r!==Ns)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===Ls?this.decodeRosterMeta(t,n):r===xs?this.decodeMucMeta(t,n):r===Ns?this.decodeStatisticGroupReceiptNotifies(t,n):this.decodeNotifyPayload(n):[]}decodeStatisticGroupReceiptNotifies(e,t){try{const r=vl(),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(!zp(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(!zp(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 Ci("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!==Ns)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=vl(),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=vl(),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=qh({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=vl(),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=$h({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=Bh({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?ql({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}):yh({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&&Ch.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);Ci("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:zp(s.data)?s.data:s}}]}if("conv"===n){const e=zp(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=Fh({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=zp(s.data)?s.data:s,t=Gh({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(!kh(s))continue;const e=Oh(s.operator_resource,s.resource,s.clientResource);if(xh(e,t.clientResource))continue;const n=Eh(s.group)??Eh(s.user);if(!n||!kh(s.data))continue;const i=Eh(s.group)?Mh:Ah,o=s.data;r.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:n,conversationType:i,remindType:Eh(o.type),silentMode:o,deviceId:e,raw:s})}return r})(zp(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(Tl(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:jh(e.category),data:e}}decodeNotice(e){const t=vl().lookupType("easemob.pb.CommNotice").decode(e);return{queue:t.queue&&"object"==typeof t.queue?t.queue:void 0}}decodeUnread(e){const t=vl().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=vl(),r=t.lookupType("easemob.pb.CommSyncUL"),s=t.lookupType("easemob.pb.MSync"),n=Kp(r,{queue:e}),i={version:0,encryptType:[$s],command:ss,payload:n,traceId:Al()};return Kp(s,i)}encodeLastSession(e,t){const r=vl(),s=r.lookupType("easemob.pb.CommSyncUL"),n=r.lookupType("easemob.pb.MSync"),i=Kp(s,{queue:e,key:t}),o={version:0,encryptType:[$s],command:ss,payload:i,traceId:Al()};return Kp(n,o)}encodeChatMessage(e,t){const r=vl(),s=r.lookupType("easemob.pb.MessageBody"),n=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),o=this.buildContent(e),a=this.resolveMessageProfileVersionFields(e),c=this.buildMessageMeta(e),d=this.resolveOutboundMessageTarget(e.conversationId,e.conversationType),u={type:this.resolveChatType(e),from:{name:this.context.userId},to:{name:d.name},contents:[o],ext:_l(e.ext??{}),...c?{meta:c}:{},...a,...e.needReadReceipt?{msgConfig:{allowGroupAck:!0}}:{}},l=Kp(s,u),h="singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",p=this.resolveDirectedUsers(e),m=this.resolveMetaExt(e),f={id:t,to:Sl({appKey:this.context.appKey,name:d.name,domain:h,clientResource:d.clientResource}),ns:Os,payload:l,routetype:this.resolveRouteType(e),directedUsers:p,ext:m,...void 0!==e.webhookEnv?{env:e.webhookEnv}:{}},g=Kp(n,{meta:f}),y={version:0,encryptType:[$s],command:ss,payload:g,traceId:Al()};return Kp(i,y)}encodeActionMessage(e,t){const r=vl(),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:_l(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=Kp(s,d);if("clearAllConversationUnreadMessageCount"===e.kind){const e=s.decode(u),r=s.fields.clearAllUnreadMessageCount;Ci("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:Sl({appKey:this.context.appKey,name:a.name,domain:"singleChat"===e.conversationType?this.context.domain:"conference.easemob.com",clientResource:a.clientResource}),ns:Os,payload:u,routetype:Ds,directedUsers:[],ext:[]},h=Kp(n,{meta:l}),p={version:0,encryptType:[$s],command:ss,payload:h,traceId:Al()};return Kp(i,p)}encodeChatRoomOperation(e,t){const r=vl(),s=r.lookupType("easemob.pb.MUCBody"),n=r.lookupType("easemob.pb.CommSyncUL"),i=r.lookupType("easemob.pb.MSync"),o={mucId:Sl({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=Kp(s,o),c={id:t,from:Sl({appKey:this.context.appKey,name:this.context.userId,domain:this.context.domain,clientResource:this.context.clientResource}),to:{domain:this.context.domain},ns:xs,payload:a},d=Kp(n,{meta:c}),u={version:0,encryptType:[$s],command:ss,payload:d,traceId:Al()};return Kp(i,u)}decodeServerMessageMeta(e){const t=vl(),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?_i(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(e=>{if(/^\d+$/.test(e))return e;const t=mo.fromString("1099511628211",!0);let r=mo.fromString("1469598103934665603",!0);for(let s=0;s<e.length;s+=1)r=r.xor(mo.fromInt(e.charCodeAt(s),!0)).multiply(t).toUnsigned();return r.isZero()?"1":r.toString()})(e)}decodeChatRoomJoinInfo(e){const t=vl().lookupType("easemob.pb.MUCBody");for(const s of e){if(!zp(s)||s.ns!==xs)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(!zp(e)||!zp(e.status))continue;const r=e.status.chatroomInfo;if("string"!=typeof r||""===r)continue;const s=JSON.parse(r);if(!zp(s))continue;const i=s[this.context.userId];if(!zp(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){Ti("Failed to decode chat room info from ACK",r)}}}decodeAck(e){const t=Tl(e.metaId);if(!t||"0"===t)return;const r=e.status??{},s="number"==typeof r.errorCode?r.errorCode:zs,n="string"==typeof r.reason?r.reason:void 0;return{protocolId:t,serverId:Tl(e.serverId),ok:s===js,statusCode:s,reason:n}}decodeMessage(e,t){const r="number"==typeof t.type?t.type:ds;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=Rl(t.ext),h=Rl(e.ext),p=Number(Tl(e.timestamp))||Date.now(),m=Tl(e.id),f=this.resolveBroadcast(h),g=this.resolvePriority(h),y=this.resolveMessageMetaPayload(t.meta,e.meta),v=this.resolveContentReplaced(y),b=this.resolveReactions(y),I=this.resolveModifiedInfo(y),w=this.resolveChatThreadMessageContext(y),C=this.resolveChatThreadOverview(y),S=this.resolveProfileVersionTime(t.userInfoUpdateTime),T=this.resolveProfileVersionTime(t.namecardUpdateTime),_={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)};bh(_,{userInfoUpdateTime:S,namecardUpdateTime:T});const R=this.decodeStreamMeta(t.stream,s);R&&(_.type="text",_.body={content:R.fullText},_.stream=R),void 0!==f&&(_.isBroadcast=f),void 0!==g&&(_.priority=g),void 0!==v&&(_.isContentReplaced=v),b&&(_.reactions=b),I&&(_.modifiedInfo=I),w&&(_.isChatThread=!0,_.chatThread=w);const A=this.resolvePeerRead(y,n,c);void 0!==A&&(_.isPeerRead=A);const M=this.resolveGroupReadCount(y,n);void 0!==M&&(_.groupReadCount=M),C&&(_.chatThreadOverview=C);const E=t.msgConfig;return E?.allowGroupAck&&(_.needReadReceipt=!0),_}resolveMessageProfileVersionFields(e){const t=Ih(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 Kh(Tl(e))}isPublicMessageType(e){return e===ds||e===us||e===ls}resolveMessageIsOnline(e,t){if(e===ls)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(Tl(r.streamSeq));if(!Number.isFinite(s))return;const n="number"==typeof r.streamStatus?r.streamStatus:Ms,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?rt.ERROR:e===Rs?rt.START:e===As?rt.START_COMPLETED:e===Es?rt.COMPLETED:e===Us?rt.FULL:rt.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:ys,text:t.content}}if("cmd"===e.type){const t=e.body;return{type:Ss,action:t.action}}if("custom"===e.type){const t=e.body;return{type:Ts,customEvent:t.event,customExts:_l(t.params??{})}}if("location"===e.type){const t=e.body;return{type:Is,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:vs,displayName:r.filename,remotePath:r.originalImageUrl??"",imageType:(t=s,t===Wn?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:bs,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:ws,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:ys,subType:0,text:_h(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:Cs,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:ys,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===_s||t===ys&&(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===ys)return{type:"text",body:{content:"string"==typeof e.text?e.text:""}};if(t===Ss)return{type:"cmd",body:{action:"string"==typeof e.action?e.action:""}};if(t===Ts){const t=Rl(e.customExts);return{type:"custom",body:{event:"string"==typeof e.customEvent?e.customEvent:"",params:t}}}if(t===Is)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===vs){const t=e.size??{},r="number"==typeof t.width?t.width:0,s="number"==typeof t.height?t.height:0,n=oi(e.imageType)===Wn,i="string"==typeof e.remotePath?e.remotePath:"",o=ni(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===bs){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===ws){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===Cs){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 us;case"chatRoom":return ls;default:return ds}}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 fs;case"sendMessageReadReceipts":return hs;case"deliveryAck":return ps;case"recall":return ms;case"update":return gs;default:return ds}}resolveConversationType(e){return e===us?"groupChat":e===ls?"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?_l({chatroom_msg_tag:this.mapPriorityToTag(e.priority)}):[]}resolveRouteType(e){return this.resolveDirectedUsers(e).length>0?Bs:this.resolveDeliverOnlineOnly(e)?qs:Ds}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(!zp(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(!zp(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(!zp(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(!zp(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=zp(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:zp(n?.ext)?n.ext:{},timestamp:s,body:l,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(zp(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=ni(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:zp(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(Ri(t));return zp(e)?e:null}catch{return null}}if(zp(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return zp(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(zp).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?[]:[Gs]}configureCompression(e,t){if(!e||!e.includes(Gs))return void this.disableCompression();this.compressor||(this.compressor=new jp);const r=this.resolveCompressionMode(t);this.compressor.mode=r,this.compressor.enableUplinkCompression=r===Fp.UPLINK_ONLY||r===Fp.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=r===Fp.DOWNLINK_ONLY||r===Fp.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?Fp.UPLINK_ONLY:1===e?Fp.DOWNLINK_ONLY:2===e?Fp.BIDIRECTIONAL:Fp.NONE}disableCompression(){this.compressor&&(this.compressor.mode=Fp.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}const Vp=1e3,Wp="direct";class Jp{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 Zp{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 Qp={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},Yp=()=>{const e=Vi(),t=e.crypto?.randomUUID;return("function"==typeof t?t.call(e.crypto):void 0)??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class Xp{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??Yp;const t=new Zp({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 Jp({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:Qp[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??Wp,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??Wp,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 em;const tm=e=>{em?.updateSession(e)},rm=e=>{em?.applyDnsSwitch(e)},sm=e=>{em?.updateNetworkType(e)},nm=e=>{if("disabled"!==em?.state)return em?.startOperation(e)},im=()=>{em?.reset(),em=void 0};class om{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.reconnectInProgress=!1,this.reconnectPaused=!1,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.tokenLifecycle=null,this.tokenWillExpireTimerId=null,this.tokenExpiredTimerId=null,this.config={heartBeatWait:3e4,autoReconnectNumMax:10,connectTimeout:1e4,...e},this.eventHub=r,this.msyncCodec=new Hp({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 pl({maxAttempts:this.config.autoReconnectNumMax,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2}),this.heartbeatManager=new gl({interval:this.config.heartBeatWait,timeout:6e4}),this.connectionEventNormalizer=new Ai,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 Wr("Token is expired",{code:lt,details:{stage:"token"}});return this.config.token=e,this.connection.token=e,this.msyncCodec.updateToken(e),this.setupTokenLifecycle(e,t,r),Si("Connection token renewed",{userId:this.config.userId,expireAt:t}),{token:e,expireAt:t}}handleOnline(){Si("Network online event received",this.getReconnectDiagnostic()),this.isOnline=!0;const e=this.offlineRecoverPending?S:C;this.offlineRecoverPending=!1,this.resumeReconnect(e)}handleOffline(){Si("Network offline event received",this.getReconnectDiagnostic()),this.isOnline=!1,this.offlineRecoverPending=!0,this.reconnectPaused=!0,this.clearReconnectTimer(),this.stopHeartbeat(),this.closeWebSocket(E,!0),Si("Network offline state applied",this.getReconnectDiagnostic())}async handleForeground(){if(!this.isLoggedIn)return;if(!this.isOnline)return;if(this.reconnectInProgress)return void Si("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(T,!0,!0),this.resumeReconnect(T)}}catch(t){if(Si("Foreground heartbeat check failed",t),this.reconnectInProgress||this.websocket!==e)return;this.closeWebSocket(T,!0,!0),this.resumeReconnect(T)}}resumeReconnect(e){this.isLoggedIn&&(this.reconnectInProgress?Si("Reconnect recovery skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()}):this.connection.status===s&&this.websocket||(this.reconnectPaused=!1,this.resetReconnectState(),Si("Reconnect recovery requested",{reason:e,...this.getReconnectDiagnostic()}),this.triggerReconnect(e)))}handleSendTimeout(e){this.isLoggedIn&&this.isOnline&&(this.reconnectPaused||e.reason===_&&Si("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,offlineRecoverPending:this.offlineRecoverPending,reconnectAttempts:this.reconnectAttempts,hasWebSocket:null!==this.websocket,hasReconnectTimer:null!==this.reconnectTimerId}}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 Wr))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(Ri(e))}catch{return!1}return!(!Array.isArray(t)||t.length<2)&&(3e3===t[0]&&"normal closed"===t[1])}clearReconnectTimer(){this.reconnectTimerId&&(clearTimeout(this.reconnectTimerId),this.reconnectTimerId=null)}async waitForReconnectDelay(){const e=this.connectionRetry.getRetryDelay();Si("Reconnect retry scheduled",{delayMs:Math.round(e),...this.getReconnectDiagnostic()}),this.clearReconnectTimer(),await new Promise(t=>{this.reconnectTimerId=setTimeout(()=>{this.reconnectTimerId=null,t()},e)})}buildConnectionEventPayload(e,t){const r=this.connection.error instanceof Wr?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),Ci("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 Si("Provision auth token has invalid payload");const r=Number(t.expires_in);if(!Number.isFinite(r))return void Si("Provision auth token has invalid expires_in");this.setupTokenLifecycle(this.connection.token??this.config.token,r)}catch(t){Si("Failed to parse provision auth token expiration",t)}}emitTokenWillExpire(){this.tokenLifecycle&&!this.tokenLifecycle.willExpireEmitted&&(this.tokenLifecycle.willExpireEmitted=!0,Si("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,Si("Token expired"),this.eventHub.dispatch(l,void 0))}isTokenExpiredConnectionError(e){return e instanceof Wr&&e.code===lt}handleTokenExpiredDisconnect(e){Si("Connection closing because token expired",{source:e}),this.connection.error=new Wr("Token expired",{code:lt,details:{stage:"token",source:e,retryable:!1}}),this.emitTokenExpired(),this.clearTokenTimers(),this.clearReconnectTimer(),this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.closeWebSocket(U,!0,!0),this.updateStatus(t,U,!0)}startHeartbeat(e){this.heartbeatManager.start(e,()=>{this.triggerReconnect(T)},()=>{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(){if(!this.reconnectInProgress)if(this.connection.status!==s&&this.connection.status!==r){this.isLoginPhase=!0,this.reconnectPaused=!1,this.resetReconnectState(),this.connectionEventNormalizer.reset();try{await this.connectWithRetry(I,!0),this.isLoggedIn=!0}catch(e){throw this.isLoggedIn=!1,e}finally{this.isLoginPhase=!1}}else Si("Connection already established or connecting")}async connectWithRetry(e,o){if(Si("Reconnect flow requested",{reason:e,throwOnFailure:o,...this.getReconnectDiagnostic()}),this.reconnectInProgress)return void Si("Reconnect flow skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()});if(this.connection.status===s&&this.websocket)return;if(this.reconnectPaused)return void Si("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;const d=this.resolveEffectiveMaxAttempts();this.connectionRetry.reset(),Si("Reconnect flow started",{reason:e,throwOnFailure:o,maxAttempts:d,...this.getReconnectDiagnostic()});try{for(;this.connectionRetry.getAttemptCount()<d;){this.connectionRetry.recordAttempt(),this.reconnectAttempts=this.connectionRetry.getAttemptCount(),this.connection.reconnectAttempts=this.reconnectAttempts;const t=this.isLoginPhase?r:n;Si("Reconnect attempt started",{attempt:this.reconnectAttempts,maxAttempts:d,reason:e,nextStatus:t,...this.getReconnectDiagnostic()}),this.updateStatus(t,e,!0,!0),this.prepareForConnectAttempt();try{return await this.connectOnce(),void this.handleConnectSuccess(e)}catch(u){if(a=u,Si("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()>=d)break;if(this.reconnectPaused||!this.isOnline&&!this.isLoginPhase){Si("Reconnect retry loop interrupted",{reason:e,attempt:this.reconnectAttempts,maxAttempts:d,...this.getReconnectDiagnostic()});break}await this.waitForReconnectDelay()}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 Wr("Connection failed",{code:gt,details:{stage:"ws"}});this.reconnectPaused=!0,Si("Reconnect attempts exhausted",{reason:e,attempt:this.reconnectAttempts,maxAttempts:d,lastError:a,...this.getReconnectDiagnostic()}),this.updateStatus(i,M,!0)}finally{this.reconnectInProgress=!1,Si("Reconnect flow finished",{reason:e,...this.getReconnectDiagnostic()})}}async connectOnce(){await this.createWebSocketConnection()}prepareForConnectAttempt(){this.clearReconnectTimer(),this.stopHeartbeat(),this.resetProvisionHandlers(),this.resetSyncState(),this.websocket&&this.closeWebSocket(w,!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),Si("Connection established successfully")}sendPostProvisionInitialSync(){this.sendMsyncPayload(this.msyncCodec.encodeHeartbeat()),this.sendMsyncPayload(this.msyncCodec.encodeStatisticRebuild())}async triggerReconnect(e){Si("Reconnect trigger received",{reason:e,...this.getReconnectDiagnostic()}),this.isLoggedIn?this.reconnectInProgress?Si("Reconnect trigger skipped",{guard:"reconnect-in-progress",reason:e,...this.getReconnectDiagnostic()}):this.reconnectPaused?Si("Reconnect trigger skipped",{guard:"reconnect-paused",reason:e,...this.getReconnectDiagnostic()}):(this.connection.status===s&&this.websocket&&this.closeWebSocket(e,!0,!0),await this.connectWithRetry(e,!1)):Si("Reconnect trigger skipped",{guard:"not-logged-in",reason:e,...this.getReconnectDiagnostic()})}handleDisconnection(e){Si("Connection disconnection handled",{reason:e,...this.getReconnectDiagnostic()}),this.stopHeartbeat(),this.updateStatus(t,e,!0),e!==U&&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(){return new Promise((e,t)=>{const r=this.pickNextServerUrl();Ci("WebSocket connecting",{url:r}),this.clearSocketListeners();let s=!1;const n=setTimeout(()=>{s=!0,Si("WebSocket connection attempt timed out",{url:r,connectTimeout:this.config.connectTimeout,...this.getReconnectDiagnostic()}),t(new Wr("Connection timeout",{code:ft,details:{stage:"ws"}}))},this.config.connectTimeout);this.socketAdapter.connect({url:r,timeoutMs:this.config.connectTimeout}).then(i=>{if(clearTimeout(n),s||this.reconnectPaused)return Si("WebSocket connection result discarded",{url:r,cancelled:s,reconnectPaused:this.reconnectPaused,note:"outer connection promise remains pending",...this.getReconnectDiagnostic()}),void i.close();this.websocket=i,this.socketGeneration+=1,this.inboundMessageQueue=Promise.resolve(),this.attachSocketListeners(i,this.socketGeneration),this.startProvision().then(()=>{if(this.resetProvisionHandlers(),s||this.reconnectPaused)return Si("Provision result discarded",{url:r,cancelled:s,reconnectPaused:this.reconnectPaused,note:"outer connection promise remains pending",...this.getReconnectDiagnostic()}),void this.closeWebSocket(A,!1,!1);e()}).catch(e=>{this.resetProvisionHandlers(),this.closeWebSocket(A,!1,!1),t(e instanceof Error?e:new Error(String(e)))})}).catch(e=>{if(clearTimeout(n),s)return;const r=e instanceof Wr?e:new Wr("Failed to create WebSocket",{code:gt,details:{stage:"ws",cause:e instanceof Error?e.message:String(e)}});this.handleConnectionError(r,A),t(r)})}).catch(e=>{if(e instanceof Wr)throw e;const t=new Wr("Failed to create WebSocket",{code:gt,details:{stage:"ws",cause:e instanceof Error?e.message:String(e)}});throw this.handleConnectionError(t,A),t})}handleWebSocketClose(e){this.suppressNextCloseEvent?this.suppressNextCloseEvent=!1:(Si("WebSocket closed",{code:e.code,reason:e.reason}),this.provisionReject&&this.rejectProvisionAfterQueuedMessages(),this.websocket=null,this.clearSocketListeners(),this.stopHeartbeat(),this.handleDisconnection(R))}async rejectProvisionAfterQueuedMessages(){try{await this.inboundMessageQueue}catch{}this.provisionReject&&(this.provisionReject(new Wr("Provision interrupted",{code:It,details:{stage:"provision"}})),this.resetProvisionHandlers())}handleConnectionError(e,t){if(Ti("Connection error:",e),this.connection.error=e,this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),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(Si("Terminal connection error received",{code:e.code,message:e.message,details:e.details}),this.connection.error=e,this.reconnectPaused=!0,this.reconnectInProgress=!1,this.offlineRecoverPending=!1,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;Ci("WebSocket message received",{dataType:typeof e});const s=await this.msyncCodec.normalizeIncoming(e);if(t!==this.socketGeneration)return;if(Ci("handleWebSocketMessage data",{length:s.length}),!s.length)return;const n=this.msyncCodec.decompressIncoming(s);if(!n){const e=null!==this.provisionReject;return Ti("Failed to decompress mSync payload, closing connection",{stage:e?"provision":"connected"}),void(e?(this.rejectPendingProvision(new Wr("Failed to decompress Provision payload",{code:gt,details:{stage:"provision",cause:"decompression-failed",retryable:!0}})),this.closeWebSocket(A,!1,!1)):this.websocket?.close())}if(this.isServerNormalClosePayload(n))return void Ci("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 Si("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 Si("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(),Ci("handleWebSocketMessage decoded",{command:i.command}),i.command){case os:this.handleProvisionMessage(i.payload);break;case as:this.handleLogoutMessage(i.payload);break;case is:this.handleNoticeMessage(i.payload);break;case ns:this.handleUnreadMessage(i.payload);break;case ss:this.handleSyncMessage(i.payload)}}catch(r){const e=r instanceof Error?r:new Error("Failed to handle mSync payload");Ti("Failed to handle mSync payload",e),this.handleConnectionError(e,A)}}startProvision(){this.provisionPromise=new Promise((e,t)=>{this.provisionResolve=e,this.provisionReject=t}),this.provisionTimeoutId&&clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=setTimeout(()=>{this.rejectPendingProvision(new Wr("Provision timeout",{code:vt,details:{stage:"provision",retryable:!0}}))},1e4);try{const e=this.msyncCodec.encodeProvision();Ci("startProvision provision",{length:e.length}),this.sendMsyncPayload(e)}catch{this.provisionReject?.(new Wr("Provision send failed",{code:gt,details:{stage:"provision"}})),this.resetProvisionHandlers()}return this.provisionPromise}handleProvisionMessage(e){const t=this.msyncCodec.decodeProvision(e);if(this.provisionTimeoutId&&(clearTimeout(this.provisionTimeoutId),this.provisionTimeoutId=null),t.ok)this.msyncCodec.updateResource(t.resource),this.setupTokenLifecycleFromProvision(t.authToken),this.provisionResolve?.();else{Si("Provision rejected",{statusCode:t.statusCode,reason:t.reason});const e=kn(t.statusCode,t.reason),r=e.code===Gr?bt:e.code;this.provisionReject?.(new Wr("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&&Si("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(Ci("handleSyncMessage result",{result:r}),!r)return;(void 0!==r.queue||void 0!==r.nextKey||void 0!==r.isLast)&&this.handleSyncQueueState(r)}handleSyncQueueState(e){Ci("[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?(Si("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);Si("Logout message received",t)}resolveStatisticDisconnectError(e){for(const t of e)switch(t.operation){case 1:return new Wr("User has been removed",{code:Ht,details:{stage:"statistics",operation:t.operation,retryable:!1}});case 2:return new Wr("The user is already logged on another device",{code:Kt,details:{stage:"statistics",operation:t.operation,retryable:!1,...t.reason?{loginInfoCustomExt:t.reason}:{}}});case 3:return new Wr("The user was kicked by changing password",{code:Vt,details:{stage:"statistics",operation:t.operation,retryable:!1}});case 4:return new Wr("The user was kicked by other device",{code:Wt,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.clearTokenTimers(),this.tokenLifecycle=null,this.resetProvisionHandlers(),this.stopHeartbeat(),this.reconnectPaused=!0,this.reconnectInProgress=!1,this.isLoginPhase=!1,this.isLoggedIn=!1,this.offlineRecoverPending=!1,this.closeWebSocket(R,!0,!0),this.updateStatus(t,R,!0),this.resetSyncState(),this.reconnectAttempts=0,this.connection.reconnectAttempts=0,this.connection.error=void 0,this.hasEverConnected=!1,this.connectionEventNormalizer.reset(),Si("Connection disconnected"),Promise.resolve()}destroy(){this.disconnect(),this.eventHub.removeEventHandler(this.internalHandlerId)}resolveSocketAdapter(e){if(e.socketAdapter)return e.socketAdapter;const t=Hd({webSocketCtor:"function"==typeof WebSocket?WebSocket:void 0});if(t)return t;throw Fi("Socket capability is missing for current platform",{code:"PLATFORM_MISSING_CAPABILITY",stage:"socket",retryable:!1,details:{capability:"socket"}})}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;Si("WebSocket error",{stage:"ws"});const t=new Wr("WebSocket connection error",{code:gt,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===ji)try{const t=this.msyncCodec.prepareOutgoing(e);Ci("WebSocket send payload",{length:t.length}),Promise.resolve(this.websocket.send(t)).catch(e=>{Ti("Failed to send mSync payload",e),this.websocket?.close()})}catch(t){Ti("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);Ci("sendBackqueue payload",{length:t.length}),this.sendMsyncPayload(t)}sendLastSession(e,t){Ci("sendLastSession queue",{queueName:this.getQueueName(e),nextKey:t});const r=this.msyncCodec.encodeLastSession(e,t);this.sendMsyncPayload(r)}sendNextQueue(){Ci("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=nm({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 am=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()}},cm=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},dm=()=>{const e=Vi().crypto;return e&&"function"==typeof e.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},um=new Uint8Array([99,109]),lm=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),hm=e=>Array.isArray(e)&&e.every(lm),pm=e=>"string"==typeof e?e:void 0,mm=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,fm=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},gm=(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 Yr("Combine payload length header is invalid",{code:lr});return r<<24|s<<16|n<<8|i},ym=e=>{let t=0;for(let r=2;r<e.length;r+=1)r%2==1&&(t^=e[r]??0);return t},vm=(e,t)=>{const r=vl().lookupType(e).decode(t);if(!lm(r))throw new Error(`${e} decoded result is invalid`);return r},bm=e=>lm(e)&&"string"==typeof e.name?e.name:"",Im=(e,t,r)=>{const s=(hm(e.contents)?e.contents:[])[0];if(!s)throw new Error("MessageBody contents is empty");const n=(e=>{const t=mm(e.type)??ys,r=Boolean(pm(e.remotePath))||Boolean(pm(e.title))||Boolean(pm(e.summary))||(mm(e.combineLevel)??0)>0,s=t===ys&&0===e.subType&&r;if(t===_s||s){const t=mm(e.combineLevel)??0;return{type:"combine",body:{title:pm(e.title)??"",summary:pm(e.summary)??"",filename:pm(e.displayName)??"combine",filetype:"application/octet-stream",url:pm(e.remotePath),secret:pm(e.secretKey),fileLength:mm(e.fileLength),combineLevel:t},combineLevel:t}}if(t===ys)return{type:"text",body:{content:pm(e.text)??""}};if(t===Ss)return{type:"cmd",body:{action:pm(e.action)??""}};if(t===Ts){const t=Rl(hm(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:pm(e.customEvent)??"",params:t}}}if(t===Is)return{type:"location",body:{latitude:mm(e.latitude)??0,longitude:mm(e.longitude)??0,address:pm(e.address),buildingName:pm(e.buildingName)}};if(t===vs){const t=lm(e.size)?e.size:{},r=pm(e.remotePath)??"",s=ni(r),n=pm(e.thumbnailRemotePath),i=oi(e.imageType)===Wn;return{type:"image",body:{localUrl:"",filename:pm(e.displayName)??"image",filetype:"application/octet-stream",width:mm(t.width)??0,height:mm(t.height)??0,isGif:1===e.subType,isOriginalImage:i,originalImageUrl:s.originalImageUrl,bigImageUrl:s.bigImageUrl,secret:pm(e.secretKey),fileLength:mm(e.fileLength),thumbnailUrl:n??s.thumbnailUrl}}}if(t===bs){const t=lm(e.size)?e.size:{};return{type:"video",body:{url:pm(e.remotePath)??"",filename:pm(e.displayName)??"video",filetype:"application/octet-stream",duration:mm(e.duration)??0,width:mm(t.width),height:mm(t.height),secret:pm(e.secretKey),fileLength:mm(e.fileLength),thumbnailUrl:pm(e.thumbnailRemotePath)}}}if(t===ws)return{type:"voice",body:{url:pm(e.remotePath)??"",filename:pm(e.displayName)??"voice",filetype:"application/octet-stream",duration:mm(e.duration)??0,secret:pm(e.secretKey),fileLength:mm(e.fileLength)}};if(t===Cs)return{type:"file",body:{url:pm(e.remotePath)??"",filename:pm(e.displayName)??"file",filetype:"application/octet-stream",secret:pm(e.secretKey),fileLength:mm(e.fileLength)}};return null})(s);if(!n)throw new Error("MessageBody content type is unsupported");const i=bm(e.from)||bm(r?.from)||`unknown-${t}`,o=bm(e.to)||bm(r?.to)||`unknown-${t}`,a=(c=e.type)===us?"groupChat":c===ls?"chatRoom":"singleChat";var c;const d=o||i,u=Number(Tl(r?.timestamp))||Date.now(),l=Rl(hm(e.ext)?e.ext:void 0),h={msgServerId:Tl(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},wm=(e,t)=>{const r=[];try{const n=vm("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=vm("easemob.pb.MessageBody",i);return Im(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=vm("easemob.pb.MessageBody",e);return Im(r,t)}catch(n){r.push(n instanceof Error?n.message:String(n))}try{const r=vm("easemob.pb.MessageBody.Content",e);return Im({type:ds,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("; "))},Cm=(e,t)=>{const r=Ri(e);try{const e=JSON.parse(r);if(!lm(e))throw new Yr("Combine payload item is invalid",{code:lr,details:{index:t}});return e}catch(s){if(s instanceof Yr)throw s;try{return wm(e,t)}catch(n){throw new Yr("Combine payload item parse failed",{code:lr,details:{index:t,cause:s instanceof Error?s.message:String(s),protobufCause:n instanceof Error?n.message:String(n)}})}}},Sm=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Tm=(e,t,r)=>{throw new Zr(e,{code:r,details:{fields:[{path:t,message:e,rule:"invalid_format"}]}})},_m=e=>{if("combine"!==e.type)return 0;const t=e.combineLevel;return"number"==typeof t?t:Sm(e.body)&&"number"==typeof e.body.combineLevel?e.body.combineLevel:0},Rm=(e,t)=>{if(e.sender.userId||Tm(`messageList[${t}] sender.userId is required`,`messageList[${t}].sender.userId`,or),e.conversationId&&["singleChat","groupChat","chatRoom"].includes(e.conversationType)||Tm(`messageList[${t}] conversation is invalid`,`messageList[${t}].conversationId`,or),(!Number.isInteger(e.timestamp)||e.timestamp<=0)&&Tm(`messageList[${t}] timestamp must be positive integer`,`messageList[${t}].timestamp`,or),Sm(e.body)||Tm(`messageList[${t}] body must be object`,`messageList[${t}].body`,or),"combine"===e.type){const r=_m(e);(!Number.isInteger(r)||r<0)&&Tm(`messageList[${t}] combineLevel is invalid`,`messageList[${t}].combineLevel`,or),r>10&&Tm(`messageList[${t}] combineLevel exceeds limit`,`messageList[${t}].combineLevel`,ar)}},Am=(e,t=300)=>{(!Number.isInteger(e)||e<=0)&&Tm("messageList must not be empty","messageList",or),(!Number.isInteger(t)||t<=0||t>300)&&Tm("max items is invalid","maxItems",or),e>t&&Tm(`messageList max length is ${t}`,"messageList",cr)},Mm=e=>{Am(e.length);for(let t=0;t<e.length;t+=1){const r=e[t];void 0!==r?Rm(r,t):Tm(`messageList[${t}] is required`,`messageList[${t}]`,or)}},Em=e=>{let t=0;for(const r of e){if("combine"!==r.type)continue;const e=_m(r);e>t&&(t=e)}return t+1},Um=e=>{(!Number.isInteger(e)||e<=0)&&Tm("combineLevel must be positive integer","combineLevel",or),e>10&&Tm("combineLevel must be <= 10","combineLevel",ar)},Nm=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class km{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(st(e))throw new Qr("Stream message send is not supported",{code:ir,details:{msgLocalId:e.msgLocalId,retryable:!1}});if(!this.websocket||this.websocket.readyState!==ji){const t=this.msyncCodec.toProtocolId(e.msgLocalId);throw new Qr("WebSocket is not connected",{code:St,details:{msgLocalId:e.msgLocalId,protocolId:t,retryable:!0}})}let s={...e,sendStatus:"sending"};wh(e,s),Ci("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"};wh(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 wh(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&&Ci("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&&Ci("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:Nm(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:Nm(e.conversationType)});return new Promise((r,s)=>{const n=this.msyncCodec.toProtocolId(e.msgLocalId),i=setTimeout(()=>{this.pendingMessages.delete(n),this.finishPendingDataReport(t,{code:Tt,success:!1,description:"Message ACK timeout"}),s(new Qr("Message ACK timeout",{code:Tt,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!==ji)throw new Qr("WebSocket is not connected",{code:St,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}),Si("Message send socket failure",{msgLocalId:e.msgLocalId,protocolId:n,websocketReadyState:this.websocket?.readyState??null,cause:o}),s(new Qr(`WebSocket send failed: ${o}`,{code:St,details:{msgLocalId:e.msgLocalId,protocolId:n,retryable:!0,cause:o}}))}),Ci("Message sent",{msgLocalId:e.msgLocalId,protocolId:n})}catch(o){if(this.pendingMessages.delete(n),clearTimeout(i),this.finishPendingDataReport(t,{code:o instanceof Qr?o.code:At,success:!1,description:o instanceof Error?o.message:String(o)}),o instanceof Qr)throw o;throw new Qr("Message encode failed",{code:At,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:Tt,success:!1,description:"Message ACK timeout"}),i(new Qr("Message ACK timeout",{code:Tt,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!==ji)throw new Qr("WebSocket is not connected",{code:St,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 Qr(`WebSocket action send failed: ${r}`,{code:St,details:{protocolId:e,retryable:!0,cause:r}}))})}catch(a){if(this.pendingMessages.delete(e),clearTimeout(o),this.finishPendingDataReport(s,{code:a instanceof Qr?a.code:At,success:!1,description:a instanceof Error?a.message:String(a)}),a instanceof Qr)throw a;i(new Qr("Message encode failed",{code:At,details:{protocolId:e,retryable:!1}}))}})}prepareCombineMessage(e){const t=e.body,r=t.messageList??[];Mm(r);const s=Em(r);Um(s);const n=(e=>{try{const t=e.map((e,t)=>{const r=JSON.stringify(e);if(!r)throw new Qr("Combine payload item encode failed",{code:dr,details:{index:t}});return _i(r)}),r=um.length+t.reduce((e,t)=>e+4+t.length,0)+1,s=new Uint8Array(r);let n=0;s.set(um,n),n+=um.length;for(const e of t){const t=fm(e.length);s.set(t,n),n+=t.length,s.set(e,n),n+=e.length}const i=ym(s.subarray(0,s.length-1));return s[s.length-1]=i,s}catch(t){if(t instanceof Qr)throw t;throw new Qr("Combine payload encode failed",{code:dr,details:{cause:t instanceof Error?t.message:String(t)}})}})(r),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=cm(o);if(!a&&!this.attachmentUploader)throw new Qr("Combine payload local url generation failed",{code:dr});am.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 wh(e,c),Rh(e,c),c}handleAck(e,t,r,s){const n=this.pendingMessages.get(e);if(!n)return void Ci("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};wh(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||am.delete(i.msgLocalId),Ci("Message ACK matched",{protocolId:e,msgLocalId:i.msgLocalId,msgServerId:i.msgServerId??null,type:i.type,conversationType:i.conversationType,conversationId:i.conversationId}),this.eventHub.dispatch(b,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 Qr?t.code:-1,success:!1,description:t.message}),void r.reject(t);const s={...r.message,sendStatus:"failed"};wh(r.message,s),this.pendingMessages.delete(e),this.finishPendingDataReport(r.report,{code:t instanceof Qr?t.code:-1,success:!1,description:t.message}),Si("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 Qr("Message sender destroyed",{code:Rt,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)>=Vp){return void(("message"===e.category?this.messageReportSaturated:this.chatRoomReportSaturated)||(Si("DataReport correlation limit reached",{category:e.category}),"message"===e.category?this.messageReportSaturated=!0:this.chatRoomReportSaturated=!0))}const t=nm({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<Vp&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<Vp&&(this.chatRoomReportSaturated=!1)))}}class Om{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!==rt.START&&t.stream.status!==rt.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 xm{constructor(e,t){this.completedIds=new Set,this.eventHub=e,this.cache=t??new Om}handle(e){const t=this.resolveMessageId(e);if(!t)return void Si("stream message id missing, skip dispatch");if(this.completedIds.has(t))return void Ci("stream message already completed, ignore",{msgId:t});if(e.stream.status===rt.FULL)return void this.handleFullChunk(t,e);const r=this.cache.get(t);if(r?.completed)return void Ci("stream session completed, ignore chunk",{msgId:t,seq:e.stream.seq});const{duplicate:s}=this.cache.addChunk(t,e);s?Ci("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?rt.ERROR:r.stream.status,a=this.buildDispatchMessage(r,{status:o,fullText:i,deltaText:n});if(this.eventHub.dispatch(k,a),this.cache.markDispatched(e,r,i),o===rt.START_COMPLETED||o===rt.COMPLETED||o===rt.ERROR){const t=o===rt.ERROR?"timeout_error":"normal";return this.cache.markCompleted(e,t,i),this.cache.clear(e),void this.markCompleted(e)}}else Ci("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?rt.ERROR:o?rt.START_COMPLETED:rt.COMPLETED,c=this.buildDispatchMessage(t,{status:a,fullText:n,deltaText:i});this.eventHub.dispatch(k,c);const d=a===rt.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:rt.ERROR,fullText:n,deltaText:i});this.eventHub.dispatch(k,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 Lm{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 Pm=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class Dm{constructor(e,t,r){this.eventHub=r,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new xm(r),this.messageContexts=new Map,this.recentMessageIds=new Lm(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{Ci("handleSyncPayload payload",{length:e.length});const t=this.msyncCodec.decodeSync(e);Ci("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&&(Ci("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){Ti("Failed to decode sync payload",t)}return null}handleAck(e,t){if(e.ok)return Ci("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));Si("ACK rejected",{protocolId:e.protocolId,statusCode:e.statusCode,reason:e.reason,hasReplacedMessage:Boolean(t)});const r=((e,t)=>{const r=kn(e,t),s=r.code===Gr?_t:r.code;return{code:s,message:On[s]??(t?`Message send failed: ${t}`:"Message send failed for an unknown reason"),retryable:r.retryable}})(e.statusCode,e.reason),s=new Qr(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(st(e))return void this.streamMessageHandler.handle(e);this.rememberMessageContext(e),this.sendDeliveryAckIfNeeded(e);const t=this.resolveMessageContextId(e);this.recentMessageIds.checkAndRecord(t)?Ci("Duplicate message ignored",{messageId:t}):(this.eventHub.dispatch(N,e),Ci("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=>{Si("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(x,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(Ci("[RosterSync] handleContactNotify",{eventName:e.eventName,type:e.type}),"string"!=typeof e.eventName)return;if(e.eventName!==K&&e.eventName!==H&&e.eventName!==V&&e.eventName!==W&&e.eventName!==J)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(z,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(!Pm(r)||"string"!=typeof r.messageId)continue;const e=this.resolveReactionConversationContext(r);e&&this.eventHub.dispatch(q,{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(!Pm(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(!Pm(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(!Pm(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(!Pm(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(!Pm(e.data))return;const t=e.data;"string"==typeof t.messageId&&"string"==typeof t.conversationId&&this.eventHub.dispatch(L,{messageId:t.messageId,conversationId:t.conversationId,conversationType:"singleChat"})}handleMessageRecalledNotify(e){if(!Pm(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(!Pm(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!Pm(t.message)||"string"!=typeof t.message.type||!Pm(t.message.body)||!Pm(t.message.ext))return;const r={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...Pm(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(D,{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)Pm(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)!Pm(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 qm=e=>e instanceof Error?e.message:String(e);class Bm{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?qd({fetchImpl:fetch}):void 0))(e)}async downloadAndParse(e){const t=e.url.trim();if(!t)throw new Zr("Combine message url is required",{code:or,details:{fields:[{path:"url",message:"Combine message url is required",rule:"required"}]}});const r="number"==typeof e.maxItems?e.maxItems:300;Am(1,r);const s=this.requestAdapter;if(!s)throw new Yr("Request adapter is required for combine message download",{code:ur});const n=ri(t,e.secret);try{const t=await s.request({url:n,method:"GET",responseType:"arraybuffer",timeoutMs:e.timeoutMs??15e3,headers:{[Ml]:Al()}});if(401===t.status||403===t.status)throw new Jr(401===t.status?"Combine payload download unauthorized":"Combine payload download forbidden",{code:401===t.status?dt:ut,details:{url:n,httpStatus:t.status}});if(t.status>=400)throw new Yr("Combine payload download failed",{code:ur,details:{status:t.status,url:n}});const i=(e=>{if(e.length<um.length+1)throw new Yr("Combine payload is too short",{code:lr});const t=e.subarray(0,um.length);if(t[0]!==um[0]||t[1]!==um[1])throw new Yr("Combine payload header is invalid",{code:lr});const r=e.subarray(0,e.length-1),s=ym(r),n=e[e.length-1]??0;if(n!==s)throw new Yr("Combine payload checksum failed",{code:lr,details:{expectedChecksum:s,actualChecksum:n}});const i=[];let o=um.length;const a=e.length-1;for(;o<a;){if(o+4>a)throw new Yr("Combine payload length header is incomplete",{code:lr});const t=gm(e,o);if(o+=4,t<=0||o+t>a)throw new Yr("Combine payload item length is invalid",{code:lr,details:{itemLength:t}});const r=e.subarray(o,o+t);o+=t;const s=Cm(r,i.length);i.push(s)}if(o!==a)throw new Yr("Combine payload has unexpected trailing bytes",{code:lr,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 _i(e);throw new Yr("Combine payload response type is invalid",{code:ur})})(t.data));return Am(i.length,r),Mm(i),i.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(i){if(i instanceof Zr||i instanceof Jr||i instanceof Yr)throw i;throw new Yr("Combine payload download or parse failed",{code:ur,details:{cause:qm(i),url:n}})}}}const $m=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"}},Fm=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 Gm{constructor(e){this.requestAdapter=(e=>e||("function"==typeof fetch?qd({fetchImpl:fetch}):void 0))(e)}async download(e,t=15e3){if("image"!==e.type&&"video"!==e.type&&"voice"!==e.type&&"file"!==e.type)throw new Zr("message does not contain downloadable attachment",{code:Ot,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 Zr("attachment url is required",{code:Ot,details:{fields:[{path:"message.body.url",message:"is required",rule:"required"}]}});if(!this.requestAdapter)throw new Vr("request adapter is required for attachment download");const n=await this.requestAdapter.request({url:ri(r,s),method:"GET",responseType:"arraybuffer",timeoutMs:t,headers:{[Ml]:Al()}});if(401===n.status)throw new Jr("attachment download unauthorized",{code:dt,details:{url:r,httpStatus:n.status}});if(403===n.status)throw new Jr("attachment download forbidden",{code:ut,details:{url:r,httpStatus:n.status}});if(404===n.status){const e=("string"==typeof n.data?n.data:"").includes("expired");throw new Hr(e?"attachment file is expired":"attachment not found",e?xt:kt)}if(429===n.status)throw new Hr("attachment download rate limited",Fr);if(n.status>=400)throw new Hr("attachment download failed",er,{details:{status:n.status,url:r}});return{filename:$m(e),mimeType:Fm(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 jm=(e,t,r)=>({Authorization:`Bearer ${e}`,Accept:t,[Ml]:Al(),...r??{}}),zm=async e=>{const t=jm(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;if(Ci("Upload request start",{operation:e.operation,method:e.method}),e.requestAdapter)try{const s=await e.requestAdapter.request({url:e.url,method:e.method,headers:t,responseType:"json",timeoutMs:xn});i=s.status;const a=Date.now()-r;if(s.status<200||s.status>=300)throw Si("Upload response error",{operation:e.operation,method:e.method,status:s.status,duration:a}),new rs("Upload request failed",{code:qr,details:{url:e.url,status:s.status}});Ci("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(d){if(n?.finish({code:0!==i?i:d instanceof rs?d.code:qr,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof rs)throw d;throw Si("Upload request failed",{operation:e.operation,method:e.method}),new rs("Upload request failed",{code:qr,details:{url:e.url}})}var o;const a=new AbortController,c=setTimeout(()=>a.abort(),xn);try{const s=await fetch(e.url,{method:e.method,headers:t,signal:a.signal});i=s.status;const o=Date.now()-r;if(!s.ok)throw Si("Upload response error",{operation:e.operation,method:e.method,status:s.status,duration:o}),new rs("Upload request failed",{code:qr,details:{url:e.url,status:s.status}});return Ci("Upload response success",{operation:e.operation,method:e.method,status:s.status,duration:o}),n?.finish({code:s.status,success:!0}),await s.json()}catch(d){if(n?.finish({code:0!==i?i:d instanceof rs?d.code:qr,success:!1,description:d instanceof Error?d.message:String(d)}),d instanceof rs)throw d;if(d instanceof Error&&"AbortError"===d.name)throw Si("Upload request timeout",{operation:e.operation,method:e.method,timeout:xn}),new rs("Upload timeout",{code:Br,details:{url:e.url,timeout:xn}});throw Si("Upload request failed",{operation:e.operation,method:e.method}),new rs("Upload request failed",{code:qr,details:{url:e.url}})}finally{clearTimeout(c)}},Km=(e,t,r,s,n,i)=>new Promise((o,a)=>{const c=new XMLHttpRequest,d=Date.now(),u=i?.startRequest({requestName:"REST_UPLOAD_PART",method:"PUT",url:e});Ci("Upload part start",{operation:"upload.multipart.part",partNumber:r}),c.upload&&n&&c.upload.addEventListener("progress",e=>{n(e.loaded)},!1),c.addEventListener("abort",()=>{u?.finish({code:$r,success:!1,description:"Upload aborted"}),Si("Upload part aborted",{operation:"upload.multipart.part",partNumber:r}),a(new rs("Upload aborted",{code:$r,details:{url:e,partNumber:r}}))},!1),c.addEventListener("error",()=>{u?.finish({code:qr,success:!1,description:"Upload part failed"}),Si("Upload part failed",{operation:"upload.multipart.part",partNumber:r}),a(new rs("Upload part failed",{code:qr,details:{url:e,partNumber:r}}))},!1),c.addEventListener("timeout",()=>{u?.finish({code:Br,success:!1,description:"Upload timeout"}),Si("Upload part timeout",{operation:"upload.multipart.part",partNumber:r,timeout:xn}),a(new rs("Upload timeout",{code:Br,details:{url:e,partNumber:r}}))},!1),c.addEventListener("load",()=>{const t=Date.now()-d;if(200!==c.status)return u?.finish({code:c.status,success:!1,description:"Upload part failed"}),Si("Upload part error",{operation:"upload.multipart.part",partNumber:r,status:c.status,duration:t}),void a(new rs("Upload part failed",{code:qr,details:{url:e,partNumber:r,status:c.status}}));Ci("Upload part success",{operation:"upload.multipart.part",partNumber:r,duration:t}),u?.finish({code:c.status,success:!0}),o()},!1);const l=new FormData;l.append("part_file",s),l.append("part_number",r),c.timeout=xn,c.open("PUT",e),Object.entries(jm(t,"*/*",{"restrict-access":"true"})).forEach(([e,t])=>{c.setRequestHeader(e,t)}),c.send(l)}),Hm=async e=>{if(e.fileSize<=jn)throw new rs("Multipart not required",{code:qr,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,{orgName:p,appName:m}=Qn(t.appKey),f=`${t.restBaseUrl}/${p}/${m}/sdk/chatfiles/part-upload`;let g;try{g=await zm({url:f,method:"POST",token:t.token,operation:"upload.multipart.init",requestAdapter:t.requestAdapter,dataReportOperation:e.dataReportOperation})}catch(M){throw new rs("Multipart init failed",{code:qr,details:{stage:"init",cause:M,url:f}})}const y=(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:zn,n="string"==typeof t?.uuid?t.uuid:"";if(!n)throw new rs("Multipart init failed",{code:qr,details:{response:e}});return{fileMaxSize:r,partMinSize:s,uuid:n}})(g);if(y.fileMaxSize&&a>y.fileMaxSize)throw new rs("File size exceeds limit",{code:Dr,details:{fileSize:a,maxSize:y.fileMaxSize}});const v=y.partMinSize||zn,b=Math.ceil(a/v),I=Array.from({length:b},()=>0),w=`${t.restBaseUrl}/${p}/${m}/sdk/chatfiles/part-upload/${y.uuid}`,C=[],S=(t,r)=>{I[t]=r;const s=I.reduce((e,t)=>e+t,0),n=a?s/a*100:void 0;e.callbacks?.onFileUploadProgress?.({loaded:s,total:a,percent:n})};for(let E=0;E<b;E+=1){const s=E*v,n=Math.min(a,s+v),i=r.slice(s,n),o=String(E+1),c=Km(w,t.token,o,i,e=>S(E,e),e.dataReportOperation).finally(()=>{const e=C.indexOf(c);e>=0&&C.splice(e,1)});C.push(c),C.length>=4&&await Promise.race(C)}await Promise.all(C);const T=Yn(n),_=ti(`${t.restBaseUrl}/${p}/${m}/sdk/chatfiles/part-upload/${y.uuid}`,{"restrict-access":"true","chat-type":T,"chat-target":s,"thumbnail-width":e.thumbnailWidth,"thumbnail-height":e.thumbnailHeight,md5:u??"",..."image"===c?{imageType:ii(d),width:l,height:h}:{}}),R=await zm({url:_,method:"POST",token:t.token,operation:"upload.multipart.complete",requestAdapter:t.requestAdapter,dataReportOperation:e.dataReportOperation}),A=ai({response:R,restBaseUrl:t.restBaseUrl,orgName:p,appName:m,fileType:o,fileName:i,fallbackSize:a,messageType:c,imageType:d,useCustomAttachmentUpload:t.useCustomAttachmentUpload});return e.callbacks?.onFileUploadComplete?.(A),A},Vm=e=>new Promise((t,r)=>{const{config:s,file:n,conversationId:i,conversationType:o,messageType:a,imageType:c,md5:d,width:u,height:l,fileName:h,fileType:p,fileSize:m}=e,{orgName:f,appName:g}=Qn(s.appKey),y=Yn(o),v=ti(`${s.restBaseUrl}/${f}/${g}/chatfiles`,{"chat-type":y,"chat-target":i,md5:d??"",..."image"===a?{imageType:ii(c),width:u,height:l}:{}}),b=Date.now(),I=e.dataReportOperation?.startRequest({requestName:"UPLOAD_MSG_ATTACH",method:"POST",url:v});Ci("Upload request start",{operation:"upload.simple",method:"POST",fileSize:m,messageType:a});const w=new XMLHttpRequest;w.upload&&e.callbacks?.onFileUploadProgress&&w.upload.addEventListener("progress",t=>{if(!t.lengthComputable)return void e.callbacks?.onFileUploadProgress?.({loaded:t.loaded});const r=t.total?t.loaded/t.total*100:void 0;e.callbacks?.onFileUploadProgress?.({loaded:t.loaded,total:t.total,percent:r})},!1),w.addEventListener("abort",()=>{I?.finish({code:$r,success:!1,description:"Upload canceled"}),Si("Upload request aborted",{operation:"upload.simple"}),e.callbacks?.onFileUploadCanceled?.(),r(new rs("Upload canceled",{code:$r,details:{url:v}}))},!1),w.addEventListener("error",()=>{I?.finish({code:qr,success:!1,description:"Upload failed"}),Si("Upload request failed",{operation:"upload.simple"}),r(new rs("Upload failed",{code:qr,details:{url:v}}))},!1),w.addEventListener("timeout",()=>{I?.finish({code:Br,success:!1,description:"Upload timeout"}),Si("Upload request timeout",{operation:"upload.simple",timeout:xn}),r(new rs("Upload timeout",{code:Br,details:{url:v,timeout:xn}}))},!1),w.addEventListener("load",()=>{try{const r=Date.now()-b,n=JSON.parse(w.responseText);if(w.status>=400)throw I?.finish({code:w.status,success:!1,description:"Upload failed"}),Si("Upload response error",{operation:"upload.simple",status:w.status,duration:r}),new rs("Upload failed",{code:qr,details:{status:w.status,response:n}});Ci("Upload response success",{operation:"upload.simple",status:w.status,duration:r});const i=ai({response:n,restBaseUrl:s.restBaseUrl,orgName:f,appName:g,fileType:p,fileName:h,fallbackSize:m,messageType:a,imageType:c,useCustomAttachmentUpload:s.useCustomAttachmentUpload});e.callbacks?.onFileUploadComplete?.(i),I?.finish({code:w.status||200,success:!0}),t(i)}catch(n){I?.finish({code:n instanceof rs?n.code:qr,success:!1,description:n instanceof Error?n.message:String(n)}),r(n instanceof Error?n:new Error(String(n)))}},!1),w.timeout=xn,w.open("POST",v),w.setRequestHeader("restrict-access","true"),w.setRequestHeader("Accept","*/*"),w.setRequestHeader("Authorization",`Bearer ${s.token}`),w.setRequestHeader(Ml,Al());const C=new FormData;C.append("file",n,h),void 0!==e.thumbnailWidth&&C.append("thumbnail-width",String(e.thumbnailWidth)),void 0!==e.thumbnailHeight&&C.append("thumbnail-height",String(e.thumbnailHeight)),w.send(C)}),Wm=hu(),Jm=e=>Object.prototype.toString.call(e),Zm=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:Jm(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}},Qm=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}),Ym=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,Xm=e=>"object"==typeof e&&null!==e,ef=(e,t)=>{const r=Xm(t)?t:void 0,s=r?.code===Pi&&r.stage===xi;return"miniapp-path"===e&&(e=>{if(!Xm(e))return!1;const t=Xm(e.details)?e.details:void 0;return e.code===Pi&&e.stage===xi&&"string"==typeof t?.capability&&t.capability.includes("FileSystem")})(t)||"rn-uri"===e&&s};class tf{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(!Ym(e.type))return e;const r=e.body;if(this.hasUploadedRemoteResource(e.type,r))return e;const s=this.resolveUploadUrl(e.type,r),n=am.get(e.msgLocalId),i=Boolean(n);if(Si("Attachment upload prepare entry",{operation:"upload.prepare.entry",msgLocalId:e.msgLocalId,messageType:e.type,conversationType:e.conversationType,hasFile:i,uploadUrl:s,cachedFile:Zm(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||!Zn(e))(s,i))return e;if(!n)throw new rs("Attachment file is required",{code:Lr,details:{msgLocalId:e.msgLocalId,url:s}});if(!this.config?.restBaseUrl)throw new rs("REST base url is required for upload",{code:Lr,details:{reason:"restBaseUrl missing"}});let o,a,c;try{o=await this.prepareAttachmentUpload(e,r,n),o.precheck?.hit||(c=nm({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=ll(d);throw c?.finish({code:e.code,success:!1,description:e.message}),e.code===$r&&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&&Zn(e.originalImageUrl)}return"url"in t&&"string"==typeof t.url&&Zn(t.url)}async prepareAttachmentUpload(e,t,r){const s=((e,t)=>{if(!e)throw new rs("Attachment file is required",{code:Lr,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=Gn({file:e,fallbackName:t.filename,fallbackMimeType:t.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new rs("Attachment file is required",{code:Lr,details:{reason:"web file missing"}});return s})(r,t);if(Si("Attachment file normalized",{operation:"upload.prepare.normalized",messageType:e.type,fileInfo:Qm(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===Wn},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:Wn,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:Wn,reason:"explicit-original"}:{resolvedImageType:Jn,reason:"default-large"})(e);if(Si("Image send policy resolved",{operation:"upload.image.policy",reason:r.reason,imageType:r.resolvedImageType,isGif:e.isGif,source:Qm(t)}),r.resolvedImageType===Wn){let s=e.width,n=e.height;if(!s||!n){const e=this.resolveImageProcessor(t.source.sourceType);Si("Image original info resolving",{operation:"upload.image.info",processorSourceType:t.source.sourceType,source:Qm(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);Si("Image big generation start",{operation:"upload.image.big.start",processorSourceType:t.source.sourceType,source:Qm(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 Si("Image big generation failed, fallback to original",{operation:"upload.image.big-fallback",reason:r.reason,error:s instanceof Error?s.message:String(s),source:Qm(t)}),{imagePolicy:{resolvedImageType:Wn,reason:"large-fallback-origin"},sourceKind:"origin",fileInfo:t,width:e.width??0,height:e.height??0}}}async maybePrecheck(e,t,r,s){if(!Ym(e.type))return;if(!0!==this.config?.enableMd5Check)return void Ci("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=si({messageType:e.type,fileSize:t.fileSize,imageType:s});if(!n.shouldPrecheck)return void Ci("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(ef(r.source.sourceType,a))return void Si("Attachment precheck skipped because md5 is unavailable",{operation:"upload.precheck.md5-unavailable",messageType:e.type,imageType:s,thresholdType:n.thresholdType,source:Qm(r),error:a instanceof Error?a.message:String(a)});throw a}const o=await this.requestPrecheck(e,n.thresholdType,i,s);return Ci(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 Si("Attachment md5 compute start",{operation:"upload.md5.start",source:Qm(e)}),t.computeMd5(e.source)}resolveImageProcessor(e){if(this.config?.imageProcessor)return Si("Image processor resolved from platform adapter",{operation:"upload.image.processor",sourceType:e,processor:"platform"}),this.config.imageProcessor;if("web-file"===e)return Si("Image processor resolved from web fallback",{operation:"upload.image.processor",sourceType:e,processor:"web-fallback"}),Wm;throw Si("Image processor missing",{operation:"upload.image.processor-missing",sourceType:e}),Fi("Image processor capability is missing for current platform",{code:Pi,stage:xi,retryable:!1,details:{capability:"imageProcessor",sourceType:e}})}async requestPrecheck(e,t,r,s){if(!this.config)throw new rs("Upload config is required",{code:Lr});const{orgName:n,appName:i}=Qn(this.config.appKey),o=ti(`${this.config.restBaseUrl}/${n}/${i}/chatfiles/exists`,{md5:r,..."image"===e.type?{imageType:ii(s)}:{}}),a=await this.requestJson({url:o,method:"GET",headers:{Authorization:`Bearer ${this.config.token}`,Accept:"application/json"},operation:"upload.precheck"}).catch(n=>{Si("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?Wn:i===Jn||i===Wn?i:void 0,a="string"==typeof t?.["share-secret"]?t["share-secret"]:void 0;if(r&&!s)throw new rs("Upload precheck response missing uuid",{code:qr,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.config?.requestAdapter?this.requestByAdapter(this.config.requestAdapter,e):this.requestByFetch(e)}async requestByAdapter(e,t){const r=await e.request({url:t.url,method:t.method,headers:t.headers,responseType:"json",timeoutMs:xn});if(r.status>=400)throw new rs("Upload precheck request failed",{code:qr,details:{url:t.url,status:r.status,operation:t.operation}});return r.data}async requestByFetch(e){if("function"!=typeof fetch)throw Fi("Request capability is missing for current platform",{code:Pi,stage:Ui,retryable:!1,details:{operation:e.operation}});const t=new AbortController,r=setTimeout(()=>t.abort(),xn);try{const r=await fetch(e.url,{method:e.method,headers:e.headers,signal:t.signal});if(!r.ok)throw new rs("Upload precheck request failed",{code:qr,details:{url:e.url,status:r.status,operation:e.operation}});return await r.json()}finally{clearTimeout(r)}}buildPrecheckedUploadResult(e,t,r){if(!this.config||!t.precheck)throw new rs("Precheck result is required",{code:qr});if(!t.precheck.uuid)throw new rs("Precheck hit missing uuid",{code:qr,details:{precheck:t.precheck}});if(!Ym(e.type))throw new rs("Attachment message type is invalid",{code:Lr,details:{messageType:e.type}});const{orgName:s,appName:n}=Qn(this.config.appKey),i="image"===e.type?t.precheck.existsType??t.imageType:void 0,o="image"===e.type&&i===Wn?t.md5FileInfo:t.fileInfo,a="image"===e.type&&i===Wn?t.originalWidth:"image"===e.type?t.body.width:void 0,c="image"===e.type&&i===Wn?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=ai({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 rs("Upload config is required",{code:Lr});if(!Ym(e.type))throw new rs("Attachment message type is invalid",{code:Lr,details:{messageType:e.type}});const n=e.type,i=await this.resolveUploadMetadata(n,t);if(this.config.uploadAdapter)return Si("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:n,source:Qm(t.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,e,t,i,r);if(!t.fileInfo.webFile)throw new rs("Upload adapter is required for non-web file source",{code:Lr,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>jn;if(Si("Attachment web upload selected",{operation:"upload.web.selected",messageType:n,source:Qm(t.fileInfo),multipartEnabled:a,uploadMode:c?"multipart":"simple"}),c)try{return await Hm(o)}catch(d){const e=d instanceof rs?d.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return Vm(o);throw d}return Vm(o)}async uploadByAdapter(e,t,r,s,n){if(!this.config)throw new rs("Upload config is required",{code:Lr});const{orgName:i,appName:o}=Qn(this.config.appKey),a=Yn(t.conversationType);if(!Ym(t.type))throw new rs("Attachment message type is invalid",{code:Lr,details:{messageType:t.type}});const c=t.type,d=ti(`${this.config.restBaseUrl}/${i}/${o}/chatfiles`,{"chat-type":a,"chat-target":t.conversationId,md5:s.md5,..."image"===c?{imageType:ii(r.imageType),width:s.width,height:s.height}:{}}),u={},l={"restrict-access":"true",Accept:"*/*",Authorization:`Bearer ${this.config.token}`,[Ml]:Al()},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)),Si("Attachment adapter upload start",{operation:"upload.adapter.start",messageType:c,source:Qm(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?tr:"string"==typeof e&&e.includes("content improper")?rr:qr;throw new rs("Upload failed",{code:t,details:{status:m.status,response:m.body}})}let f;try{f=JSON.parse(m.body)}catch(y){throw new rs("Upload response parse failed",{code:qr,details:{response:m.body,cause:y instanceof Error?y.message:String(y)}})}const g=ai({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 wh(e,n),Rh(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 wh(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 wh(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 wh(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 wh(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(!ef(t.md5FileInfo.source.sourceType,n))throw n;Si("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:Qm(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 rf{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 sf="__internal:core";class nf{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 om({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const r=this.connectionManager.getMsyncCodec(),s=e.restBaseUrl?new tf({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 km(r,null,this.eventHub,s),this.messageReceiver=new Dm(r,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new Bm(e.platformAdapter?.request),this.attachmentDownloader=new Gm(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(sf,{[a]:e=>{const t=this.connectionManager.getWebSocket();t&&this.messageSender.setWebSocket(t)},[c]:e=>{this.messageSender.setWebSocket(null)},[d]:e=>{this.messageSender.setWebSocket(null)},[b]:e=>{this.messageReceiver.rememberSentMessageContext(e)}})}registerNetworkListeners(){const e=this.resolveRuntimeAdapter();this.runtimeEventBridge=new rf(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(){return this.connectionManager.connect()}async disconnect(){return this.connectionManager.disconnect()}getConnectionStatus(){return this.connectionManager.getConnectionStatus()}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(sf),am.clear()}}const of=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)},af=e=>{const t=new Uint8Array(Vc.util.base64.length(e));return Vc.util.base64.decode(e,t,0),t};class cf{getCrypto(){return Vi().crypto}constructor(e,t){if(this.enabled=(()=>{const e=Vi();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=co(e);if("web"!==t.framework&&"worker"!==t.framework&&t.platform!==Mi.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:of(s),ct:of(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=af(t.iv),s=af(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 df="conversationMap",uf="userInfoMap",lf="groupNamecardMap",hf="contactRelationMap",pf="contactVersion",mf="contactMeta",ff="sessionListMap",gf="sessionListCheckpoint",yf="joinedGroupPreview",vf="metadata",bf=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class If{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 wf=()=>{const e="undefined"!=typeof window?window.localStorage:void 0;if(e&&"function"==typeof e.getItem)return e;const t=Vi().localStorage;return t&&"function"==typeof t.getItem?t:null};class Cf{constructor(e,t){this.storage=t??Cf.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!Cf.checkAvailable())return null;const e=wf();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=wf();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 $l(s,t)}catch(r){return Si("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(Tu(n))throw n;if(r)throw n;Si("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){Si("CacheStore remove failed",t)}}}const Sf={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},Tf={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class _f{constructor(){this.items=new Map,this.versionState=Sf,this.meta=Tf}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(!Bl(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 Bl(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"}:Sf}normalizeMeta(e){return Bl(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"}:Tf}}const Rf=(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}},Af=(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}},Mf=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 Ef{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=Rf(this.items,e,t);return this.items=[...r.kept],r.removed.length>0}evictByLru(e){const t=Af(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:Mf(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(!Bl(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=Bl(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 Uf=(e,t)=>`${e}:${t}`;class Nf{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(Uf(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,r,s){const n=Uf(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(Uf(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=Uf(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(Uf(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=Rf(n,e,t),o=new Set(i.removed.map(e=>Uf(e.groupId,e.userId)));this.items.clear();for(const a of s)o.has(Uf(a.groupId,a.userId))||this.items.set(Uf(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=Af(s,Math.min(e,s.length)),i=new Set(n.removed.map(e=>Uf(e.groupId,e.userId)));this.items.clear();for(const o of r)i.has(Uf(o.groupId,o.userId))||this.items.set(Uf(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||!Bl(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,Of=3e3,xf=e=>({...e}),Lf=e=>"object"==typeof e&&null!==e,Pf=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 Df{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:kf,serverLimit:Of,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:kf,serverLimit:Of,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return Lf(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:Pf(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=Lf(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:Of,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=>xf(e)).slice(0,kf),this.meta={...e.meta,source:"localPreview",storageLimit:kf,serverLimit:Of,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>xf(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>xf(e)),meta:{...this.meta,source:"localPreview"}}}}const qf=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,Bf=e=>{const t={...e};return delete t.type,t},$f=e=>{if(!Bl(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!Bl(e.body))return null;const r=((e,t)=>{if(Bl(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=qf(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(Bl(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:Bf(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}:{}}},Ff=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},Gf=(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 jf{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(Gf)}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(Gf)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!Bl(e))return null;const r=e,s="string"==typeof r.conversationId?r.conversationId:"";if(!s)return null;const n=qf(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:$f(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:Ff(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 zf{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=Rf(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=Af(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(!Bl(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 Kf=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,Hf=e=>e.lastMessageAt??e.updatedAt,Vf=e=>[...e].sort((e,t)=>{const r=Kf(t)-Kf(e);if(0!==r)return r;const s=Hf(t)-Hf(e);return 0!==s?s:e.conversationId.localeCompare(t.conversationId)}),Wf=e=>`${e.conversationType}:${e.conversationId}`,Jf=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,Zf=(e,t)=>((e,t)=>Hf(t)>Hf(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:Jf(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,Qf=e=>{const t=new Map,r=new Set;for(const i of e.snapshot)r.add(Wf(i));for(const i of e.existing)t.set(Wf(i),i);const s=e.snapshot.map(e=>{const r=t.get(Wf(e));return r?Zf(e,r):e}),n=e.existing.filter(t=>!r.has(Wf(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return Vf([...s,...n])},Yf=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],Xf=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),eg=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 tg{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,Yf.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 rg=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class sg{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 cf(e.appKey,e.userId);this.store=new Cf(t??void 0,e.storageAdapter);const r={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=bf(r,df),this.userInfoKey=bf(r,uf),this.groupNamecardKey=bf(r,lf),this.sessionListKey=bf(r,ff),this.sessionListCheckpointKey=bf(r,gf),this.joinedGroupPreviewKey=bf(r,yf),this.contactRelationKey=bf(r,hf),this.contactVersionKey=bf(r,pf),this.contactMetaKey=bf(r,mf),this.metadataKey=bf(r,vf),this.metadataStore=new If(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new Ef,this.userInfoCache=new zf,this.groupNamecardCache=new Nf,this.sessionListCache=new jf,this.joinedGroupPreviewCache=new Df,this.contactCache=new _f,this.userInfoRuntimeStore=new tg,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 Df;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=Qf({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?Xf(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,r)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([eg(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=Wf(e.nextRecord),r=e.existing.filter(e=>Wf(e)!==t);return Vf([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&&Bl(n)&&Array.isArray(n.items)?n.items:[];this.sessionListCache.load(i,e);const o=(n&&Bl(n)&&Bl(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&&Bl(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&Bl(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(!Tu(t))return this.restoreDirtyBatch(e),void Si("Cache flush failed",t);const s=this.handleQuotaExceeded();if(this.addQuotaCleanupDomains(e,s),"none"===s)return void Si("Cache flush failed: no cache entry can be evicted",t);try{await this.writeDomain(s)}catch(r){if(!Tu(r))return this.restoreDirtyBatch(e),void Si("Cache quota cleanup persistence failed",r)}}Si("Cache flush failed after quota cleanup attempts")}finally{}}async writeDirtyDomains(e){for(const t of rg)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=>Kf(e)>0),r=new Map;for(const n of e.incoming)r.set(Wf(n),n);const s=t.length>0?e.existing.filter(e=>!r.has(Wf(e))&&0===Kf(e)):e.existing.filter(e=>!r.has(Wf(e)));return Vf([...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(Qf({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=Ih(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?Xf(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 ng{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=>{Ti(`Event handler error for ${e}`,t)}):null}catch(s){return Ti(`Event handler error for ${e}`,s),null}}isPromiseLike(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}}const ig={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function og(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 ag(e){return new Promise(t=>setTimeout(t,e))}const cg=e=>{const t={...e};return delete t.type,t},dg=(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:cg(r.body),modifiedInfo:r.modifiedInfo,userInfoUpdateTime:r.userInfoUpdateTime,namecardUpdateTime:r.namecardUpdateTime}},ug=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},lg=async(e,t)=>{const r=await ug(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:dg(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 hg{constructor(e=`session-list-${dm()}`){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 Hr("Session-list sync session cannot re-enter syncing state after completion",Sr);this.status="syncing"}pushBatch(e){if(e.requestId!==this.requestId)throw new Hr("Session-list sync requestId mismatch",Sr,{details:{expected:this.requestId,received:e.requestId}});if(this.isTerminal())throw new Hr("Session-list sync batch received after terminal state",Sr,{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 pg=0,mg=5,fg=10,gg=11,yg=1,vg=2,bg=1,Ig=2,wg=3,Cg=e=>e===yg?"groupChat":e===vg?"chatRoom":"singleChat",Sg=()=>vl().lookupType("easemob.pb.MessageBody"),Tg=e=>{const t=Sg().toObject(Sg().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:ys,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===_s||i===ys&&(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===ys?{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:""}:{}},_g=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}},Rg=e=>{const t={...e};return delete t.type,t},Ag=e=>"singleChat"===e.conversationType?e.from===e.currentUserId?e.conversationId:e.currentUserId:e.conversationId,Mg=(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:Ag({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:Rg(t)};var i},Eg=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},Ug=(e,t)=>e.sessions.map(e=>{const r=(e=>{if(!e||0===e.byteLength)return{};try{return Tg(e)}catch{return{}}})(e.last_message?.payload),s=e.session_id??"",n=Cg(e.session_type),i=(e=>{const t=e.session_id??"",r=Cg(e.session_type);return"groupChat"===r||"chatRoom"===r?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:_g(e)})(e);return{conversationId:s,conversationType:n,unreadCount:e.unread_count??0,lastMessage:Mg(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:Eg(e.marks),readAt:e.read_receipt,remindType:(o=e.remind_type,o===bg?"ALL":o===Ig?"AT":o===wg?"NONE":"DEFAULT"),conversationName:i.conversationName,conversationAvatar:i.conversationAvatar};var o}),Ng={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 kg=null,Og=!1;const xg=()=>kg||(Og||(Vc.util.Long=mo,Vc.configure(),Og=!0),Sd(),kg=Vc.Root.fromJSON(Ng),Cd(kg),kg),Lg=e=>xg().lookupType(e),Pg=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}},Dg=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:Pg(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:Pg(t.protocol_version)??Pg(t.protocolVersion)??0}},qg=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}},Bg=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==Pg(t.id)?String(Pg(t.id)):void 0,from:qg(t.from),timestamp:Pg(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 $g{constructor(){this.requestType=Lg("easemob.sessionlist.GetSessionListRequest"),this.responseType=Lg("easemob.sessionlist.GetSessionListResponse"),this.errorType=Lg("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:pg}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=Pg(t.type);return r!==fg?null:{type:r,header:Dg(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:Pg(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=Pg(t.type);return r!==gg?null:{type:r,header:Dg(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:Pg(t.session_type),last_message:Bg(t.last_message),updated_at:Pg(t.updated_at),pinned_time:Pg(t.pinned_time),unread_count:Pg(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:Pg(t.read_receipt),remind_type:Pg(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:Pg(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=Pg(t.type);return r!==mg?null:{type:r,header:Dg(t.header),code:Pg(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const Fg=async e=>{const t=e.client.getCacheManager(),r=e.client.getRestContext(),s=e.client.getSessionListSyncWsUrls();if(!t||0===s.length)throw new Wr("session-list sync websocket is unavailable",{code:gt,details:{protocol:"session-list",stage:"socket_connect"}});const[n,i]=r.appKey.split("#");if(!n||!i)throw new Zr("session-list appKey is invalid",{code:it,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 $g;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 Jr(s.message,{code:lt,details:{protocol:"session-list",responseCode:s.code}}):1003===s.code?new Hr(s.message,Nt,{details:{protocol:"session-list",responseCode:s.code}}):1501===s.code||1001===s.code?new Zr(s.message,{code:it,details:{protocol:"session-list",responseCode:s.code}}):1503===s.code?new Hr(s.message,Ut,{details:{protocol:"session-list",responseCode:s.code}}):(s.code,new Hr(s.message,fr,{details:{protocol:"session-list",responseCode:s.code}}));var s;if(11!==t.type)throw new Hr("session-list response type is invalid",Mt,{details:{responseType:t.type}});const n=t,i=n.header?.requestId;if(i&&i!==e.session.getRequestId())return;u+=1,Ci("Decoded session-list sync raw response",{requestId:e.session.getRequestId(),batchSequence:u,response:n});const o=Ug(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}}}})},Gg=e=>new Zr(`${e} must be a local paging cursor returned by SDK`,{code:it,details:{fields:[{path:e,message:`${e} must be a local paging cursor returned by SDK`,rule:"invalid_format"}]}}),jg=(e,t,r)=>{const s=e+t;return s<r?String(s):""},zg=e=>({...e}),Kg=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}},Hg=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,Vg=e=>{if(!Number.isInteger(e.pageSize)||e.pageSize<=0)throw new Zr("pageSize must be a positive integer",{code:it,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 Gg(t);const r=Number.parseInt(e,10);if(!Number.isSafeInteger(r)||r<0)throw Gg(t);return r})(e.cursor,"cursor"),r=[];for(const s of e.items){if("chatRoom"===s.conversationType)continue;const e=Hg(s.remindType);e&&r.push({conversationId:s.conversationId,conversationType:s.conversationType,remindType:e})}return{conversations:r.slice(t,t+e.pageSize),cursor:jg(t,e.pageSize,r.length)}},Wg=()=>Date.now(),Jg={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},Zg=(e,t)=>({status:e,determinedAt:Wg(),reason:t}),Qg=e=>e instanceof Hr&&(e.code===Nt||1103===e.code),Yg=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:Qg(e)});class Xg{constructor(e){this.running=null,this.currentSession=null,this.capabilityState={status:"unknown"},this.client=e}getCapabilityState(){return this.capabilityState}refresh(e){return this.running||(this.currentSession=new hg,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[];this.client.emitSyncDataStart("conversation");const s=await this.tryDirectFallback(r);if(s)return this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"success"}),s;try{const s=r.loadSessionListCheckpoint().sessionsLastSyncTs>0?"incremental":"full";let i=0;const o=await async function(e,t,r={}){const s={...ig,...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=og(o,s);await ag(e)}throw n}(async()=>{i+=1;const r=1===i?e:this.createRetrySession();r.start();try{return await Fg({client:this.client,session:r,params:t})}catch(s){throw r.fail(),s}},Qg,Jg),a={result:o,syncStartedAt:e.getStartedAt()},c=a.result.items;this.capabilityState={status:"available",determinedAt:Wg()};const d={lastSyncTime:a.result.lastSyncFinishedTs,lastSyncFinishedTs:a.result.lastSyncFinishedTs,sessionsLastSyncTs:a.result.lastSyncFinishedTs,lastSuccessfulAt:Wg()};try{await r.commitSessionListSync({items:c,mode:s,checkpoint:d,syncStartedAt:a.syncStartedAt})}catch(n){e.fail();const t=new Xr("Session-list final persistence failed",{details:{cause:n instanceof Error?n.message:String(n)}});return this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"failed",error:Yg(t)}),r.loadSessionList()}const u=r.loadSessionList();return r.updateConversationsFromServer(u.map(Kg),{syncStartedAt:a.syncStartedAt}),await r.flushPending(),this.client.emitConversationListUpdate("conversation","full"===s),this.client.emitSyncDataFinished({dataType:"conversation",status:"success"}),u}catch(n){const t=n instanceof Hr?n:new Hr(n instanceof Error?n.message:String(n));e.fail();const s=(e=>e.code===Ut||e.code===dt?{capabilityState:Zg("unsupported",e.message),shouldUseFallback:!0}:e.code===lt||e.code===ht?{shouldUseFallback:!0}:e.code===Nt||1103===e.code?{shouldUseFallback:!0,shouldRetry:!0}:e.code===Sr?{shouldUseFallback:!0,shouldResetCheckpoint:!0}:{shouldUseFallback:!0})(t);s.capabilityState&&(this.capabilityState=s.capabilityState),s.shouldResetCheckpoint&&r.resetSessionListCheckpoint();const i=await this.buildFallbackSessionList(r);return s.shouldUseFallback&&r.replaceSessionList(i),this.client.emitConversationListUpdate("conversation",!0),this.client.emitSyncDataFinished({dataType:"conversation",status:"failed",error:Yg(t)}),i}}async tryDirectFallback(e){if("unsupported"===(t=this.capabilityState).status||"unconfigured"===t.status){const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}var t;const r=Boolean(this.client.getServerUrlsConfig()?.syncWsUrl),s=this.client.isSessionListDnsProbeAvailable();if(!r&&!s){this.capabilityState=Zg("unconfigured","session-list sync websocket is unavailable");const t=await this.buildFallbackSessionList(e);return e.replaceSessionList(t),t}return null}createRetrySession(){return new hg}async buildFallbackSessionList(e){return await(async(e,t)=>await lg(e,t))(e.loadConversationSummaries(),this.client)}}const ey=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),ty=async e=>{if("string"==typeof e||ey(e)||ArrayBuffer.isView(e))return(e=>"string"==typeof e?(new TextEncoder).encode(e):ey(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 Hr("sync websocket frame payload type is invalid",Tr,{details:{stage:"response_decode",payloadType:typeof e}})},ry=e=>{const t=Math.max(e-1,0),r=1e3*Math.pow(2,t);return Math.min(r,5e3)},sy=async e=>{await new Promise(t=>{setTimeout(t,e)})},ny=e=>e instanceof Error?e:new Error(String(e));class iy{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 Hr("sync websocket session is cancelled",_r,{details:{stage:"cancelled",requestId:e.requestId}});if(this.pending.has(e.requestId))throw new Hr("sync websocket requestId is duplicated",it,{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,ny(r))}return await t}cancel(e="sync-websocket-cancelled"){this.cancelled=!0;const t=new Hr("sync websocket cancelled",_r,{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!==ji){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&&Si("sync websocket retry started",this.buildLogContext({reason:e?.message}));try{return void(await this.openSocket())}catch(t){if(e=ny(t),this.cancelled||0===this.pending.size)throw e;if(this.attempt>=3)throw Si("sync websocket retry exhausted",this.buildLogContext({reason:e.message})),e;const r=ry(this.attempt);Si("sync websocket retry scheduled",this.buildLogContext({delayMs:r,reason:e.message})),await sy(r)}}throw new Wr("sync websocket retry exhausted",{code:Cr,details:{stage:"socket_connect",reason:e?.message??"unknown"}})}async openSocket(){const e=await this.getUrls();if(0===e.length)throw new Wr("sync websocket urls are unavailable",{code:Cr,details:{stage:"socket_connect"}});const t=e[this.urlIndex%e.length];if(this.urlIndex+=1,!t)throw new Wr("sync websocket url is invalid",{code:Cr,details:{stage:"socket_connect"}});this.activeUrl=t,this.state="connecting",Si("sync websocket connect started",this.buildLogContext());const r=Vi(),s=this.socketAdapter??Hd({webSocketCtor:r.WebSocket});if(!s)throw this.state="idle",this.buildConnectionError("sync websocket adapter is unavailable","socket_connect");let n=null;try{const e=await Promise.race([s.connect({url:t}),new Promise((e,t)=>{n=setTimeout(()=>{t(this.buildConnectionError("sync websocket socket connect timeout","socket_connect"))},5e3)})]);n&&clearTimeout(n),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(),Si("sync websocket connected",this.buildLogContext())}catch(i){if(n&&clearTimeout(n),this.state="idle",this.closeSocket(4e3,"sync-websocket-connect-failed"),i instanceof Wr)throw i;throw this.buildConnectionError("sync websocket socket create failed","socket_connect",{cause:i instanceof Error?i.message:String(i)})}}async handleMessage(e){try{this.resetIdleTimer();const t=await ty(e);if(!(await this.routeFrame(t)))return}catch(t){const e=ny(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(ny(s)),this.closeIfComplete()}return!0}t.requestId||1!==t.type||r||(r={pending:n,frame:t.frame})}catch(s){t.push(ny(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 Hr("sync websocket frame decode failed",Tr,{details:{stage:"response_decode",cause:t[0]?.message}});return Si("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?(Si("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(ny(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===ji)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)}))}),Si("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||(Si("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>=zi||(this.state="closing",r.close(e,t))}buildConnectionError(e,t,r={}){return new Wr(e,{code:Cr,details:{stage:t,url:this.activeUrl,...r}})}buildLogContext(e={}){return{attempt:this.attempt,maxAttempts:3,url:zr(this.activeUrl),pendingCount:this.pending.size,dataTypes:[...new Set([...this.pending.values()].map(e=>e.dataType))],...e}}}const oy=(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 ay(e){const t=e.entry?.code??fr,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 ts(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 cy={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"}},dy=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase(),uy=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}};class ly{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=t?.requestAdapter,this.includeRequestId=t?.includeRequestId??!1,this.defaultHeaders={Accept:"application/json",...t?.headers}}sanitizeUrl(e){try{const t=new URL(e),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 Zr("Invalid request parameters",{code:ot,details:{...n,canonicalCode:ot}});if(401===e){const e=[r,s].some(e=>"string"==typeof e&&/token[ _-]?(?:has[ _-]?)?expired/i.test(e)),t=e?lt:dt;return new Jr(e?"Authentication token expired":"Authentication failed",{code:t,details:{...n,reasonKey:e?"token_expired":"unauthorized",canonicalCode:t}})}return 403===e?new Jr("Access forbidden",{code:ut,details:{...n,canonicalCode:ut}}):429===e?new ts("REST rate limit exceeded",{code:Fr,details:{...n,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:Fr}}):e>=500?new ts("REST business error: request failed",{code:fr,details:{...n,retryable:!0,reasonKey:"server_unknown_error",canonicalCode:fr}}):void 0}async request(e,t={}){const r=`${this.baseUrl}${e}`,s=t.method??"GET",n=Date.now(),i=this.sanitizeUrl(r);Ci("REST request",{method:s,url:i,operation:t.operation});const o=t.operation?(e=>{const t=cy[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_${dy(e)}`,operationType:r}})(t.operation):void 0,a=o?nm(o):void 0,c=a?.startRequest({requestName:o?.operationName,method:s,url:r});let d=0;const u={...this.defaultHeaders,...t.headers};this.includeRequestId&&(u[Ml]=Al());const l={method:s,headers:u};if(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"),l.body=t.body):(e||(u["Content-Type"]="application/json"),l.body=JSON.stringify(t.body))}else if("GET"===s)for(const p of Object.keys(u))"content-type"===p.toLowerCase()&&delete u[p];try{if(this.requestAdapter){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)&&(Si("REST response error",{method:s,url:i,status:e.status,duration:l}),this.handleErrorPayload(e.status,"",o,{operation:t.operation,url:r,method:s})),Ci("REST response",{method:s,url:i,status:e.status,duration:l});const h=uy(o);return c?.finish({code:e.status,success:!0,resultCount:h}),a?.finish({code:0,success:!0,resultCount:h}),o}const e=new AbortController,o=setTimeout(()=>e.abort(),t.timeout??this.timeout),h=await fetch(r,{...l,signal:e.signal});d=h.status,clearTimeout(o);const p=Date.now()-n;h.ok||(Si("REST response error",{method:s,url:i,status:h.status,duration:p}),await this.handleErrorResponse(h,{operation:t.operation,url:r,method:s})),Ci("REST response",{method:s,url:i,status:h.status,duration:p});const m=h.headers.get("content-type");if(m?.includes("application/json")){const e=await h.json(),t=uy(e);return c?.finish({code:h.status,success:!0,resultCount:t}),a?.finish({code:0,success:!0,resultCount:t}),e}const f=await h.text();return c?.finish({code:h.status,success:!0}),a?.finish({code:0,success:!0}),f}catch(h){const e=0!==d?d:h instanceof Hr?h.code:-1,n=h instanceof Error?h.message:String(h);if(c?.finish({code:e,success:!1,description:n}),a?.finish({code:e,success:!1,description:n}),h instanceof Hr)throw h;if(h instanceof Error&&"AbortError"===h.name)throw Si("REST request timeout",{method:s,url:i,timeout:t.timeout??this.timeout}),new es(`Request timeout: ${r}`,{code:pr,details:{url:r,method:s,timeout:t.timeout??this.timeout}});throw Si("REST request failed",{method:s,url:i}),new es(`Request failed: ${r}`,{code:hr,details:{url:r,method:s}})}}async handleErrorResponse(e,t){let r;try{r=await e.json()}catch{r=await e.text()}this.handleErrorPayload(e.status,e.statusText,r,t)}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=function(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: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(oy(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}}(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 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);if(s.operation&&a)throw ay({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 ay({apiName:s.operation,serverCode:d,serverMessage:u,httpStatus:e,mapped:!1,reasonKey:c});throw new es(`HTTP ${e}: ${t}`,{code:mr,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 hy=async(e,t,r)=>{const{orgName:s,appName:n}=Qn(e.appKey),i=`/${s}/${n}/user/${encodeURIComponent(e.userId)}/roster/metadata/version`,o=new ly(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(Bl(e))return Bl(e.data)?s(e.data):s(e);throw new Zr("Invalid contact metadata response",{code:it,details:{payload:e}})})(await o.get(i),t)}catch(a){if(a instanceof Zr)throw a;const e=a instanceof Hr&&a.details?a.details:{};throw new es("Contact metadata request failed",{code:wr,details:{stage:"metadata",cause:a instanceof Error?a.message:String(a),httpStatus:"number"==typeof e.httpStatus?e.httpStatus:void 0,sourceCode:a instanceof Hr?a.code:void 0}})}};var py,fy,gy;(fy=py||(py={})).assertEqual=e=>{},fy.assertIs=function(e){},fy.assertNever=function(e){throw new Error},fy.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},fy.getValidEnumValues=e=>{const t=fy.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(const s of t)r[s]=e[s];return fy.objectValues(r)},fy.objectValues=e=>fy.objectKeys(e).map(function(t){return e[t]}),fy.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},fy.find=(e,t)=>{for(const r of e)if(t(r))return r},fy.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,fy.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},fy.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(gy||(gy={})).mergeShapes=(e,t)=>({...e,...t});const yy=py.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vy=e=>{switch(typeof e){case"undefined":return yy.undefined;case"string":return yy.string;case"number":return Number.isNaN(e)?yy.nan:yy.number;case"boolean":return yy.boolean;case"function":return yy.function;case"bigint":return yy.bigint;case"symbol":return yy.symbol;case"object":return Array.isArray(e)?yy.array:null===e?yy.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?yy.promise:"undefined"!=typeof Map&&e instanceof Map?yy.map:"undefined"!=typeof Set&&e instanceof Set?yy.set:"undefined"!=typeof Date&&e instanceof Date?yy.date:yy.object;default:return yy.unknown}},by=py.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 Iy 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 Iy))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,py.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()}}Iy.create=e=>new Iy(e);const wy=(e,t)=>{let r;switch(e.code){case by.invalid_type:r=e.received===yy.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case by.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,py.jsonStringifyReplacer)}`;break;case by.unrecognized_keys:r=`Unrecognized key(s) in object: ${py.joinValues(e.keys,", ")}`;break;case by.invalid_union:r="Invalid input";break;case by.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${py.joinValues(e.options)}`;break;case by.invalid_enum_value:r=`Invalid enum value. Expected ${py.joinValues(e.options)}, received '${e.received}'`;break;case by.invalid_arguments:r="Invalid function arguments";break;case by.invalid_return_type:r="Invalid function return type";break;case by.invalid_date:r="Invalid date";break;case by.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}"`:py.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case by.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 by.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 by.custom:r="Invalid input";break;case by.invalid_intersection_types:r="Intersection results could not be merged";break;case by.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case by.not_finite:r="Number must be finite";break;default:r=t.defaultError,py.assertNever(e)}return{message:r}};let Cy=wy;function Sy(e,t){const r=Cy,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===wy?void 0:wy].filter(e=>!!e)});e.common.issues.push(s)}class Ty{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 _y;"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 Ty.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 _y;if("aborted"===n.status)return _y;"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 _y=Object.freeze({status:"aborted"}),Ry=e=>({status:"dirty",value:e}),Ay=e=>({status:"valid",value:e}),My=e=>"aborted"===e.status,Ey=e=>"dirty"===e.status,Uy=e=>"valid"===e.status,Ny=e=>"undefined"!=typeof Promise&&e instanceof Promise;var ky,Oy;(Oy=ky||(ky={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},Oy.toString=e=>"string"==typeof e?e:e?.message;class xy{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 Ly=(e,t)=>{if(Uy(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 Iy(e.common.issues);return this._error=t,this._error}}};function Py(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 Dy{get description(){return this._def.description}_getType(e){return vy(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:vy(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ty,ctx:{common:e.parent.common,data:e.data,parsedType:vy(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Ny(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:vy(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Ly(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:vy(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return Uy(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=>Uy(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:vy(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await(Ny(s)?s:Promise.resolve(s));return Ly(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:by.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 Pv({schema:this,typeName:Vv.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 Dv.create(this,this._def)}nullable(){return qv.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Iv.create(this)}promise(){return Lv.create(this,this._def)}or(e){return Sv.create([this,e],this._def)}and(e){return _v.create(this,e,this._def)}transform(e){return new Pv({...Py(this._def),schema:this,typeName:Vv.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Bv({...Py(this._def),innerType:this,defaultValue:t,typeName:Vv.ZodDefault})}brand(){return new Gv({typeName:Vv.ZodBranded,type:this,...Py(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new $v({...Py(this._def),innerType:this,catchValue:t,typeName:Vv.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return jv.create(this,e)}readonly(){return zv.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const qy=/^c[^\s-]{8,}$/i,By=/^[0-9a-z]+$/,$y=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fy=/^[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,Gy=/^[a-z0-9_-]{21}$/i,jy=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zy=/^[-+]?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)?)??$/,Ky=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Hy;const Vy=/^(?:(?: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])$/,Wy=/^(?:(?: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])$/,Jy=/^(([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]))$/,Zy=/^(([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])$/,Qy=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Yy=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Xy="((\\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])))",ev=new RegExp(`^${Xy}$`);function tv(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 rv(e){return new RegExp(`^${tv(e)}$`)}function sv(e){let t=`${Xy}T${tv(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 nv(e,t){return!("v4"!==t&&t||!Vy.test(e))||!("v6"!==t&&t||!Jy.test(e))}function iv(e,t){if(!jy.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 ov(e,t){return!("v4"!==t&&t||!Wy.test(e))||!("v6"!==t&&t||!Zy.test(e))}class av extends Dy{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==yy.string){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.string,received:t.parsedType}),_y}const t=new Ty;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.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),Sy(r,{code:by.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?Sy(r,{code:by.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&Sy(r,{code:by.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)Ky.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"email",code:by.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)Hy||(Hy=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Hy.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"emoji",code:by.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)Fy.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"uuid",code:by.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)Gy.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"nanoid",code:by.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)qy.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"cuid",code:by.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)By.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"cuid2",code:by.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)$y.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"ulid",code:by.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),Sy(r,{validation:"url",code:by.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),Sy(r,{validation:"regex",code:by.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),Sy(r,{code:by.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),Sy(r,{code:by.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),Sy(r,{code:by.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty());else if("datetime"===s.kind){sv(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.invalid_string,validation:"datetime",message:s.message}),t.dirty())}else if("date"===s.kind){ev.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.invalid_string,validation:"date",message:s.message}),t.dirty())}else if("time"===s.kind){rv(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.invalid_string,validation:"time",message:s.message}),t.dirty())}else"duration"===s.kind?zy.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"duration",code:by.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?nv(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"ip",code:by.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?iv(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"jwt",code:by.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?ov(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"cidr",code:by.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?Qy.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"base64",code:by.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?Yy.test(e.data)||(r=this._getOrReturnCtx(e,r),Sy(r,{validation:"base64url",code:by.invalid_string,message:s.message}),t.dirty()):py.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:by.invalid_string,...ky.errToObj(r)})}_addCheck(e){return new av({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ky.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ky.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ky.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ky.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ky.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ky.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ky.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ky.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ky.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ky.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ky.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ky.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ky.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,...ky.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,...ky.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ky.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ky.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...ky.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ky.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ky.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ky.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ky.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ky.errToObj(t)})}nonempty(e){return this.min(1,ky.errToObj(e))}trim(){return new av({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new av({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new av({...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 cv(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}av.create=e=>new av({checks:[],typeName:Vv.ZodString,coerce:e?.coerce??!1,...Py(e)});class dv extends Dy{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)!==yy.number){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.number,received:t.parsedType}),_y}let t;const r=new Ty;for(const s of this._def.checks)if("int"===s.kind)py.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Sy(t,{code:by.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),Sy(t,{code:by.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),Sy(t,{code:by.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==cv(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),Sy(t,{code:by.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Sy(t,{code:by.not_finite,message:s.message}),r.dirty()):py.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ky.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ky.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ky.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ky.toString(t))}setLimit(e,t,r,s){return new dv({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:ky.toString(s)}]})}_addCheck(e){return new dv({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ky.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ky.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ky.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ky.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ky.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ky.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ky.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ky.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ky.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&&py.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)}}dv.create=e=>new dv({checks:[],typeName:Vv.ZodNumber,coerce:e?.coerce||!1,...Py(e)});class uv extends Dy{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)!==yy.bigint)return this._getInvalidInput(e);let t;const r=new Ty;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),Sy(t,{code:by.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),Sy(t,{code:by.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),Sy(t,{code:by.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):py.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.bigint,received:t.parsedType}),_y}gte(e,t){return this.setLimit("min",e,!0,ky.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ky.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ky.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ky.toString(t))}setLimit(e,t,r,s){return new uv({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:ky.toString(s)}]})}_addCheck(e){return new uv({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ky.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ky.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ky.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ky.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ky.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}}uv.create=e=>new uv({checks:[],typeName:Vv.ZodBigInt,coerce:e?.coerce??!1,...Py(e)});class lv extends Dy{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==yy.boolean){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.boolean,received:t.parsedType}),_y}return Ay(e.data)}}lv.create=e=>new lv({typeName:Vv.ZodBoolean,coerce:e?.coerce||!1,...Py(e)});class hv extends Dy{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==yy.date){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.date,received:t.parsedType}),_y}if(Number.isNaN(e.data.getTime())){return Sy(this._getOrReturnCtx(e),{code:by.invalid_date}),_y}const t=new Ty;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),Sy(r,{code:by.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),Sy(r,{code:by.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):py.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new hv({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:ky.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ky.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}}hv.create=e=>new hv({checks:[],coerce:e?.coerce||!1,typeName:Vv.ZodDate,...Py(e)});class pv extends Dy{_parse(e){if(this._getType(e)!==yy.symbol){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.symbol,received:t.parsedType}),_y}return Ay(e.data)}}pv.create=e=>new pv({typeName:Vv.ZodSymbol,...Py(e)});class mv extends Dy{_parse(e){if(this._getType(e)!==yy.undefined){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.undefined,received:t.parsedType}),_y}return Ay(e.data)}}mv.create=e=>new mv({typeName:Vv.ZodUndefined,...Py(e)});class fv extends Dy{_parse(e){if(this._getType(e)!==yy.null){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.null,received:t.parsedType}),_y}return Ay(e.data)}}fv.create=e=>new fv({typeName:Vv.ZodNull,...Py(e)});class gv extends Dy{constructor(){super(...arguments),this._any=!0}_parse(e){return Ay(e.data)}}gv.create=e=>new gv({typeName:Vv.ZodAny,...Py(e)});class yv extends Dy{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ay(e.data)}}yv.create=e=>new yv({typeName:Vv.ZodUnknown,...Py(e)});class vv extends Dy{_parse(e){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.never,received:t.parsedType}),_y}}vv.create=e=>new vv({typeName:Vv.ZodNever,...Py(e)});class bv extends Dy{_parse(e){if(this._getType(e)!==yy.undefined){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.void,received:t.parsedType}),_y}return Ay(e.data)}}bv.create=e=>new bv({typeName:Vv.ZodVoid,...Py(e)});class Iv extends Dy{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==yy.array)return Sy(t,{code:by.invalid_type,expected:yy.array,received:t.parsedType}),_y;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(Sy(t,{code:e?by.too_big:by.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&&(Sy(t,{code:by.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&&(Sy(t,{code:by.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 xy(t,e,t.path,r)))).then(e=>Ty.mergeArray(r,e));const n=[...t.data].map((e,r)=>s.type._parseSync(new xy(t,e,t.path,r)));return Ty.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new Iv({...this._def,minLength:{value:e,message:ky.toString(t)}})}max(e,t){return new Iv({...this._def,maxLength:{value:e,message:ky.toString(t)}})}length(e,t){return new Iv({...this._def,exactLength:{value:e,message:ky.toString(t)}})}nonempty(e){return this.min(1,e)}}function wv(e){if(e instanceof Cv){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=Dv.create(wv(s))}return new Cv({...e._def,shape:()=>t})}return e instanceof Iv?new Iv({...e._def,type:wv(e.element)}):e instanceof Dv?Dv.create(wv(e.unwrap())):e instanceof qv?qv.create(wv(e.unwrap())):e instanceof Rv?Rv.create(e.items.map(e=>wv(e))):e}Iv.create=(e,t)=>new Iv({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Vv.ZodArray,...Py(t)});class Cv extends Dy{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=py.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==yy.object){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.object,received:t.parsedType}),_y}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof vv&&"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 xy(r,t,r.path,a)),alwaysSet:a in r.data})}if(this._def.catchall instanceof vv){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&&(Sy(r,{code:by.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 xy(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=>Ty.mergeObjectSync(t,e)):Ty.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return ky.errToObj,new Cv({...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:ky.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new Cv({...this._def,unknownKeys:"strip"})}passthrough(){return new Cv({...this._def,unknownKeys:"passthrough"})}extend(e){return new Cv({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Cv({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Vv.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Cv({...this._def,catchall:e})}pick(e){const t={};for(const r of py.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new Cv({...this._def,shape:()=>t})}omit(e){const t={};for(const r of py.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new Cv({...this._def,shape:()=>t})}deepPartial(){return wv(this)}partial(e){const t={};for(const r of py.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new Cv({...this._def,shape:()=>t})}required(e){const t={};for(const r of py.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Dv;)e=e._def.innerType;t[r]=e}return new Cv({...this._def,shape:()=>t})}keyof(){return kv(py.objectKeys(this.shape))}}Cv.create=(e,t)=>new Cv({shape:()=>e,unknownKeys:"strip",catchall:vv.create(),typeName:Vv.ZodObject,...Py(t)}),Cv.strictCreate=(e,t)=>new Cv({shape:()=>e,unknownKeys:"strict",catchall:vv.create(),typeName:Vv.ZodObject,...Py(t)}),Cv.lazycreate=(e,t)=>new Cv({shape:e,unknownKeys:"strip",catchall:vv.create(),typeName:Vv.ZodObject,...Py(t)});class Sv extends Dy{_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 Iy(e.ctx.common.issues));return Sy(t,{code:by.invalid_union,unionErrors:r}),_y});{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 Iy(e));return Sy(t,{code:by.invalid_union,unionErrors:n}),_y}}get options(){return this._def.options}}function Tv(e,t){const r=vy(e),s=vy(t);if(e===t)return{valid:!0,data:e};if(r===yy.object&&s===yy.object){const r=py.objectKeys(t),s=py.objectKeys(e).filter(e=>-1!==r.indexOf(e)),n={...e,...t};for(const i of s){const r=Tv(e[i],t[i]);if(!r.valid)return{valid:!1};n[i]=r.data}return{valid:!0,data:n}}if(r===yy.array&&s===yy.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const n=Tv(e[s],t[s]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===yy.date&&s===yy.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Sv.create=(e,t)=>new Sv({options:e,typeName:Vv.ZodUnion,...Py(t)});class _v extends Dy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(My(e)||My(s))return _y;const n=Tv(e.value,s.value);return n.valid?((Ey(e)||Ey(s))&&t.dirty(),{status:t.value,value:n.data}):(Sy(r,{code:by.invalid_intersection_types}),_y)};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}))}}_v.create=(e,t,r)=>new _v({left:e,right:t,typeName:Vv.ZodIntersection,...Py(r)});class Rv extends Dy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==yy.array)return Sy(r,{code:by.invalid_type,expected:yy.array,received:r.parsedType}),_y;if(r.data.length<this._def.items.length)return Sy(r,{code:by.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_y;!this._def.rest&&r.data.length>this._def.items.length&&(Sy(r,{code:by.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 xy(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>Ty.mergeArray(t,e)):Ty.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new Rv({...this._def,rest:e})}}Rv.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Rv({items:e,typeName:Vv.ZodTuple,rest:null,...Py(t)})};class Av extends Dy{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!==yy.object)return Sy(r,{code:by.invalid_type,expected:yy.object,received:r.parsedType}),_y;const s=[],n=this._def.keyType,i=this._def.valueType;for(const o in r.data)s.push({key:n._parse(new xy(r,o,r.path,o)),value:i._parse(new xy(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?Ty.mergeObjectAsync(t,s):Ty.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new Av(t instanceof Dy?{keyType:e,valueType:t,typeName:Vv.ZodRecord,...Py(r)}:{keyType:av.create(),valueType:e,typeName:Vv.ZodRecord,...Py(t)})}}class Mv extends Dy{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!==yy.map)return Sy(r,{code:by.invalid_type,expected:yy.map,received:r.parsedType}),_y;const s=this._def.keyType,n=this._def.valueType,i=[...r.data.entries()].map(([e,t],i)=>({key:s._parse(new xy(r,e,r.path,[i,"key"])),value:n._parse(new xy(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 _y;"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 _y;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}Mv.create=(e,t,r)=>new Mv({valueType:t,keyType:e,typeName:Vv.ZodMap,...Py(r)});class Ev extends Dy{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==yy.set)return Sy(r,{code:by.invalid_type,expected:yy.set,received:r.parsedType}),_y;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(Sy(r,{code:by.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&&(Sy(r,{code:by.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 _y;"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 xy(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>i(e)):i(o)}min(e,t){return new Ev({...this._def,minSize:{value:e,message:ky.toString(t)}})}max(e,t){return new Ev({...this._def,maxSize:{value:e,message:ky.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ev.create=(e,t)=>new Ev({valueType:e,minSize:null,maxSize:null,typeName:Vv.ZodSet,...Py(t)});class Uv extends Dy{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})}}Uv.create=(e,t)=>new Uv({getter:e,typeName:Vv.ZodLazy,...Py(t)});class Nv extends Dy{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Sy(t,{received:t.data,code:by.invalid_literal,expected:this._def.value}),_y}return{status:"valid",value:e.data}}get value(){return this._def.value}}function kv(e,t){return new Ov({values:e,typeName:Vv.ZodEnum,...Py(t)})}Nv.create=(e,t)=>new Nv({value:e,typeName:Vv.ZodLiteral,...Py(t)});class Ov extends Dy{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return Sy(t,{expected:py.joinValues(r),received:t.parsedType,code:by.invalid_type}),_y}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 Sy(t,{received:t.data,code:by.invalid_enum_value,options:r}),_y}return Ay(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 Ov.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ov.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Ov.create=kv;class xv extends Dy{_parse(e){const t=py.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==yy.string&&r.parsedType!==yy.number){const e=py.objectValues(t);return Sy(r,{expected:py.joinValues(e),received:r.parsedType,code:by.invalid_type}),_y}if(this._cache||(this._cache=new Set(py.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=py.objectValues(t);return Sy(r,{received:r.data,code:by.invalid_enum_value,options:e}),_y}return Ay(e.data)}get enum(){return this._def.values}}xv.create=(e,t)=>new xv({values:e,typeName:Vv.ZodNativeEnum,...Py(t)});class Lv extends Dy{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==yy.promise&&!1===t.common.async)return Sy(t,{code:by.invalid_type,expected:yy.promise,received:t.parsedType}),_y;const r=t.parsedType===yy.promise?t.data:Promise.resolve(t.data);return Ay(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Lv.create=(e,t)=>new Lv({type:e,typeName:Vv.ZodPromise,...Py(t)});class Pv extends Dy{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Vv.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=>{Sy(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 _y;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?_y:"dirty"===s.status||"dirty"===t.value?Ry(s.value):s});{if("aborted"===t.value)return _y;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?_y:"dirty"===s.status||"dirty"===t.value?Ry(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?_y:("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?_y:("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(!Uy(e))return _y;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=>Uy(e)?Promise.resolve(s.transform(e.value,n)).then(e=>({status:t.value,value:e})):_y)}py.assertNever(s)}}Pv.create=(e,t,r)=>new Pv({schema:e,typeName:Vv.ZodEffects,effect:t,...Py(r)}),Pv.createWithPreprocess=(e,t,r)=>new Pv({schema:t,effect:{type:"preprocess",transform:e},typeName:Vv.ZodEffects,...Py(r)});class Dv extends Dy{_parse(e){return this._getType(e)===yy.undefined?Ay(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Dv.create=(e,t)=>new Dv({innerType:e,typeName:Vv.ZodOptional,...Py(t)});class qv extends Dy{_parse(e){return this._getType(e)===yy.null?Ay(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}qv.create=(e,t)=>new qv({innerType:e,typeName:Vv.ZodNullable,...Py(t)});class Bv extends Dy{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===yy.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Bv.create=(e,t)=>new Bv({innerType:e,typeName:Vv.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...Py(t)});class $v extends Dy{_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 Ny(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Iy(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new Iy(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}$v.create=(e,t)=>new $v({innerType:e,typeName:Vv.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...Py(t)});class Fv extends Dy{_parse(e){if(this._getType(e)!==yy.nan){const t=this._getOrReturnCtx(e);return Sy(t,{code:by.invalid_type,expected:yy.nan,received:t.parsedType}),_y}return{status:"valid",value:e.data}}}Fv.create=e=>new Fv({typeName:Vv.ZodNaN,...Py(e)});class Gv extends Dy{_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 jv extends Dy{_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?_y:"dirty"===e.status?(t.dirty(),Ry(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?_y:"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 jv({in:e,out:t,typeName:Vv.ZodPipeline})}}class zv extends Dy{_parse(e){const t=this._def.innerType._parse(e),r=e=>(Uy(e)&&(e.value=Object.freeze(e.value)),e);return Ny(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function Kv(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Hv(e,t={},r){return e?gv.create().superRefine((s,n)=>{const i=e(s);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Kv(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Kv(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}}):gv.create()}var Vv,Wv;zv.create=(e,t)=>new zv({innerType:e,typeName:Vv.ZodReadonly,...Py(t)}),(Wv=Vv||(Vv={})).ZodString="ZodString",Wv.ZodNumber="ZodNumber",Wv.ZodNaN="ZodNaN",Wv.ZodBigInt="ZodBigInt",Wv.ZodBoolean="ZodBoolean",Wv.ZodDate="ZodDate",Wv.ZodSymbol="ZodSymbol",Wv.ZodUndefined="ZodUndefined",Wv.ZodNull="ZodNull",Wv.ZodAny="ZodAny",Wv.ZodUnknown="ZodUnknown",Wv.ZodNever="ZodNever",Wv.ZodVoid="ZodVoid",Wv.ZodArray="ZodArray",Wv.ZodObject="ZodObject",Wv.ZodUnion="ZodUnion",Wv.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Wv.ZodIntersection="ZodIntersection",Wv.ZodTuple="ZodTuple",Wv.ZodRecord="ZodRecord",Wv.ZodMap="ZodMap",Wv.ZodSet="ZodSet",Wv.ZodFunction="ZodFunction",Wv.ZodLazy="ZodLazy",Wv.ZodLiteral="ZodLiteral",Wv.ZodEnum="ZodEnum",Wv.ZodEffects="ZodEffects",Wv.ZodNativeEnum="ZodNativeEnum",Wv.ZodOptional="ZodOptional",Wv.ZodNullable="ZodNullable",Wv.ZodDefault="ZodDefault",Wv.ZodCatch="ZodCatch",Wv.ZodPromise="ZodPromise",Wv.ZodBranded="ZodBranded",Wv.ZodPipeline="ZodPipeline",Wv.ZodReadonly="ZodReadonly";const Jv=av.create,Zv=dv.create,Qv=lv.create;gv.create;const Yv=yv.create,Xv=vv.create,eb=Iv.create,tb=Cv.create,rb=Sv.create;_v.create,Rv.create;const sb=Av.create,nb=Ov.create;Lv.create,Dv.create,qv.create;class ib{static validate(e,t){try{return{success:!0,data:e.parse(t)}}catch(r){if(r instanceof Iy){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);return{success:!1,error:new Zr(t,{code:s?nt:it,details:{fields:e}})}}return{success:!1,error:new Zr("Unknown validation error",{code:ot,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 Zr("Unknown validation error",{code:ot,details:{fields:[]}})}static safeParse(e,t){return this.validate(e,t)}}const ob=e=>Jv().regex(/^https?:\/\/\S+$/i,e),ab=e=>Jv().regex(/^wss?:\/\/\S+$/i,e),cb=tb({appKey:Jv().min(1,"appKey is required").optional(),appId:Jv().min(1,"appId is required").optional(),enableUserInfoSync:Qv().optional(),enableSyncData:eb(nb(["conversation","contact","group"])).optional(),enableDeliveryReceipt:Qv().optional(),deleteConversationOnGroupDestroyed:Qv().optional(),syncConversationListConfig:tb({includeEmpty:Qv().optional()}).strict().optional(),useCustomAttachmentUpload:Qv().optional(),useFixedDeviceId:Qv().optional(),deviceId:Jv().min(1,"deviceId is required").optional(),serviceConfig:tb({dnsConfigUrls:eb(ob("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:tb({restApiUrl:ob("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:ab("serviceConfig.serverUrls.wsUrl must be a valid URL").optional(),syncRestApiUrl:ob("serviceConfig.serverUrls.syncRestApiUrl must be a valid URL").optional(),syncWsUrl:ab("serviceConfig.serverUrls.syncWsUrl must be a valid URL").optional()}).optional()}).optional(),useReplacedMessageContents:Qv().optional(),customDeviceName:Jv().min(1,"customDeviceName is required").optional(),customOSPlatform:Zv().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:Jv().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:Jv().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:eb(Yv()).optional(),platformAdapterOptions:tb({prefer:nb(["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:Hv(e=>"object"==typeof e&&null!==e).optional(),overrides:Hv(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:by.custom,path:["appKey"],message:"appKey or appId is required"}):r>1&&t.addIssue({code:by.custom,path:["appId"],message:"appKey and appId cannot be used together"}),"enableMd5Check"in e&&t.addIssue({code:by.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:by.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:by.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:by.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:by.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:by.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:by.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:by.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),n&&(void 0!==e.appId&&t.addIssue({code:by.custom,path:["serviceConfig","serverUrls"],message:"serviceConfig.serverUrls cannot be used when initialized with appId"}),n?.restApiUrl||t.addIssue({code:by.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),n?.wsUrl||t.addIssue({code:by.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))}),db=tb({userId:Jv().min(1,"userId is required"),token:Jv().min(1,"token is required")}),ub=Jv().trim().min(1,"token is required"),lb=tb({channelName:Jv().trim().min(1,"channelName is required").optional()}).optional(),hb=eb(Zv({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))),pb=tb({protocol:Jv(),domain:Jv().optional(),ip:Jv().optional(),port:rb([Jv(),Zv()]).optional()}).passthrough(),mb=tb({app_key:Jv().optional(),rest:tb({hosts:eb(pb).nonempty()}),"msync-wx":tb({hosts:eb(pb).nonempty()}),"sync-ws":tb({hosts:eb(pb).nonempty()}).optional(),enableReportLogs:nb(["true","false"]).optional(),reportInterval:Zv().positive().finite().optional(),enableDataReport:nb(["true","false"]).optional(),enableMd5Check:nb(["true","false"]).optional(),uploadinparts_enable:nb(["true","false"]).optional()}).passthrough(),fb=e=>encodeURIComponent(e).replace(/[!'()~]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g,"+"),gb=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])=>`${fb(e)}=${fb(t)}`).join("&")}})(e),yb="5.1.0",vb=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],bb=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"],Ib=["sync-ws","sync_ws","syncws","roster-ws","contact-sync-ws"];function wb(e){return"object"==typeof e&&null!==e}function Cb(e){return Array.isArray(e)?{hosts:e}:function(e){return wb(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function Sb(e,t,r){for(const s of t){const t=Cb(e[s]);if(t)return{key:s,section:t}}for(const[s,n]of Object.entries(e)){if(!r(s))continue;const e=Cb(n);if(e)return{key:s,section:e}}}function Tb(e){if(!wb(e))return ib.validateOrThrow(mb,e);const t=Cb(e.rest),r=Sb(e,bb,e=>{const t=e.toLowerCase();return t.includes("msync")||t.includes("websocket")||"socket"===t||"im-ws"===t}),s=Sb(e,Ib,e=>{const t=e.toLowerCase();return!t.includes("msync")&&t.includes("sync")&&(t.includes("ws")||t.includes("socket"))}),n={...e,rest:t??e.rest,"msync-wx":r?.section};s?.section?n["sync-ws"]=s.section:"sync-ws"in n&&!Cb(n["sync-ws"])&&delete n["sync-ws"];const i="true"===(o=e.enableReportLogs)||!0===o?"true":"false"===o||!1===o?"false":void 0;var o;i&&(n.enableReportLogs=i);const a=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!==a?n.reportInterval=a:delete n.reportInterval;const c=function(e){if("true"===e||"false"===e)return e}(e.enableDataReport);c?n.enableDataReport=c:delete n.enableDataReport;const d=function(e){if("true"===e||"false"===e)return e}(e.enableMd5Check);d?n.enableMd5Check=d:delete n.enableMd5Check;const u=function(e){if("true"===e||"false"===e)return e}(e.uploadinparts_enable);return u?n.uploadinparts_enable=u:delete n.uploadinparts_enable,r&&"msync-wx"!==r.key&&Si("DNS config websocket section normalized",{sourceKey:r.key}),s&&"sync-ws"!==s.key&&Si("DNS config sync websocket section normalized",{sourceKey:s.key}),ib.validateOrThrow(mb,n)}function _b(e,t){const r=e.domain||e.ip;if(!r)throw new Zr("DNS host missing domain/ip",{code:nt,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 Rb(e,t){return"https"===e?"https":"http"===e?"http":t}function Ab(e,t){const r=e.domain||e.ip;if(!r)throw new Zr("DNS rest host missing domain/ip",{code:nt,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 Mb(e,t){const r=e.filter(e=>e.protocol===t);return r.length>0?r:"http"===t?e.filter(e=>"https"===e.protocol):[]}function Eb(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 Ub(e,t,r){const s=new ly(e,{requestAdapter:r,includeRequestId:!0});let n="/easemob/server.json",i=!0;try{const t=new URL(e),r=""!==t.pathname&&"/"!==t.pathname,s=""!==t.search;(r||s)&&(n="",i=!1)}catch{n="/easemob/server.json",i=!0}if(i){n=`${n}?${(void 0!==t.appId?gb({app_id:t.appId,sdk_version:yb,file_version:"1"}):gb({app_key:t.appKey,_v:String(Date.now())})).toString()}`}return Tb(await s.get(n))}function Nb(e,t){const r=e["sync-ws"];return r&&Array.isArray(r.hosts)?r.hosts.map(e=>function(e,t){const r=e.domain||e.ip;if(!r)throw new Zr("DNS host missing domain/ip",{code:nt,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}`}(e,Rb(e.protocol,t))).filter(e=>"string"==typeof e&&e.length>0):[]}async function kb(e){const t=e.baseUrls&&e.baseUrls.length>0?e.baseUrls:vb;if(0===t.length)throw new Zr("DNS_CONFIG list is empty",{code:nt,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)try{const t=void 0!==e.appId?{appId:e.appId}:{appKey:e.appKey},s=await Ub(o,t,e.requestAdapter),n=void 0!==e.appId?s.app_key:e.appKey;if("string"!=typeof n||0===n.length)throw new Zr("DNS app_key is required for appId initialization",{code:nt,details:{fields:[{path:"dns.app_key",message:"DNS app_key is required for appId initialization",rule:"required"}]}});const i=Eb(Mb(s["msync-wx"].hosts,r));if(0===i.length)throw new Zr("DNS msync-wx hosts resolution failed",{code:it,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const a=i[0];if(!a)throw new Zr("DNS msync-wx hosts resolution failed",{code:it,details:{fields:[{path:"dns.msync-wx.hosts",message:"DNS msync-wx hosts resolution failed",rule:"invalid_format"}]}});const c=Mb(s.rest.hosts,r);if(0===c.length)throw new Zr("DNS rest hosts resolution failed",{code:it,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const d=c[0];if(!d)throw new Zr("DNS rest hosts resolution failed",{code:it,details:{fields:[{path:"dns.rest.hosts",message:"DNS rest hosts resolution failed",rule:"invalid_format"}]}});const u=i.map(e=>_b(e,Rb(e.protocol,r))),l=_b(a,Rb(a.protocol,r)),h=Nb(s,r);return{appKey:n,websocketUrl:l,websocketUrls:u,syncWebsocketUrls:h,baseUrl:o,restBaseUrl:Ab(d,Rb(d.protocol,r)),dnsConfig:s}}catch(i){Si("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 Wr("DNS_CONFIG exhausted",{code:wt,details:n})}const Ob=e=>new Zr(e,{code:it,details:{reason:"invalid_rest_response"}}),xb=e=>{if(!Bl(e))throw Ob("Invalid REST response");return Bl(e.data)?e.data:e},Lb=(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}}},Pb=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t)return t}},Db=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}`},qb=async(e,t)=>{const r=await e.get((e=>`${Db(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=xb(e),r=Lb(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===r)throw Ob("Invalid token expires response");return r})(r)},Bb=async(e,t,r)=>{const s=await e.get(((e,t)=>{const r=gb({channelName:t?.channelName??"*"});return`${Db(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${r.toString()}`})(t,r),{operation:"getRtcTokenInfo"});return(e=>{const t=xb(e);return{appId:Pb(t,["app_id","appId"])??"",rtcToken:Pb(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:Pb(t,["channel_name","channelName"])??"",rtcUid:Lb(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:Lb(t,["expires_in","expire","expireAt"])??0}})(s)},$b=async(e,t,r)=>{const s=await e.post((e=>`${Db(e)}/rtc_mapper/batch/get`)(t),{data:r},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=xb(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)},Fb=async(e,t)=>{const r=await e.get((e=>`${Db(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const r=Bl(e)&&Array.isArray(e.data)?e.data:[],s=[];for(const n of r){if(!Bl(n))continue;const e=Pb(n,["res","resource","clientResource"]);e&&e!==t.clientResource&&s.push(`${t.userId}/${e}`)}return s})(r,t)},Gb=(...e)=>{const t={},r={};for(const s of e)Object.assign(t,s.common),Object.assign(r,s.apis);return{common:t,apis:r}},jb={common:{validation:{range:"100-110",errors:{MISSING_REQUIRED:{code:110},INVALID_FORMAT:{code:110},UNKNOWN:{code:110}}},auth:{range:"108,200-215",errors:{ALREADY_LOGIN:{code:200},NOT_LOGIN:{code:201},UNAUTHORIZED:{code:202},FORBIDDEN:{code:210},TOKEN_EXPIRED:{code:108},BIND_ANOTHER_DEVICE:{code:213},LOGIN_TOO_MANY_DEVICES:{code:214},USER_MUTED:{code:215}}},connection:{range:"1,100,202,300-304",errors:{TIMEOUT:{code:301},WEBSOCKET_ERROR:{code:300},NOT_CREATED:{code:1},CLOSED_BEFORE_READY:{code:300},CANCELLED:{code:1},PROVISION_TIMEOUT:{code:301},PROVISION_REJECTED:{code:202},PROVISION_CLOSED:{code:300},DNSLIST_FAILED:{code:304},SERVER_BUSY:{code:302}}},storage:{range:"3",errors:{OPERATION_FAILED:{code:3}}},message:{range:"1,300-511",errors:{NOT_CONNECTED:{code:300},ACK_TIMEOUT:{code:301},SEND_FAILED:{code:303},SENDER_DESTROYED:{code:1},ENCODE_FAILED:{code:500},DECODE_FAILED:{code:500},ACK_MISSING:{code:301}}},transport:{range:"2,301,303",errors:{NETWORK_ERROR:{code:2},TIMEOUT:{code:301},HTTP_ERROR:{code:303},BUSINESS_UNKNOWN:{code:303}}},upload:{range:"1,100,110,301,402,405",errors:{REQUIRED_FIELD_MISSING:{code:110},INVALID_APPKEY:{code:100},SIZE_EXCEEDED:{code:405},REQUEST_FAILED:{code:402},TIMEOUT:{code:301},ABORTED:{code:1}}},unknown:{range:"1,4",errors:{UNKNOWN:{code:1},SERVICE_LIMIT_EXCEEDED:{code:4}}},push:{range:"1500,1501,1502",errors:{TOKEN_UPLOAD_FAILED:{code:1500},SILENT_MODE_OPERATION_FAILED:{code:1501},PUSH_LANGUAGE_OPERATION_FAILED:{code:1502}}},chatroom:{range:"700-707",errors:{CHATROOM_INVALID_ID:{code:700},CHATROOM_NOT_JOINED:{code:702},CHATROOM_PERMISSION_DENIED:{code:703},CHATROOM_MEMBERS_FULL:{code:704},CHATROOM_NOT_EXIST:{code:705},CHATROOM_OWNER_NOT_ALLOW_LEAVE:{code:706},CHATROOM_USER_IN_BLOCKLIST:{code:707}}}},apis:{}},zb=e=>({userId:e}),Kb=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Hb=e=>e,Vb=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,Kb(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,Hb(t))}for(const o of r)s.has(o)||s.set(o,zb(o));return s};class Wb{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=>{Si("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 Jb{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(Si("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)}}const Zb=0,Qb=1,Yb=2,Xb=3,eI=4,tI=5,rI=0,sI=0,nI=1,iI=1001,oI=1002,aI=1003,cI=1004,dI=1005,uI=1101,lI=Gb(jb,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),hI=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.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=ul(this.config.platformAdapterOptions)),this.managerRegistry=new Map,this.managerCapabilities=new Map,this.eventHub=new ng,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 Jb({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:3,maxRetries:1,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new Wb({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)},[d]:e=>{this.updateState(e.state)},[N]:e=>{this.handleIncomingConversationMessage(e),this.handleIncomingMessageProfileSync(e)},[k]:e=>{this.handleIncomingConversationStreamMessage(e)},[b]:e=>{this.handleOutgoingConversationMessage(e)},[$]:e=>{this.handleMultiDeviceContactEvent(e)},[F]:e=>{if("CONVERSATION_DELETED"===e.operation)return this.handleMultiDeviceConversationEvent(e)},[V]:e=>this.handleIncomingContactRosterEvent("add",e),[J]:e=>this.handleIncomingContactRosterEvent("add",e),[K]:e=>this.handleIncomingContactRosterEvent("none",e),[W]: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===ne&&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=ib.validateOrThrow(cb,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 Zr("ChatClient already initialized with different config",{code:it,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){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});const i=ib.validateOrThrow(db,n);if(this.state===r||this.state===s){const e=this.currentUserId&&this.currentUserId!==i.userId;throw new Wr(e?"Another user is already logged in":"ChatClient is already connecting or connected",{code:e?Jt:at,details:{stage:"auth",...e?{currentUserId:this.currentUserId,nextUserId:i.userId}:{}}})}const o=++this.loginAttempt;let a=this.config.appKey??null;this.activeAppKey=a,Si("Login started",{userId:i.userId,serviceConnectionMode:this.config.serviceConfig.mode,hasCustomDnsConfigUrls:this.config.serviceConfig.hasCustomDnsConfigUrls});const c=this.platformAdapter??ul(this.config.platformAdapterOptions);var d;this.platformAdapter=c,d={requestAdapter:c.request,onDiagnostic:(e,t)=>{Si(e,t)}},em?.reset(),em=new Xp(d);const u=(e=>em?.startSession(e))({appKey:a??"default#appkey",uid:i.userId,sdkVersion:yb,platform:c.runtime.getPlatform(),deviceId:this.config.deviceId,os:this.config.customOSPlatform,uikitVersion:this.config.uiKitVersion,did:this.config.customDeviceName}),l=c.runtime.getNetworkType?.();l&&l.then(e=>{sm(e)}).catch(()=>{sm("unknown")});const h=nm({operationName:"USER_LOGIN",operationType:"MANUALLOGIN",uid:i.userId});let p,m,f;this.updateState(r),this.logReportEnabled=!1,vi("unknown");let g,y=!1,v=!1,b=!0;if("dns"===this.config.serviceConfig.mode){const e=h?.startRequest({requestName:"REST_DNSLIST",method:"GET",url:this.config.serviceConfig.dnsConfigUrls[0]});try{const t=await kb(void 0!==this.config.appId?{appId:this.config.appId,baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:c.request}:{appKey:this.requireConfiguredAppKey(),baseUrls:this.config.serviceConfig.dnsConfigUrls,requestAdapter:c.request});a=t.appKey,this.activeAppKey=a,tm({appKey:a}),Si("DNS resolved for login",{baseUrl:t.baseUrl,websocketUrl:t.websocketUrl,syncWsCount:t.syncWebsocketUrls.length,restBaseUrl:t.restBaseUrl}),p=t.websocketUrl,m=t.websocketUrls,this.contactSyncWsUrls=t.syncWebsocketUrls,this.syncConversationListConfigWsUrls=t.syncWebsocketUrls,this.contactSyncDnsResolved=!0,f=t.restBaseUrl,y="true"===t.dnsConfig.enableReportLogs,g=t.dnsConfig.reportInterval,v="true"===t.dnsConfig.enableMd5Check,b="false"!==t.dnsConfig.uploadinparts_enable,e?.finish({code:200,success:!0}),rm(t.dnsConfig.enableDataReport),Ci("DNS report switch resolved",{enabled:y})}catch(C){const r=C instanceof Hr?C.code:-1,s=C instanceof Error?C.message:String(C);throw e?.finish({code:r,success:!1,description:s}),h?.finish({code:r,success:!1,description:s}),rm(void 0),vi("disabled"),this.activeAppKey=this.config.appKey??null,this.updateState(t),C}}else{const e=this.config.serviceConfig.serverUrls;if(!e?.wsUrl||!e.restApiUrl){const e=new Zr("serviceConfig.serverUrls.restApiUrl and serviceConfig.serverUrls.wsUrl are required when serverUrls is configured",{code:nt,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 h?.finish({code:e.code,success:!1,description:e.message}),rm(void 0),this.updateState(t),e}p=e.wsUrl,f=e.restApiUrl,v=this.config.enableMd5Check,this.contactSyncWsUrls=[],this.syncConversationListConfigWsUrls=e.syncWsUrl?[e.syncWsUrl]:[],this.contactSyncDnsResolved=!1,rm(void 0)}if(!a){const e=new Zr("appKey is unavailable after service discovery",{code:nt,details:{fields:[{path:"appKey",message:"appKey is unavailable after service discovery",rule:"required"}]}});throw this.updateState(t),im(),e}var I;if(bi({restBaseUrl:f,appKey:a,userId:i.userId,token:i.token,requestAdapter:c.request}),I=g,di.updateReportInterval(I),this.logReportEnabled=y,vi(y?"enabled":"disabled"),this.resetCore(),o!==this.loginAttempt){const e=new Wr("Login cancelled",{code:yt,details:{stage:"auth"}});throw h?.finish({code:yt,success:!1,description:e.message}),this.updateState(t),this.activeAppKey=this.config.appKey??null,im(),e}this.core=new nf({serverUrl:p,serverUrls:m,userId:i.userId,token:i.token,appKey:a,restBaseUrl:f,useReplacedMessageContents:this.config.useReplacedMessageContents,useCustomAttachmentUpload:this.config.useCustomAttachmentUpload,enableMd5Check:v,enableMultipartUpload:b,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:u,platformAdapter:c,enableDeliveryReceipt:this.config.enableDeliveryReceipt},this.eventHub),bi({resource:this.core.getClientResource()});const w=h?.startRequest({requestName:"CONNECT_WEBSOCKET",method:"",url:p});try{if(Si("Connecting core websocket",{serverUrl:p,restBaseUrl:f,userId:i.userId}),await this.core.connect(),w?.finish({code:200,success:!0}),h?.finish({code:0,success:!0}),Si("Core websocket connected",{userId:i.userId,resource:this.core.getClientResource()}),this.currentUserId=i.userId,tm({uid:i.userId}),this.restBaseUrl=f??null,this.authToken=i.token,this.clientResource=this.core.getClientResource(),await this.initCacheManager(i.userId),Si("Cache initialized after login",{userId:i.userId}),this.loadCachedConversations(),this.loadCachedUserInfo(),await this.syncSelfUserInfoAfterLogin(),this.config.enableSyncData.includes("conversation")&&await this.refreshSessionList(this.config.syncConversationListConfig),this.triggerConfiguredSyncDataAfterLogin(i.userId),this.logReportEnabled)try{await Ii()}catch(C){Si("Report logs on login failed",C)}}catch(C){const e=C instanceof Hr?C.code:-1,r=C instanceof Error?C.message:String(C);throw w?.finish({code:e,success:!1,description:r}),h?.finish({code:e,success:!1,description:r}),this.resetCore(),this.activeAppKey=this.config.appKey??null,this.updateState(t),im(),C}}async logout(){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(this.loginAttempt+=1,!this.core)return this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("logout"),this.syncWebSocketSession=null,this.syncConversationListConfigController=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),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.resetManagerSessionRuntimes(),this.updateState(t),this.logReportEnabled=!1,vi("disabled"),wi(),void im();try{if(await(this.cacheManager?.flushPending()),this.logReportEnabled)try{await Ii()}catch(r){Si("Report logs on logout failed",r)}await this.core.disconnect()}finally{this.resetCore(),this.activeAppKey=this.config.appKey??null,this.updateState(t),this.logReportEnabled=!1,vi("disabled"),wi(),im()}}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 Zr("restBaseUrl is required",{code:nt,details:{fields:[{path:"restBaseUrl",message:"restBaseUrl is required",rule:"required"}]}});if(!this.authToken)throw new Zr("token is required",{code:nt,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}});if(!this.currentUserId)throw new Zr("userId is required",{code:nt,details:{fields:[{path:"userId",message:"userId is required",rule:"required"}]}});const e=this.clientResource??this.core?.getClientResource();if(!e)throw new Zr("clientResource is required",{code:nt,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=ib.validateOrThrow(ub,e);if(!this.core||!this.currentUserId||this.state!==s)throw new Wr("ChatClient is not connected",{code:ct,details:{stage:"token",state:this.state}});const r=this.getRestContext(),n={...r},i=new ly(n.restBaseUrl,{errorMap:lI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});i.setAuthToken(t),Si("Renew token started",{userId:r.userId});const o=await qb(i,n);if(o<=Date.now())throw new Wr("Token is expired",{code:lt,details:{stage:"token"}});const a=this.core.renewToken(t,o);return this.authToken=t,bi({token:t}),Si("Renew token succeeded",{userId:r.userId,expireAt:o}),a}async getRTCTokenInfo(e){const t=ib.validateOrThrow(lb,e),r=this.getRestContext(),s=new ly(r.restBaseUrl,{errorMap:lI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),Si("Get RTC token info started",{userId:r.userId,hasChannelName:Boolean(t?.channelName)}),Bb(s,r,t)}async getUserIdsWithRTCUids(e){const t=ib.validateOrThrow(hb,e),r=this.getRestContext(),s=new ly(r.restBaseUrl,{errorMap:lI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),Si("Get userIds with RTC UIDs started",{userId:r.userId,count:t.length}),$b(s,r,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new ly(e.restBaseUrl,{errorMap:lI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return t.setAuthToken(e.token),Si("Get self ids on other platform started",{userId:e.userId,clientResource:e.clientResource}),Fb(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(){const e=this.config.serviceConfig.serverUrls?.syncWsUrl;return e?this.buildAuthenticatedSessionListSyncUrls([e]):this.buildAuthenticatedSessionListSyncUrls(this.syncConversationListConfigWsUrls)}getSharedSyncWebSocketSession(){return this.syncWebSocketSession||(this.syncWebSocketSession=new iy({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===rt.START_COMPLETED||e.stream.status===rt.FULL||e.stream.status===rt.COMPLETED||e.stream.status===rt.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:Sh(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 Vb([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 Si("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&&Si("Self user info sync returned empty result after login",{userId:this.currentUserId})}catch(t){Si("Self user info sync failed after login",{userId:this.currentUserId,error:t})}}handleIncomingMessageProfileSync(e){if("RECEIVE"!==e.direct||!this.isMessageProfileSyncEnabled())return;const t=Ih(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=>{vh.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};bh(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 Si("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&&Si("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){Si("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 Zr("ChatClient is not initialized",{code:nt,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 Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!t?.sender?.userId)throw new Zr("sender.userId is required",{code:nt,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});if(this.currentUserId&&t.sender.userId!==this.currentUserId)throw new Zr("sender.userId does not match current user",{code:it,details:{fields:[{path:"sender.userId",message:"sender.userId does not match current user",rule:"conflict"}]}});if(st(t))throw new Qr("Stream message send is not supported",{code:ir,details:{msgLocalId:t.msgLocalId,retryable:!1}});if(!this.core||this.state!==s)throw new Qr("ChatClient is not connected",{code:St,details:{msgLocalId:t.msgLocalId,state:this.state,retryable:!0}});return this.attachOutgoingMessageProfileVersions(t),this.core.sendMessage(t,r)}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 Zr("ChatClient is not initialized",{code:nt,details:{fields:[{path:"client",message:"ChatClient is not initialized",rule:"state"}]}});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct,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 Zr("ChatClient is not initialized",{code:nt});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.sendMessageAction(t,r)}async sendChatRoomOperation(t,r){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.sendChatRoomOperation(t,r)}async downloadAttachment(t){if(e.instance!==this)throw new Zr("ChatClient is not initialized",{code:nt});if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});return this.core.downloadAttachment(t)}decodeServerMessageMeta(e){if(!this.core)throw new Zr("ChatClient is not connected",{code:ct});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}`,it,"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),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),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 Zr(`${e} requires explicit manager capability: ${t}`,{code:nt,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",it,"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",nt,"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",nt,"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 Zr(e,{code:t,details:{fields:[{path:r,message:e,rule:s}],...n}})}buildManagerConflictError(e,t,r,s){return this.buildManagerValidationError("Manager key conflict",it,"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)}async initCacheManager(e){this.cacheManager&&this.cacheUserId===e||(this.cacheManager=new sg({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(zg),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(O,{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()}triggerConfiguredSyncDataAfterLogin(e){this.config.enableSyncData.includes("contact")&&(Si("Triggering automatic contact sync after login",{userId:e}),this.triggerContactSync()),this.config.enableSyncData.includes("group")&&(Si("Triggering automatic group sync after login",{userId:e}),this.triggerGroupSync())}async triggerGroupSync(){if(!this.config.enableSyncData.includes("group"))return;const e=this.ensureGroupSyncController();await e.sync()}ensureSessionListSyncController(){return this.syncConversationListConfigController||(this.syncConversationListConfigController=new Xg(this)),this.syncConversationListConfigController}ensureContactSyncController(){if(this.contactSyncController)return this.contactSyncController;const e=this.managerRegistry.get("contactManager");if(!e?.createSyncController)throw new Zr("ContactManager is required for contact sync",{code:nt,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 hy(this.getContactSyncRestContext(),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 Zr("GroupManager is required for group sync",{code:nt,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(G,{dataType:e})}emitSyncDataFinished(e){this.eventHub.dispatch(j,e)}requireCacheManager(){if(!this.cacheManager)throw new Zr("cacheManager is required",{code:nt,details:{fields:[{path:"cacheManager",message:"cacheManager is required",rule:"required"}]}});return this.cacheManager}async resolveContactSyncUrls(){const e=this.config.serviceConfig.serverUrls?.syncWsUrl;if(e)return this.buildAuthenticatedContactSyncUrls([e]);if(this.contactSyncWsUrls.length>0)return this.buildAuthenticatedContactSyncUrls(this.contactSyncWsUrls);if(this.contactSyncDnsResolved)throw Si("Automatic contact sync sync-ws is unavailable after DNS precheck",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new Hr("Contact sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect"}});if("dns"!==this.config.serviceConfig.mode)throw Si("Automatic contact sync sync-ws is unavailable without dns service config",{userId:this.currentUserId,serviceConnectionMode:this.config.serviceConfig.mode}),new Hr("Contact sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect"}});try{const e=await kb(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=e.syncWebsocketUrls,this.contactSyncDnsResolved=!0}catch(t){throw Si("Automatic contact sync sync-ws DNS resolve failed",{userId:this.currentUserId,reason:t instanceof Error?t.message:String(t)}),new Hr("Contact sync websocket dns resolve failed",Cr,{details:{stage:"socket_connect",cause:t instanceof Error?t.message:String(t)}})}if(0===this.contactSyncWsUrls.length)throw Si("Automatic contact sync sync-ws is unavailable after DNS resolve",{userId:this.currentUserId,serviceConnectionMode:"dns"}),new Hr("Contact sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect"}});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 Zr("token is required",{code:nt,details:{fields:[{path:"token",message:"token is required",rule:"required"}]}})}buildContactSyncSocketUrl(e,t){const r=e.trim();if(!/^wss?:\/\/[^/?#]+/i.test(r))throw new Zr("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.getContactSyncRestContext(),{orgName:r,appName:s}=Qn(t.appKey);return{type:Xb,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}}resetCore(){this.contactSyncController?.cancel(),this.contactSyncController=null,this.groupSyncController?.cancel(),this.groupSyncController=null,this.syncWebSocketSession?.cancel("reset-core"),this.syncWebSocketSession=null,this.syncConversationListConfigController=null,this.userInfoHydrationQueue.destroy(),this.groupNamecardHydrationQueue.destroy(),this.activeIncomingStreamMessageIds.clear(),this.core&&(this.core.destroy(),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,this.resetManagerSessionRuntimes())}requireConfiguredAppKey(){if(this.config.appKey)return this.config.appKey;throw new Zr("appKey is unavailable before DNSConfig resolution",{code:nt,details:{fields:[{path:"appKey",message:"appKey is unavailable before DNSConfig resolution",rule:"required"}]}})}requireActiveAppKey(){if(this.activeAppKey)return this.activeAppKey;throw new Zr("appKey is unavailable for the current session",{code:nt,details:{fields:[{path:"appKey",message:"appKey is unavailable for the current session",rule:"required"}]}})}resetManagerSessionRuntimes(){const e=this.managerRegistry.get("groupManager");e?.resetSessionRuntime?.()}getContactSyncRestContext(){const e=this.getRestContext(),t=this.config.serviceConfig.serverUrls?.syncRestApiUrl;return t?{...e,restBaseUrl:t}:e}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?.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(e){return{mode:e?.serverUrls?"fixed":"dns",dnsConfigUrls:e?.dnsConfigUrls??vb,hasCustomDnsConfigUrls:Boolean(e?.dnsConfigUrls?.length),serverUrls:e?.serverUrls}}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&&e.syncRestApiUrl===t.syncRestApiUrl&&e.syncWsUrl===t.syncWsUrl)}};hI.instance=null;let pI=hI;const mI=(e,t)=>new Zr(t,{code:it,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),fI=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw(e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}))(t);return e.trim()},gI=e=>`mark_${String(e)}`,yI=(e,t)=>{if("singleChat"===e||"groupChat"===e||"chatRoom"===e)return e;throw mI(t,`${t} must be one of singleChat, groupChat, chatRoom`)},vI=e=>"singleChat"===e?"chat":"groupChat"===e?"groupchat":"chatroom",bI=e=>"string"==typeof e&&e.length>0?e:void 0,II=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}},wI=e=>Bl(e)?e:void 0,CI=(e,t)=>{const r=wI(e);if(!r)return;const s=(e=>"string"==typeof e?$l(e,{}):wI(e)??{})(r.payload),n=Array.isArray(s.bodies)?s.bodies:[],i=wI(n[0])??wI(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:bI(t.msg)??bI(t.content)??""};if("custom"===e){const e=wI(t.customExts)??wI(t.params)??{},r={};for(const[t,s]of Object.entries(e))"string"==typeof s&&(r[t]=s);return{event:bI(t.customEvent)??bI(t.event)??"",params:r}}if("cmd"===e)return{action:bI(t.action)??""};if("image"===e){const e=bI(t.url)??bI(t.remotePath)??"";return{localUrl:"",filename:bI(t.filename)??bI(t.displayName),filetype:bI(t.filetype)??"application/octet-stream",width:II(t.width),height:II(t.height),isGif:!0===t.isGif||1===t.subType,isOriginalImage:!0===t.isOriginalImage,originalImageUrl:e,bigImageUrl:bI(t.bigImageUrl),thumbnailUrl:bI(t.thumbnailUrl)??bI(t.thumbnailRemotePath),secret:bI(t.secret)??bI(t.secretKey),fileLength:II(t.fileLength)}}return"file"===e?{url:bI(t.url)??bI(t.remotePath),filename:bI(t.filename)??bI(t.displayName),filetype:bI(t.filetype)??"application/octet-stream",fileSize:II(t.fileSize),fileLength:II(t.fileLength),secret:bI(t.secret)??bI(t.secretKey)}:"voice"===e?{url:bI(t.url)??bI(t.remotePath),filename:bI(t.filename)??bI(t.displayName),filetype:bI(t.filetype)??"application/octet-stream",duration:II(t.duration)??0,fileLength:II(t.fileLength),secret:bI(t.secret)??bI(t.secretKey)}:"video"===e?{url:bI(t.url)??bI(t.remotePath),filename:bI(t.filename)??bI(t.displayName),filetype:bI(t.filetype)??"application/octet-stream",duration:II(t.duration)??0,width:II(t.width),height:II(t.height),fileLength:II(t.fileLength),secret:bI(t.secret)??bI(t.secretKey),thumbnailUrl:bI(t.thumbnailUrl)??bI(t.thumbnailRemotePath)}:"location"===e?{latitude:II(t.latitude)??0,longitude:II(t.longitude)??0,address:bI(t.address),buildingName:bI(t.buildingName)}:null})(o,i);if(!a)return;const c=bI(s.from)??bI(r.from)??"",d=bI(s.to)??t.conversationId,u=wI(s.sender),l={userId:bI(u?.userId)??c,nickname:bI(u?.nickname),avatarUrl:bI(u?.avatarUrl)},h=wI(s.ext)??{},p=(e=>{const t=wI(e);if(!t)return;const r=bI(t.operatorId)??bI(t.operator),s=II(t.operationCount)??II(t.count),n=II(t.operationTime)??II(t.edit_time);return r&&void 0!==s&&void 0!==n?{operatorId:r,operationCount:s,operationTime:n}:void 0})(s.modifiedInfo??wI(s.meta)?.edit_msg);return{msgServerId:bI(r.id)??t.messageId,msgLocalId:bI(r.msgLocalId)??"",from:c,to:d,sender:l,conversationId:t.conversationId,conversationType:t.conversationType,type:o,sendStatus:"sent",ext:h,timestamp:II(r.timestamp)??t.timestamp,body:a,direct:c===t.currentUserId?"SEND":"RECEIVE",...p?{modifiedInfo:p}:{}}},SI=e=>`${e.conversationType}:${e.conversationId}`,TI=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},_I=async(e,t,r,s)=>{const n=TI(t),i=(e=>{const t=e,r=t.conversations;if(void 0!==r){if(!Array.isArray(r)||0===r.length)throw mI("params.conversations","params.conversations must be a non-empty array");return r.map((e,t)=>{if(!Bl(e))throw mI(`params.conversations.${String(t)}`,`params.conversations.${String(t)} must be an object`);return{conversationId:fI(e.conversationId,`params.conversations.${String(t)}.conversationId`),conversationType:yI(e.conversationType,`params.conversations.${String(t)}.conversationType`)}})}return[{conversationId:fI(t.conversationId,"params.conversationId"),conversationType:yI(t.conversationType,"params.conversationType")}]})(r),o=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0||e>19)throw mI(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:gI(o),targets:i.map(e=>({to:e.conversationId,type:vI(e.conversationType)}))},operation:s?"addConversationMark":"removeConversationMark"}),c=(e=>{if(!Array.isArray(e))return new Set;const t=new Set;return e.forEach(e=>{if(!Bl(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(SI({conversationId:r,conversationType:s}))}),t})((Bl(a)&&Bl(a.data)?a.data:{}).ignore),d=[],u=[];for(const l of i){const e={conversationId:l.conversationId,conversationType:l.conversationType};c.has(SI(l))?u.push({...e,reason:"ignored_by_server"}):d.push(e)}return{succeeded:d,failed:u,mark:o,operation:s?"addMark":"removeMark"}},RI=async(e,t,r,s)=>{const n=TI(t),i=fI(r.conversationId,"params.conversationId"),o=yI(r.conversationType,"params.conversationType"),a=fI(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:vI(o),pin_msg_id:a},operation:s?"pinMessage":"unpinMessage"}),{conversationId:i,conversationType:o,messageId:a,operation:s?"pin":"unpin"}},AI=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],MI=(e,t)=>`${e}\0${t}`,EI=(e,t,r)=>{const s={userId:e};for(const n of AI){const e=r?.[n]??t?.[n];void 0!==e&&(s[n]=e)}return s},UI=e=>EI(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),NI=(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(MI(n.groupId,n.user.userId),t.namecard)}return s},kI=async(e,t)=>{if(0===e.length||!t)return[];try{return await t({userIds:e})}catch(r){return Si("Group user info hydration failed",{userIds:e,error:r}),[]}},OI=async(e,t)=>{t&&0!==e.size&&await Promise.all([...e.entries()].map(async([e,r])=>{try{await t(e,r)}catch(s){Si("Group namecard hydration failed",{groupId:e,userIds:r,error:s})}}))},xI=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=MI(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,UI(n));return r})(e.cacheManager,r),n=r.filter(e=>!s.has(e)),i=new Set(n),o=NI(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=MI(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([kI(n,e.fetchUserInfos),OI(a,e.hydrateGroupNamecards)]),d=new Map(c.map(e=>[e.userId,e])),u=NI(e.cacheManager,t,e.includeNameCard),l=new Map;for(const h of t){const e=h.user.userId,t=MI(h.groupId,e),r=EI(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))}},LI=async e=>{const t=await xI({...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(MI(e.groupId.trim(),n));i&&r.set(n,i)}return{usersById:r,fetchedUserInfos:t.fetchedUserInfos,missingUserIds:t.missingUserIds}},PI=nb(["singleChat","groupChat","chatRoom"]),DI=sb(Yv()).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"),qI=tb({path:Jv().min(1,"data.path is required"),size:Zv().optional(),name:Jv().optional(),type:Jv().optional()}),BI=tb({uri:Jv().min(1,"data.uri is required"),size:Zv().optional(),name:Jv().optional(),type:Jv().optional()}),$I=rb(["undefined"!=typeof File?((e,t={message:`Input not instance of ${e.name}`})=>Hv(t=>t instanceof e,t))(File):Xv(),qI,BI]),FI=tb({conversationId:Jv().min(1,"conversationId is required"),conversationType:PI,ext:DI.optional(),timestamp:Zv().int().positive("timestamp must be a positive integer").optional(),receiverList:eb(Jv().min(1,"receiverList item is required")).nonempty("receiverList must not be empty").optional(),deliverOnlineOnly:Qv().optional(),webhookEnv:Jv().optional(),priority:nb(["high","normal","low"]).optional(),needReadReceipt:Qv().optional(),isChatThread:Qv().optional()}),GI=tb({type:Jv().min(1,"messageList.type is required"),sender:tb({userId:Jv().min(1,"messageList.sender.userId is required"),nickname:Jv().optional(),avatarUrl:Jv().optional()}),conversationId:Jv().min(1,"messageList.conversationId is required"),conversationType:PI,timestamp:Zv().int().positive("messageList.timestamp must be positive"),body:sb(Yv()),combineLevel:Zv().int().min(0).max(10).optional()}).passthrough(),jI=e=>e.superRefine((e,t)=>{e.receiverList&&"singleChat"===e.conversationType&&t.addIssue({code:by.custom,message:"receiverList is only allowed for group or chat room conversation",path:["receiverList"]}),e.isChatThread&&"groupChat"!==e.conversationType&&t.addIssue({code:by.custom,message:"isChatThread is only allowed for group conversation",path:["isChatThread"]}),e.needReadReceipt&&"chatRoom"===e.conversationType&&t.addIssue({code:by.custom,message:"needReadReceipt is not allowed for chatRoom conversation",path:["needReadReceipt"]})}),zI=jI(FI.extend({content:Jv().min(1,"content is required"),targetLanguages:eb(Jv().min(1)).optional()})),KI=jI(FI.extend({originalUrl:Jv().min(1,"originalUrl is required").optional(),filename:Jv().min(1,"filename is required").optional(),filetype:Jv().min(1,"filetype is required").optional(),width:Zv().positive("width must be positive").optional(),height:Zv().positive("height must be positive").optional(),isGif:Qv().optional(),isOriginalImage:Qv().optional(),fileLength:Zv().positive("fileLength must be positive").optional(),data:$I.optional(),thumbnailUrl:Jv().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),HI=jI(FI.extend({originalUrl:Jv().min(1,"originalUrl is required").optional(),filename:Jv().min(1,"filename is required").optional(),filetype:Jv().min(1,"filetype is required").optional(),fileSize:Zv().positive("fileSize must be positive").optional(),fileLength:Zv().positive("fileLength must be positive").optional(),data:$I.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),VI=jI(FI.extend({originalUrl:Jv().min(1,"originalUrl is required").optional(),filename:Jv().min(1,"filename is required").optional(),filetype:Jv().min(1,"filetype is required").optional(),duration:Zv().positive("duration must be positive"),fileLength:Zv().positive("fileLength must be positive").optional(),data:$I.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),WI=jI(FI.extend({originalUrl:Jv().min(1,"originalUrl is required").optional(),filename:Jv().min(1,"filename is required").optional(),filetype:Jv().min(1,"filetype is required").optional(),duration:Zv().positive("duration must be positive"),width:Zv().positive("width must be positive").optional(),height:Zv().positive("height must be positive").optional(),fileLength:Zv().positive("fileLength must be positive").optional(),thumbnailUrl:Jv().min(1).optional(),data:$I.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),JI=jI(FI.extend({latitude:Zv(),longitude:Zv(),address:Jv().min(1).optional(),buildingName:Jv().min(1).optional()})),ZI=jI(FI.extend({action:Jv().min(1,"action is required")})),QI=jI(FI.extend({event:Jv().min(1,"event is required"),params:sb(Jv()).optional()})),YI=jI(FI.extend({title:Jv().min(1,"title is required"),summary:Jv().min(1,"summary is required"),compatibleText:Jv().min(1).optional(),messageList:eb(GI).min(1,"messageList must not be empty").max(300,"messageList max length is 300")})),XI=e=>{const t=e?.userId?.trim();if(!t)throw new Zr("sender.userId is required",{code:nt,details:{fields:[{path:"sender.userId",message:"sender.userId is required",rule:"required"}]}});return{userId:t,nickname:e?.nickname,avatarUrl:e?.avatarUrl}},ew=()=>dm(),tw=(e,t)=>{if(e)return e;if(!t)throw new Zr("url or data is required",{code:nt,details:{fields:[{path:"url",message:"url or data is required",rule:"required"}]}});const r=cm(t);if(!r)throw new Zr("Failed to resolve local url",{code:it,details:{fields:[{path:"url",message:"Failed to resolve local url",rule:"invalid_format"}]}});return r},rw=e=>!!e.isGif||(e.isOriginalImage??!1),sw=(e,t,r,s,n)=>({msgServerId:"",msgLocalId:n??dm(),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}),nw=(e,t)=>{const r=ib.validateOrThrow(YI,e),s=r.messageList,n=XI(t);Mm(s);const i=Em(s);Um(i);const o={title:r.title,summary:r.summary,messageList:s,filename:"combine",filetype:"application/octet-stream",combineLevel:i},a=sw(r,n,"combine",o);return((e,t)=>{t&&Th.set(e,t)})(a,r.compatibleText),a},iw=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}`},ow=e=>{const t=new Uint8Array(Vc.util.base64.length(e));return Vc.util.base64.decode(e,t,0),t},aw=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),cw=async e=>{try{return await e()}catch(t){if(!(t instanceof ts))throw t;const e=(e=>{const t="string"==typeof e.details?.serverMessage?e.details.serverMessage:void 0;switch(e.code){case qt:case Ar:return"Translation service is not enabled";case Rr:return t?.includes("too long")?"Translation text is too long":t?.includes("target language")?"Invalid target language":"Invalid translation request";case Mr:return"Translation quota has been reached";case Er:return"Translation service error";default:return}})(t);if(!e)throw t;throw new ts(`REST business error: ${e}`,{code:t.code,details:t.details})}},dw=e=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):"",uw=e=>{if("string"!=typeof e)return"";const t=e.trim();return t&&"undefined"!==t&&"null"!==t?t:""},lw=e=>({userId:e}),hw=(e,t)=>{if(!aw(e)||!aw(e.data))throw ay({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},pw=(e,t)=>{if(!aw(e)||!Array.isArray(e.data))throw ay({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},mw=(e,t)=>Array.isArray(e)?e:pw(e,t),fw={txt:"text",img:"image",video:"video",file:"file",loc:"location",custom:"custom",combine:"combine"},gw={text:"txt",image:"img",video:"video",file:"file",location:"loc",custom:"custom",combine:"combine"},yw={chat:"singleChat",chatroom:"chatRoom",groupchat:"groupChat",singleChat:"singleChat",chatRoom:"chatRoom",groupChat:"groupChat"},vw=(e,t,r)=>{if(!t)return"";if(t.includes("em-redirect"))return t;const{orgName:s,appName:n}=Qn(e.appKey),i=t.indexOf("/chatfiles/"),o=i>=0?t.slice(i):t,a=`${e.restBaseUrl}/${s}/${n}${o}`;return ri(a,r)},bw=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},Iw=(e,t,r)=>{const s=dw(r.contentType??r.type),n=gw[s];if(!n)return null;const i=aw(r.content)?r.content:{},o=((e,t)=>{const r=dw(t.conversationType);if("groupchat"===r||"chatroom"===r)return dw(t.receiverId);const s=dw(t.senderId);return s===e?dw(t.receiverId):s})(t,r),a=yw[dw(r.conversationType)]??"singleChat",c={msgServerId:dw(r.messageId),msgLocalId:dw(r.messageId),from:dw(r.senderId),to:dw(r.receiverId),conversationId:o,conversationType:a,type:n,ext:aw(r.ext)?r.ext:{},timestamp:"number"==typeof r.sentTime?r.sentTime:new Date(dw(r.sentTime)).getTime(),sender:{userId:dw(r.senderId)},highlight:bw(r.highlight),text:"string"==typeof r.text?r.text:void 0};let d;const u=dw(i.remotePath??i.url),l=dw(i.secret??i.secretKey);switch(n){case"txt":d={type:"txt",content:dw(i.message??r.text)};break;case"img":{const t=vw(e,u,l);d={type:"img",url:t,thumb:i.thumb?vw(e,dw(i.thumb),dw(i.thumb_secret??i.thumbnailSecretKey)):`${t}&thumbnail=true`,secret:l,width:Number(i.width??(aw(i.size)?i.size.width:0))||0,height:Number(i.height??(aw(i.size)?i.size.height:0))||0,fileLength:Number(i.file_length??i.fileLength??0)};break}case"video":d={type:"video",url:vw(e,u,l),thumb:i.thumb||i.thumbnailRemotePath?vw(e,dw(i.thumb??i.thumbnailRemotePath),dw(i.thumb_secret??i.thumbnailSecretKey)):"",secret:l,filename:dw(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:vw(e,u,l),secret:l,filename:dw(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:dw(i.addr??i.address),buildingName:dw(i.buildingName)};break;case"custom":d={type:"custom",customEvent:dw(i.customEvent),customExts:aw(i.customExts)?i.customExts:{}};break;default:return null}return{...c,body:d}},ww=async(e,t,r)=>{const s=`${iw(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=>fw[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=aw(i)?i:{},a=aw(o.data)?o.data:o,c=aw(a.data)?a.data:a,d=Array.isArray(c.items)?c.items:Array.isArray(c.list)?c.list:[],u=aw(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(!aw(g))continue;const e=Iw(t,t.userId,g);e&&f.push(e)}return{messages:f,pageNum:l,pageSize:h,totalPages:p,isLast:m}},Cw=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/api/sdk/v1/${t}/${r}`},Sw=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Tw=e=>Sw(e)&&"string"==typeof e.path&&e.path.trim().length>0,_w=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||Tw(e),Rw=e=>{if(!Sw(e))return;return{data:Sw(e.data)?e.data:void 0,error:Sw(e.error)?e.error:void 0}},Aw=(e,t)=>{const r=Rw(e),s=r?.data?.text;if("string"!=typeof s)throw new Hr(`${t} response data is invalid`,fr,{details:{api:t,response:e}});return s},Mw=(e,t,r,s="sdk")=>"auth"===s?new Jr(e,{code:t,details:r}):"validation"===s?new Zr(e,{code:t,details:r}):new Hr(e,t,{details:r}),Ew=e=>!(void 0===e||Sw(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))),Uw=e=>{if(!e)return;const t=(e.split("#")[0]?.split("?")[0]??"").split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0},Nw=e=>{const{serviceCode:t,serviceMessage:r}=(e=>{const t=e instanceof Hr&&Sw(e.details)?e.details:void 0,r=Rw(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 rs)return Mw("File upload failed",qr,{cause:e.details});if(e instanceof Hr&&!t)return e;if(t)switch(t){case"4041001":return Mw("File not found",Or,{serviceCode:t,serviceMessage:r});case"4001002":return Mw("Invalid file",Ur,{serviceCode:t,serviceMessage:r},"validation");case"5021001":return Mw("File upload failed",qr,{serviceCode:t,serviceMessage:r});case"4001003":return Mw("Voice duration exceeds 60 seconds",Nr,{serviceCode:t,serviceMessage:r},"validation");case"4031001":return Mw("Voice-to-text service is not enabled",qt,{serviceCode:t,serviceMessage:r});case"4031002":return Mw("Beta service usage limit exceeded",Fr,{serviceCode:t,serviceMessage:r});case"4001001":return"string"==typeof(s=r)&&s.toLowerCase().includes("uploaded file exceeds")?Mw("File too large",xr,{serviceCode:t,serviceMessage:r}):Mw(r||"Missing or invalid request parameter",nt,{serviceCode:t,serviceMessage:r},"validation");case"5021003":case"5001003":return Mw("Voice-to-text failed",kr,{serviceCode:t,serviceMessage:r});case"4011001":return Mw(r||"Unauthorized or invalid token",dt,{serviceCode:t,serviceMessage:r},"auth");default:return Mw(r||(e instanceof Error?e.message:"Voice-to-text failed"),kr,{serviceCode:t,serviceMessage:r})}var s;return e instanceof Hr?Mw(e.message,e.code,e.details):Mw(e instanceof Error?e.message:"Voice-to-text failed",kr)},kw=(e,t)=>{if(!Sw(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 Mw("Invalid file",Ur,{path:"voiceMessageBody"},"validation");var r;if(Ew(t))throw Mw("Invalid file",Ur,{path:"voiceParams"},"validation");if(!e.url)throw Mw("File not found",Or,{path:"voiceMessageBody.url"});if(!Uw(e.url))throw Mw("Invalid file",Ur,{path:"voiceMessageBody.url"},"validation");return e},Ow=(e,t)=>{if(Ew(t))throw Mw("Invalid file",Ur,{path:"voiceParams"},"validation");if(!_w(e))throw Mw("Invalid file",Ur,{path:"file"},"validation");return e},xw=async(e,t,r,s)=>{const n=kw(r,s),i=Uw(n.url);if(!i)throw((e,t,r,s="invalid")=>new Zr(e,{code:t,details:{fields:[{path:r,message:e,rule:s}]}}))("File not found",Or,"voiceMessageBody.url");try{const r=await e.post(`${Cw(t)}/speech/transcriptions`,{data:{fileId:i,username:t.userId,...s?{audio:s}:{}}},{operation:"voiceMessageToText"});return{text:Aw(r,"voiceMessageToText")}}catch(o){throw Nw(o)}},Lw=tb({keywordList:eb(Jv()).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:nb(["or","and"]).optional(),conversationId:Jv().min(1).optional(),conversationType:nb(["singleChat","groupChat","chatRoom"]).optional(),msgTypes:eb(nb(["txt","img","video","file","loc","custom","combine"])).optional(),startTime:Zv().optional(),endTime:Zv().optional(),searchScope:nb(["none","with","only"]).optional(),direction:nb(["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"}),Pw=tb({option:Lw,pageNum:Zv().int().min(1).default(1),pageSize:Zv().int().min(1).max(100).default(20)}),Dw=Gb(jb,{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"]}}}}}),qw=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=ib.validateOrThrow(zI,e),s=XI(t),n=ew(),i={content:r.content};return r.targetLanguages&&(i.targetLanguages=r.targetLanguages),sw(r,s,"text",i,n)})(e,this.buildMessageSenderOrThrow())}createImageMessage(e){return((e,t,r)=>{const s=ib.validateOrThrow(KI,e),n=XI(t),i=ew(),o=s.data?tw(void 0,s.data):"",a=s.originalUrl?ni(s.originalUrl,{deriveVariants:!r?.useCustomAttachmentUpload}):void 0;s.data&&am.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:rw({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),sw(s,n,"image",d,i)})(e,this.buildMessageSenderOrThrow(),this.getClientOrThrow().getMessageCreationOptions())}createFileMessage(e){return((e,t)=>{const r=ib.validateOrThrow(HI,e),s=XI(t),n=ew(),i=tw(r.originalUrl,r.data);r.data&&am.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),sw(r,s,"file",o,n)})(e,this.buildMessageSenderOrThrow())}createVoiceMessage(e){return((e,t)=>{const r=ib.validateOrThrow(VI,e),s=XI(t),n=ew(),i=tw(r.originalUrl,r.data);r.data&&am.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),sw(r,s,"voice",o,n)})(e,this.buildMessageSenderOrThrow())}createVideoMessage(e){return((e,t)=>{const r=ib.validateOrThrow(WI,e),s=XI(t),n=ew(),i=tw(r.originalUrl,r.data);r.data&&am.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),sw(r,s,"video",o,n)})(e,this.buildMessageSenderOrThrow())}createLocationMessage(e){return((e,t)=>{const r=ib.validateOrThrow(JI,e),s=XI(t),n={latitude:r.latitude,longitude:r.longitude};return r.address&&(n.address=r.address),r.buildingName&&(n.buildingName=r.buildingName),sw(r,s,"location",n)})(e,this.buildMessageSenderOrThrow())}createCmdMessage(e){return((e,t)=>{const r=ib.validateOrThrow(ZI,e),s=XI(t),n={action:r.action};return void 0!==r.deliverOnlineOnly&&(n.deliverOnlineOnly=r.deliverOnlineOnly),sw(r,s,"cmd",n)})(e,this.buildMessageSenderOrThrow())}createCustomMessage(e){return((e,t)=>{const r=ib.validateOrThrow(QI,e),s=XI(t),n={event:r.event};return r.params&&(n.params=r.params),sw(r,s,"custom",n)})(e,this.buildMessageSenderOrThrow())}createCombineMessage(e){return nw(e,this.buildMessageSenderOrThrow())}getConversationList(e){if(void 0!==e?.mark&&(!Number.isInteger(e.mark)||e.mark<0||e.mark>19))throw new Zr("filter.mark must be an integer between 0 and 19",{code:it,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(zg);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=TI(t),n=fI(r.conversationId,"params.conversationId"),i=yI(r.conversationType,"params.conversationType"),o=r.deleteRoamingMessages??!1;if("boolean"!=typeof o)throw mI("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":vI(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=TI(t),n=fI(r.conversationId,"params.conversationId"),i=yI(r.conversationType,"params.conversationType");if("boolean"!=typeof r.pinned)throw mI("params.pinned","params.pinned must be a boolean");const o="groupChat"===i?"groupChat":vI(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=Bl(a)&&Bl(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)=>_I(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)=>_I(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=TI(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)=>RI(e,t,r,!0))(this.getRestClient(t),t,e))}async unpinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>RI(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=TI(t),n=fI(r.conversationId,"params.conversationId"),i=yI(r.conversationType,"params.conversationType"),o=await e.get(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/pin?to=${encodeURIComponent(n)}&type=${encodeURIComponent(vI(i))}&limit=${String(20)}`,{operation:"getPinnedMessageList"}),a=Bl(o)&&Bl(o.data)?o.data:{};return{items:(Array.isArray(a.msg_infos)?a.msg_infos:[]).reduce((e,r)=>{if(!Bl(r))return e;const s="string"==typeof r.pin_msg_id?r.pin_msg_id:Bl(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=CI(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},[])}})(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;Si("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 Zr("only text and custom messages are editable",{code:Ut});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=`${iw(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=hw(i,"getHistoryMessages"),a=Array.isArray(o.msgs)?o.msgs:[],c=[];for(const d of a){if(!aw(d)||"string"!=typeof d.msg||0===d.msg.length)continue;const e=s(ow(d.msg));e&&c.push(e)}return{items:c,cursor:uw(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=ib.validateOrThrow(Pw,e),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>ww(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?`${iw(t)}/sdk/message/roaming/${n}/user/${t.userId}?${s}=${encodeURIComponent(r.conversationId)}&msgIdList=${encodeURIComponent(r.messageIds.join(","))}&resource=${i}`:`${iw(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=gb();s.set("limit",String(r.pageSize??10)),r.cursor&&s.set("key",r.cursor);const n=`${iw(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/${encodeURIComponent(r.messageId)}?${s.toString()}`,i=await e.get(n,{operation:"getGroupMessageReadUsers"}),o=hw(i,"getGroupMessageReadUsers"),a=aw(o.group_ack)?o.group_ack:o,c=(Array.isArray(a.userlist)?a.userlist:[]).map(e=>aw(e)&&"string"==typeof e.username?{userId:e.username,user:lw(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:uw(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=`${iw(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/batch`,n=await e.post(s,{messageIds:r.messageIds},{operation:"getGroupMessageReadReceipts"});return pw(n,"getGroupMessageReadReceipts").map(e=>aw(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(`${iw(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=`${iw(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=gb(),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(`${iw(t)}/reaction/user/${t.userId}?${s.toString()}`,{operation:"getReactionList"});return pw(i,"getReactionList").map(e=>{if(!aw(e)||"string"!=typeof e.msgId)return null;const t=Array.isArray(e.reactionList)?e.reactionList:[];return{messageId:e.msgId,reactions:t.map(e=>aw(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=gb();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(`${iw(t)}/reaction/user/${t.userId}/detail?${s.toString()}`,{operation:"getReactionDetail"}),i=hw(n,"getReactionDetail"),o=Array.isArray(i.reactionUserList)?i.reactionUserList.map(e=>aw(e)&&"string"==typeof e.userId?{userId:e.userId,user:lw(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:lw(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:uw(i.cursor),hasMore:uw(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 cw(()=>e.get(`${iw(t)}/users/${t.userId}/translate/support/language`,{operation:"getSupportedTranslationLanguages"}));return mw(r,"getSupportedTranslationLanguages").map(e=>aw(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 Zr("only text messages can be translated",{code:Rr,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 Zr("message text is required",{code:Rr,details:{fields:[{path:"message.body.content",message:"is required",rule:"required"}]}});if(!Array.isArray(e.targetLanguages)||0===e.targetLanguages.length)throw new Zr("targetLanguages is required",{code:Rr,details:{fields:[{path:"targetLanguages",message:"is required",rule:"required"}]}});if(e.targetLanguages.some(e=>"string"!=typeof e||0===e.trim().length))throw new Zr("targetLanguages contains invalid language code",{code:Rr,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 cw(()=>e.post(`${iw(t)}/users/${t.userId}/translate`,{text:r.text,to:[...r.targetLanguages]},{operation:"translateMessage"})),n=mw(s,"translateMessage"),i=aw(n[0])?n[0]:null;if(!i)throw ay({apiName:"translateMessage",message:"translateMessage response data is invalid",mapped:!1});const o=Array.isArray(i.translations)?i.translations:[],a=aw(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=>aw(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){kw(e,t);const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>xw(this.getRestClient(r),r,e,t))}async voiceFileToText(e,t){Ow(e,t);const r=this.getRestContextOrThrow(),s=this.getClientOrThrow().getUploadAdapter();if(!s)throw new Hr("Upload capability is missing for current platform",Lr);return this.executeRestOperation(()=>(async(e,t,r,s)=>{const n=Ow(r,s),i=Gn({file:n,fallbackName:Tw(n)?"voice.amr":void 0,fallbackMimeType:"audio/amr"});try{const r=await e.upload({url:`${t.restBaseUrl}${Cw(t)}/speech/recognitions`,headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json",[Ml]:Al()},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 Hr("Voice-to-text failed",kr,{details:{httpStatus:r.status,rawResponse:n}});return{text:Aw(n,"voiceFileToText")}}catch(o){if(o instanceof Hr)throw Nw(o);throw Nw(ll(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 Zr("message must be a combine message",{code:it});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===ct||e===dt?new Jr(t??"authentication failed",{code:e}):e===gt||e===ft?new Wr(t??"connection unavailable",{code:e}):107===e||110===e||205===e||500===e||e===nt||e===it?new Zr(t??"invalid parameter",{code:e}):e===Dt?new Hr(t??"message recall time limit reached",e):e===zt?new Hr(t??"message update failed",e):e===Ut?new Zr(t??"operation unsupported",{code:e}):new Hr(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 Zr(e,{code:it,details:{fields:[{path:t,message:e,rule:"required"}]}})}getEventContextOrThrow(){if(!this.eventContext)throw new Zr("ChatManager is not bound to event context",{code:nt});return this.eventContext}getClientOrThrow(){if(!this.client)throw new Zr("ChatManager is not bound to client",{code:nt});return this.client}getRestContextOrThrow(){return this.getClientOrThrow().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new ly(e.restBaseUrl,{errorMap:Dw,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 Wr("client is not connected",{code:gt});return e}getCurrentUserIdOrThrow(){const e=this.getClientOrThrow().getCurrentUserId();if(!e)throw new Jr("user is not logged in",{code:ct});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 LI({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 Zr||e instanceof Jr||e instanceof Wr||e instanceof Vr?e:e instanceof es?new Vr(e.message,{code:e.code,details:e.details}):e instanceof ts||e instanceof Hr?e:new Hr(String(e),Gr)}};qw.key="chatManager";let Bw=qw;class $w{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 Fw=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),Gw=(e,t)=>new Zr(t,{code:it,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),jw=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw Fw(t);return e.trim()},zw=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw Gw(t,`${t} must be a string`);return e},Kw=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw Gw(t,`${t} must be an integer between 1 and 50`);return e},Hw=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},Vw=e=>Bl(e)?e:null,Ww=e=>{const t=Vw(e);return t?.data??e},Jw=e=>{const t=Vw(e);if(Array.isArray(t?.entities))return t.entities;const r=Ww(e);if(Array.isArray(r))return r;const s=Vw(r);return Array.isArray(s?.entities)?s.entities:Array.isArray(s?.affiliations)?s.affiliations:[]},Zw=e=>{const t=Vw(e),r=Vw(t?.data),s=Vw(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)??""},Qw=e=>{const t=Vw(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?$l(n,{}):Vw(n)??{},o=Array.isArray(i.bodies)?i.bodies:[],a=Vw(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}},Yw=e=>{const t=Vw(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:Qw(t.lastMessage??t.last_message)}:null},Xw=e=>({items:Jw(e).map(e=>Yw(e)).filter(e=>null!==e),cursor:Zw(e)}),eC=async(e,t,r)=>{const s=Hw(t),n=jw(r,"chatThreadId");return(e=>{const t=Ww(e),r=Array.isArray(t)?t[0]:t,s=Yw(r);if(!s)throw Gw("response.data","response.data is invalid");return s})(await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}`,{operation:"getChatThreadInfo"}))},tC=async(e,t,r)=>{const s=Hw(t),n=jw(r.chatThreadId,"params.chatThreadId"),i=Kw(r.pageSize,"params.pageSize"),o=zw(r.cursor,"params.cursor"),a=gb({limit:String(i),cursor:o}),c=await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users?${a.toString()}`,{operation:"getChatThreadMemberList"});return{items:Jw(d=c).map(e=>{if("string"==typeof e)return{memberId:e};const t=Vw(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:Zw(d)};var d},rC=async(e,t,r)=>{const s=Hw(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw Fw("params.chatThreadIds");if(r.chatThreadIds.length>20)throw Gw("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const n=r.chatThreadIds.map((e,t)=>jw(e,`params.chatThreadIds[${t}]`)),i=await e.post(`/${s.orgName}/${s.appName}/thread/message`,{threadIds:n},{operation:"getChatThreadLastMessageList"});return{items:Jw(i).map(e=>{const t=Vw(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:Qw(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},sC=Gb(jb,{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"]}}}}}),nC=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 Zr("chatThreadId is required",{code:nt,details:{fields:[{path:"chatThreadId",message:"chatThreadId is required",rule:"required"}]}});const r=this.registry.get(t);if(r)return r;const s=new $w(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=Hw(t),n=jw(r.parentId,"params.parentId"),i=jw(r.name,"params.name"),o=jw(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=Vw(Ww(a)),d="string"==typeof c?.thread_id?c.thread_id:void 0;if(!d)throw Gw("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=Hw(t),n=jw(r.parentId,"params.parentId"),i=Kw(r.pageSize,"params.pageSize"),o=zw(r.cursor,"params.cursor"),a=gb({limit:String(i),cursor:o}),c=await e.get(`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(n)}?${a.toString()}`,{operation:"getChatThreadList"});return Xw(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=Hw(t),n=Kw(r.pageSize,"params.pageSize"),i=zw(r.cursor,"params.cursor"),o=gb({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 Xw(c)})(this.getRestClient(t),t,e)})}async getChatThreadInfo(e){return this.runOperation("getChatThreadInfo",async()=>{const t=this.getRestContextOrThrow();return eC(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=Hw(t),n=jw(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=Hw(t),n=jw(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=Hw(t),n=jw(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=Hw(t),n=jw(r.chatThreadId,"params.chatThreadId"),i=jw(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 tC(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Hw(t),n=jw(r.chatThreadId,"params.chatThreadId"),i=jw(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 rC(this.getRestClient(t),t,e)})}getClientOrThrow(){if(!this.client)throw new Zr("ChatThreadManager is not bound to client",{code:nt,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 Zr("ChatThreadManager is not bound to event context",{code:nt,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 ly(e.restBaseUrl,{errorMap:sC,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 Hr)throw r;const t=r instanceof Error?r.message:String(r);throw new Hr(`ChatThreadManager ${e} failed: ${t}`,Gr)}}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}}};nC.key="chatThreadManager";let iC=nC;class oC{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 aC=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],cC=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},dC=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),uC=e=>({userId:e}),lC=(e,t,r)=>{const s={userId:r};for(const n of aC){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},hC=async(e,t)=>{const r=cC(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,dC(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,uC(o));return s},pC=e=>Bl(e)?e:null,mC=e=>"string"==typeof e?e:void 0,fC=e=>{const t=mC(e)?.trim();return t||void 0},gC=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}},yC=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},vC=e=>{const t=pC(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},bC=e=>{const t=pC(e);return t?pC(t.data)?t.data:t:null},IC=(e,t)=>{const r=pC(e),s=r&&pC(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return gC(n[0])},wC=e=>fC(e.chatRoomId)??fC(e.chatroomid)??fC(e.id)??"",CC=e=>mC(e.name)??mC(e.title)??mC(e.groupname)??"",SC=e=>uC(e),TC=(e,t)=>{const r=pC(e);if(!r)return null;const s=wC(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)})(fC(r.owner)):fC(r.owner);return{chatRoomId:s,name:CC(r),owner:n?SC(n):void 0,memberCount:gC(r.memberCount)??gC(r.affiliations_count),disabled:yC(r.disabled)}},_C=(e,t)=>{const r=(e=>{const t=pC(e);return t?gC(t.count):void 0})(e),s=vC(e).map(e=>TC(e,t)).filter(e=>null!==e),n=IC(e,"pagenum"),i=IC(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}},RC=(e,t)=>{const r=vC(e),s=pC(r[0])??bC(e)??{},n=TC(s)??{chatRoomId:wC(s),name:CC(s)},i=((e,t)=>{if(!t)return;if(fC(e.owner)===t)return"owner";const r=Array.isArray(e.affiliations)?e.affiliations:[];for(const s of r){const e=pC(s);if(e){if(fC(e.owner)===t)return"owner";if(fC(e.admin)===t)return"admin";if(fC(e.member)===t)return"member"}}})(s,t),o=gC(s.muteExpireAt)??gC(s.mute_expire)??gC(s.expire),a=yC(s.inAllowlist)??yC(s.white)??yC(s.in_whitelist),c=yC(s.muted);return{...n,description:mC(s.description),maxMembers:gC(s.maxMembers)??gC(s.maxusers)??gC(s.max_users),createdAt:gC(s.createdAt)??gC(s.created),ext:mC(s.ext)??mC(s.custom),announcement:mC(s.announcement),permissionType:i,currentUserStatus:void 0!==a||void 0!==c||void 0!==o||void 0!==i?{inAllowlist:a,muted:c,muteExpireAt:o,permissionType:i}:void 0}},AC=e=>vC(e).map(e=>fC(e)).filter(e=>Boolean(e)).map(e=>SC(e)),MC=(e,t)=>{const r=bC(e)??{},s=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],n=pC(r.errorKeys)??{},i={};for(const[o,a]of Object.entries(n))"string"==typeof a&&(i[o]={code:UC(a),message:a});return{chatRoomId:t,appliedKeys:s,failedKeys:i}},EC=e=>{const t=pC(e),r=t?.data,s=Array.isArray(r)?r:void 0!==r?[r]:[],n=[],i=[];return s.forEach(e=>{const t=pC(e),r=(e=>{const t=pC(e);if(!t)return null;const r=fC(t.user),s=fC(t.chatRoomId)??fC(t.chatroomid)??fC(t.id),n=mC(t.action),i=yC(t.result);return r&&s&&void 0!==n&&void 0!==i?{chatRoomId:s,user:SC(r),action:n,reason:mC(t.reason),...i?{}:{reason:mC(t.reason)??"failed"}}:null})(e);if(!r||!t)return;yC(t.result)?n.push(r):i.push(r)}),{succeeded:n,failed:i}},UC=e=>e.includes("is exceeding maximum limit")||e.includes("size of metadata")&&e.includes("exceeds")?Fr:e.includes("is not part of you")?Ir:e.includes("is not Legal")||e.includes("is not exist")?nt:fr,NC=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},kC=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),OC=(e,t)=>new Zr(t,{code:it,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),xC=(e,t)=>`/${e.orgName}/${e.appName}${t}`,LC=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw OC(t,`${t} must be a string`);return e}},PC=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw OC(t,`${t} must be a number`);return e}},DC=(e,t)=>{const r=gb();"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}`:""},qC=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw kC(t);return e.trim()},BC=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw kC(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw OC(`${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 kC(t);return r},$C=(e,t)=>BC(e,t),FC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i={},o=LC(r.name,"params.name"),a=LC(r.description,"params.description"),c=PC(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 kC("params");const d=xC(s,`/chatrooms/${encodeURIComponent(n)}?resource=${s.encodedResource}`);return(e=>{const t=bC(e)??{};return{nameUpdated:yC(t.groupname),descriptionUpdated:yC(t.description),maxMembersUpdated:yC(t.maxusers)}})(await e.put(d,i,{operation:"updateChatRoomInfo"}))},GC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/chatrooms/${encodeURIComponent(n)}/users${(e=>{const t=gb();"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 vC(e)){const e=pC(n);if(!e)continue;const r=fC(e.owner),s=fC(e.admin),i=fC(e.member),o=r??s??i;o&&t.push({user:SC(o),role:r?"owner":s?"admin":"member",joinedAt:gC(e.joinedAt)??gC(e.joined_time)})}const r=pC(e),s=r?fC(r.cursor):void 0;return{items:t,cursor:s,hasMore:"string"==typeof s&&s.length>0}})(await e.get(i,{operation:"getChatRoomMemberList"}))},jC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/chatrooms/${encodeURIComponent(n)}/admin`),o=await e.get(i,{operation:"getChatRoomAdminList"});return AC(o)},zC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=gb();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=xC(s,`/chatrooms/${encodeURIComponent(n)}/mute?${i.toString()}`);return(e=>{const t=vC(e);if(t.every(e=>"string"==typeof e))return AC(e).map(e=>({user:e}));const r=[];for(const s of t){const e=pC(s);if(!e)continue;const t=fC(e.user)??fC(e.member)??fC(e.owner)??fC(e.admin);t&&r.push({user:SC(t),muteExpire:gC(e.muteExpire)??gC(e.expire)??gC(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(o,{operation:"getChatRoomMuteList"}))},KC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/sdk/chatrooms/${encodeURIComponent(n)}/mute/${s.encodedUserId}?version=v3`);return(e=>{const t=bC(e)??{};return{muted:yC(t.muted)??yC(t.value)??Boolean(t.data),muteExpireAt:gC(t.muteExpireAt)??gC(t.expire)??gC(t.mute_expire)}})(await e.get(i,{operation:"isCurrentUserMutedInChatRoom"}))},HC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=DC(r),o=i?"&":"",a=xC(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users?version=v3${o}${i.replace("?","")}`),c=await e.get(a,{operation:"getChatRoomBlocklist"});return AC(c).map(e=>({user:e}))},VC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/chatrooms/${encodeURIComponent(n)}/white/users`),o=await e.get(i,{operation:"getChatRoomAllowlist"});return AC(o).map(e=>({user:e}))},WC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${s.encodedUserId}?version=v3`);return(e=>{const t=bC(e)??{};return yC(t.value)??yC(t.white)??!1})(await e.get(i,{operation:"checkIfInChatRoomAllowList"}))},JC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/chatrooms/${encodeURIComponent(n)}/announcement`);return(e=>{const t=bC(e)??{};return{announcement:mC(t.announcement)??""}})(await e.get(i,{operation:"getChatRoomAnnouncement"}))},ZC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/metadata/chatroom/${encodeURIComponent(n)}`);return((e,t)=>{const r=bC(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(i,{keys:r.keys?$C(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),n)},QC=async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw OC(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw kC(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw OC(t,`${t} contains invalid key`);if("string"!=typeof r)throw OC(`${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=xC(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${c}`),u=await e.put(d,{metaData:i,autoDelete:o?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return MC(u,n)},YC={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},XC=(e,t,r)=>new Zr(e,{code:"required"===r?nt:it,details:{fields:[{path:t,message:e,rule:r}]}}),eS=(e,t)=>{if("string"!=typeof e)throw XC(`${t} must be a string`,t,"invalid_format");return e},tS=(e,t)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw XC(`${t} must be a string, number, or boolean`,t,"invalid_format")},rS=(e,t="attribute")=>{const r=YC[e];if(!r)throw XC(`${t} is invalid`,t,"invalid_format");return r},sS=(e,t="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw XC(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,i]of e.entries()){const e=eS(i,`${t}[${n}]`).trim();e&&(s.has(e)||(s.add(e),r.push(e)))}if(0===r.length)throw XC(`${t} is required`,t,"required");return r},nS=(e,t="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw XC(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,i]of e.entries()){const e=eS(i,`${t}[${n}]`);if(!(e in YC))throw XC(`${t}[${n}] is invalid`,`${t}[${n}]`,"invalid_format");s.has(e)||(s.add(e),r.push(e))}if(0===r.length)throw XC(`${t} is required`,t,"required");return r},iS=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/metadata/user/get`},oS=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/metadata/user/${encodeURIComponent(e.userId)}`},aS=e=>({targets:sS(e)}),cS=e=>!!Bl(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),dS=(e,t)=>{if(Array.isArray(e))for(const r of e){if(!Bl(r))continue;const e="string"==typeof r.username?r.username:"";e&&t.set(e,r)}},uS=(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},lS=(e,t)=>{const r=(e=>{const t=new Map,r=Bl(e)?e:null;if(r?.data&&Bl(r.data))for(const[s,n]of Object.entries(r.data))cS(n)&&t.set(s,n);return dS(r?.entities,t),dS(r?.data&&Bl(r.data)?r.data.entities:void 0,t),t})(e),s=(e=>{const t=new Map,r=Bl(e)?e:null;if(!r?.lastModified||!Bl(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:uS(i,e),lastModified:s.get(i)})}return n},hS=(e,t)=>lS(e,t).map(e=>e.profile),pS=(e,t,r,s)=>{void 0!==r&&("gender"!==t?e.push([t,eS(r,s)]):e.push([t,String(tS(r,s))]))},mS=e=>e.map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"),fS={onChatRoomDestroyed:Se,onMembersJoined:Te,onMembersExited:_e,onRemovedFromChatRoom:Re,onMuteListAdded:Ae,onMuteListRemoved:Me,onAllowListAdded:Ee,onAllowListRemoved:Ue,onAllMemberMuteStateChanged:Ne,onAdminAdded:ke,onAdminRemoved:Oe,onOwnerChanged:xe,onAnnouncementChanged:Le,onChatRoomInfoChanged:Pe,onAttributesUpdate:De,onAttributesRemoved:qe},gS=Gb(jb,{common:{},apis:{getChatRoomList:{range:"",errors:{}},getChatRoomInfo:{range:"705",errors:{resource_not_found:{code:705,httpStatus:404,retryable:!1}}},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,httpStatus:404,retryable:!1}}},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,httpStatus:404,retryable:!1}}},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}}}}}),yS=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=fS[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=fS[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=NC(t),n=xC(s,`/chatrooms${DC(r)}`),i=await e.get(n,{operation:"getChatRoomList"});return _C(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 Zr("chatRoomId is required",{code:nt,details:{fields:[{path:"chatRoomId",message:"chatRoomId is required",rule:"required"}]}});const r=this.chatRoomRegistry.get(t);if(r)return r;const s=new oC(t,this);return this.chatRoomRegistry.set(t,s),s}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(s,`/chatrooms/${encodeURIComponent(n)}?joined_time=true`),o=await e.get(i,{operation:"getChatRoomInfo"});return RC(o,t.userId)})(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return FC(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=qC(e.chatRoomId,"params.chatRoomId"),s=this.normalizeOptionalString(e.ext,"params.ext"),n=this.normalizeOptionalBoolean(e.leaveOtherRooms,"params.leaveOtherRooms");return(await t.sendChatRoomOperation({operation:"join",chatRoomId:r,ext:s,leaveOtherRooms:n})).chatRoomInfo??{}})}async leaveChatRoom(e){return this.runOperation("leaveChatRoom",async()=>{const t=this.requireClient(),r=qC(e.chatRoomId,"params.chatRoomId");await t.sendChatRoomOperation({operation:"leave",chatRoomId:r})})}async getMemberList(e){return this.runOperation("getMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await GC(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=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=BC(r.userIds,"params.userIds"),o=xC(s,`/chatrooms/${encodeURIComponent(n)}/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"removeChatRoomMembers"});return EC(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await jC(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=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=qC(r.userId,"params.userId"),o=xC(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=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=qC(r.userId,"params.userId"),o=xC(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 zC(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=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=BC(r.userIds,"params.userIds"),o=PC(r.duration,"params.duration"),a=xC(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=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=BC(r.userIds,"params.userIds"),o=xC(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=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(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=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=xC(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 KC(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await HC(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=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=BC(r.userIds,"params.userIds"),o=1===i.length,a=xC(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 EC(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=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=BC(r.userIds,"params.userIds"),o=xC(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"unblockChatRoomMembers"});return EC(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await VC(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=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=BC(r.userIds,"params.userIds"),o=xC(s,`/chatrooms/${encodeURIComponent(n)}/white/users?resource=${s.encodedResource}`),a=await e.post(o,{usernames:i},{operation:"addUsersToChatRoomAllowlist"});return EC(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=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=BC(r.userIds,"params.userIds"),o=xC(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"removeUsersFromChatRoomAllowlist"});return EC(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return WC(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return JC(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=LC(r.announcement,"params.announcement");if(void 0===i)throw kC("params.announcement");const o=xC(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 ZC(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await QC(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=NC(t),n=qC(r.chatRoomId,"params.chatRoomId"),i=$C(r.keys,"params.keys"),{isForced:o=!1}=r,a=o?"/forced":"",c=xC(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${a}`),d=await e.request(c,{method:"DELETE",body:{keys:i},operation:"removeChatRoomAttributes"});return MC(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 Si(`ChatRoomManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`ChatRoomManager ${e} failed: ${t.message}`,Gr):new Hr(`ChatRoomManager ${e} failed`,Gr)}checkAttributeMutationResult(e){const t=Object.values(e.failedKeys);if(t.length>0&&0===e.appliedKeys.length){const[e]=t;if(e)throw new Hr(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 ly(e.restBaseUrl,{errorMap:gS,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 Hr("ChatRoomManager is not bound to client",nt);return this.client}normalizeOptionalString(e,t){if(void 0!==e){if("string"!=typeof e)throw new Zr(`${t} must be a string`,{code:it,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 Zr(`${t} must be a boolean`,{code:it,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 hC(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 Si("ChatRoomManager user info fetch failed",{userIds:e,error:r}),[]}}})}async hydrateUserInfos(e){return(async(e,t)=>{const r=cC(e),s=await hC(r,t);return r.map(e=>lC(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 Si("ChatRoomManager hydrate users failed",{userIds:e,error:r}),[]}}})}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=aS(e),s=await this.getRestClient(t).request(iS(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return hS(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 lC(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>lC(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){Si("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:lC(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:lC(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:lC(e.owner,t.get(e.owner.userId),e.owner.userId)}}};yS.key="chatRoomManager";let vS=yS;const bS=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},IS=e=>Bl(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):[],wS=(e,t)=>{if(!Array.isArray(e.userIds)||0===e.userIds.length)throw new Zr(`${t} is required`,{code:nt,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}});const r=e.userIds.map((e,r)=>{if("string"!=typeof e)throw new Zr(`${t}[${r}] must be a string`,{code:it,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 Zr(`${t} is required`,{code:nt,details:{fields:[{path:t,message:`${t} is required`,rule:"required"}]}});return s.length!==r.length&&Bl(e),s},CS=async(e,t)=>{const r=bS(t),s=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/blocks/users`,n=await e.get(s,{operation:"getBlocklist"});return IS(n).map(e=>({userId:e}))},SS=async(e,t,r)=>{const s=bS(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:IS(i).map(e=>({userId:e})),failed:[]}},TS={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 _S=!1,RS=null;const AS=()=>RS||(_S||(Vc.util.Long=mo,Vc.configure(),_S=!0),Sd(),RS=Vc.Root.fromJSON(TS),Cd(RS),RS),MS=e=>"number"==typeof e?e:mo.isLong(e)?e.toNumber():0,ES=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:MS(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:MS(t.protocolVersion)}};class US{encodeRequest(e){const t=AS().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=rI){const t=AS().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:Yb,status:e})).finish()}decode(e){const t=AS(),r=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(r.type){case Qb:return{type:Qb};case Yb:{const r=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:Yb,status:MS(r.status)}}case eI:{const r=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:eI,header:ES(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:MS(t.createdAt),updatedAt:MS(t.updatedAt),metadataUpdatedAt:MS(t.metadataUpdatedAt)}})(e)):[],cursor:MS(r.cursor),version:"string"==typeof r.version?r.version:"",responseType:MS(r.responseType)||sI}}case tI:{const r=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:tI,header:ES(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:Zb}}}}class NS{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 Hr("Roster response requestId mismatched",Tr,{details:{stage:"response_decode",expectedRequestId:this.requestId,receivedRequestId:t}});if(this.completed)throw new Hr("Roster response received after completion",Sr,{details:{cursor:e.cursor}});if(null!==this.responseType&&this.responseType!==e.responseType)throw new Hr("Roster response type changed in same session",Sr,{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 Hr("Roster cursor duplicated",Sr,{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===nI?"incremental":"full",version:this.version,pages:this.pages}}}const kS=e=>e.type===eI,OS=e=>"message"in e&&"code"in e;class xS{constructor(e){this.codec=new US,this.sharedSession=e}async sync(e){const t=new NS(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:kS(t)||OS(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(e,r)=>{try{if(e.type===Qb)return void(await r.send(this.codec.encodePong()));if(kS(e)){if(!t.push(e).done)return;return{done:!0,result:t.buildResult()}}if(OS(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 oI:return new Jr(e.message,{code:dt,details:r(!1)});case aI:return new Hr(e.message,Fr,{details:r(!0)});case iI:return new Hr(e.message,nt,{details:r(!1)});case cI:return new Hr(e.message,it,{details:r(!1)});case dI:return new Hr(e.message,fr,{details:r(!0)});case uI:return new Hr(e.message,Cr,{details:r(!1)});default:return new Hr(e.message,Cr,{details:r(!0)})}})(e);return}catch(s){throw s instanceof Hr?s:new Hr("Roster frame decode failed",Tr,{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 LS=e=>e.versionState.version?"incremental":"full",PS=e=>{const{metadata:t,metadataFailed:r,state:s}=e,n=s.versionState.version;return r||!t?{decision:"complete"===s.cacheMeta.cacheIntegrity?LS(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}},DS=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{}}},qS=e=>{const t=(e=>{if(!(e instanceof Hr&&e.details))return null;const t=e.details.httpStatus;return"number"==typeof t?t:null})(e);return 401===t||403===t||404===t},BS=(e,t,r,s)=>({code:t,stage:e,message:`${e}: ${r}`,retryable:s}),$S=e=>{Si("Contact sync duration",e)};class FS{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=PS({metadata:s,state:e}),"skip"===r.decision)return this.dependencies.onFinish(),void $S({outcome:"skip",decision:r.decision,durationMs:Date.now()-t,version:r.version,hasUsableSnapshot:e.cachedSnapshot.complete})}catch(s){if(qS(s)){const r=PS({metadataFailed:!0,state:e}),n=s instanceof Hr?s:new Hr("Contact metadata request failed",wr,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:BS("metadata",n.code,n.message,!1)}),void $S({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=PS({metadataFailed:!0,state:e}),e.cachedSnapshot.complete)return this.dependencies.onFinish({error:BS("metadata",wr,s instanceof Error?s.message:String(s),!0)}),void $S({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 xS(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=DS(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(),$S({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 Hr?s:new Hr("Contact sync failed",Cr,{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:BS(o,n.code,n.message,!0)}),$S({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 GS={items:[],loaded:!1,source:"server"},jS=Gb(jb,{common:{},apis:{getContactList:{range:"",errors:{}},addContact:{range:"110,204,210,1000,1001,1002",localErrors:{addContact:{validation_invalid:{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}}},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,223",localErrors:{setContactRemark:{validation_invalid:{code:110,retryable:!1}}},errors:{illegal_argument:{code:223,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:{}}}}),zS=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=GS,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=GS,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(),n=this.getRestClient(s);Ci("ContactManager addContact",{userId:t,hasMessage:"string"==typeof r&&r.length>0}),await(async(e,t,r)=>{const s=bS(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/apply?resource=${s.encodedResource}`;await e.post(n,{usernames:[r.userId],reason:r.message??""},{operation:"addContact"})})(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);Ci("ContactManager deleteContact",{userId:t}),await(async(e,t,r)=>{const s=bS(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);Ci("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);Ci("ContactManager acceptContactInvite",{userId:t}),await(async(e,t,r)=>{const s=bS(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);Ci("ContactManager declineContactInvite",{userId:t}),await(async(e,t,r)=>{const s=bS(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);Ci("ContactManager setContactRemark",{userId:t,remarkLength:r.length}),await(async(e,t,r)=>{const s=bS(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"),Ci("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 CS(t,e));return this.blocklistSnapshot={items:r,loaded:!0,source:"server"},Ci("ContactManager getBlocklist",{count:r.length}),r})}async addUsersToBlocklist(e){return this.runOperation("addUsersToBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const r=wS(e,"params.userIds"),s=this.getRestClient(t);Ci("ContactManager addUsersToBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length});const n=await SS(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=wS(e,"params.userIds"),s=this.getRestClient(t);Ci("ContactManager removeUserFromBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length}),await(async(e,t,r)=>{const s=bS(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 Si(`ContactManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`ContactManager ${e} failed: ${t.message}`,Gr):new Hr(`ContactManager ${e} failed`,Gr)}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 ly(e.restBaseUrl,{errorMap:jS,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=GS)}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)?it:nt;return new Zr(e,{code:r,details:{fields:t}})}async enrichBlocklistUsers(e){if(0===e.length||!this.requireClient().isUserInfoSyncEnabled())return e;const t=await Vb(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 Si("ContactManager user info fetch failed",{userIds:e,error:t}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=aS(e),s=await this.getRestClient(t).request(iS(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return hS(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 FS(e)}};zS.key="contactManager";let KS=zS;class HS{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 VS=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},WS=e=>new Zr(`${e} is required`,{code:nt,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),JS=(e,t)=>new Zr(t,{code:it,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),ZS=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw WS(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw JS(`${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 WS(t);return r},QS=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw WS(t);return e.trim()},YS=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw JS(t,`${t} must be a string`);return e}},XS=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw JS(t,`${t} must be a boolean`);return e}},eT=(e,t)=>`/${e.orgName}/${e.appName}${t}`,tT=new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),rT=e=>{const t=gb();"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}`:""},sT=async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups?resource=${s.encodedResource}`);return(e=>{const t=Ql(e),r=Hl(t[0]),s=Yl(e)??r;return{groupId:s&&th(s)||r&&th(r)||""}})(await e.post(n,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?ZS(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"}))},nT=async(e,t,r)=>{const s=VS(t),n=QS(r.groupId,"params.groupId"),i=eT(s,`/chatgroups/${encodeURIComponent(n)}?joined_time=true&version=v3`),o=await e.get(i,{operation:"getGroupInfo"});return sh(o)},iT=async(e,t,r)=>{const s=VS(t),n=QS(r.groupId,"params.groupId"),i={},o=YS(r.name,"params.name"),a=YS(r.description,"params.description"),c=YS(r.avatar,"params.avatar"),d=YS(r.ext,"params.ext"),u=XS(r.public,"params.public"),l=XS(r.joinApprovalRequired,"params.joinApprovalRequired"),h=XS(r.allowInvites,"params.allowInvites"),p=XS(r.inviteNeedConfirm,"params.inviteNeedConfirm"),m=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw JS(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 WS("params");const f=eT(s,`/chatgroups/${encodeURIComponent(n)}?resource=${s.encodedResource}&version=v3`);await e.put(f,i,{operation:"updateGroupInfo"})},oT=async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/users${(e=>{const t=gb();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 Ql(e)){const e=Hl(i);if(!e)continue;const r=Wl(e.owner),s=Wl(e.admin),n=Wl(e.member),o=r??s??n;if(!o)continue;const a=Jl(e.joinedAt)??Jl(e.joined_time);t.push({user:nh(o),role:r?"owner":s?"admin":"member",...void 0===a?{}:{joinedAt:a}})}const r=Xl(e,"pagenum"),s=Xl(e,"pagesize"),n=eh(e,s);return{items:t,pageNum:r,pageSize:s,...void 0===n?{}:{hasMore:n}}})(await e.get(n,{operation:"getGroupMemberList"}))},aT=async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/admin`),i=await e.get(n,{operation:"getGroupAdminList"});return ih(i)},cT=async(e,t,r)=>{const s=VS(t),n=QS(r.groupId,"params.groupId"),i=rT(r),o=i?"&":"",a=eT(s,`/chatgroups/${encodeURIComponent(n)}/mute?version=v3${o}${i.replace("?","")}`);return(e=>{const t=[];for(const r of Ql(e)){const e=Wl(r);if(e){t.push({user:nh(e)});continue}const s=Hl(r);if(!s)continue;const n=Wl(s.user);if(!n)continue;const i=Jl(s.expire);t.push({user:nh(n),...void 0===i?{}:{muteExpire:i}})}return t})(await e.get(a,{operation:"getGroupMuteList"}))},dT=async(e,t,r)=>{const s=VS(t),n=QS(r.groupId,"params.groupId"),i=rT(r),o=i?"&":"",a=eT(s,`/chatgroups/${encodeURIComponent(n)}/blocks/users?version=v3${o}${i.replace("?","")}`),c=await e.get(a,{operation:"getGroupBlocklist"});return ih(c).map(e=>({user:e}))},uT=async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/white/users`),i=await e.get(n,{operation:"getGroupAllowlist"});return ih(i).map(e=>({user:e}))},lT=async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=Yl(e)??{};return{announcement:Vl(t.announcement)??""}})(await e.get(n,{operation:"getGroupAnnouncement"}))},hT=async(e,t,r)=>{const s=VS(t),n=gb();n.set("pagenum",String(r.pageNum??1)),n.set("pagesize",String(r.pageSize??20));const i=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/share_files?${n.toString()}`);return(e=>{const t=Xl(e,"pagenum"),r=Xl(e,"pagesize"),s=eh(e,r);return{items:Ql(e).map(e=>oh(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===s?{}:{hasMore:s}}})(await e.get(i,{operation:"getGroupSharedFileList"}))},pT=(e,t)=>{const r=VS(e);return eT(r,`/chatgroups/${encodeURIComponent(QS(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(QS(t.fileId,"params.fileId"))}`)},mT=async(e,t,r)=>{const s=VS(t),n=QS(r.groupId,"params.groupId"),i=QS(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(!tT.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=eT(s,`/sdk/chatgroups/${encodeURIComponent(n)}/nameCard`);return await e.put(t,o,{operation:"setGroupMemberAttributes"})}const a=eT(s,`/sdk/metadata/chatgroup/${encodeURIComponent(n)}/user/${encodeURIComponent(i)}?resource=${s.encodedResource}`);return await e.put(a,{metaData:r.memberAttributes},{operation:"setGroupMemberAttributes"})},fT=async(e,t,r)=>{const s=VS(t),n=eT(s,`/sdk/metadata/chatgroup/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/get`);return(e=>{const t=Yl(e)??{},r=Hl(t.data)??t,s={};for(const[n,i]of Object.entries(r)){const e=Hl(i);e&&(s[n]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:s}})(await e.post(n,{targets:ZS(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},gT=e=>{const t=Bl(e)?e:{},r=t.data,s=Bl(r)?r.data:void 0,n=Array.isArray(r)?r:Array.isArray(s)?s:null;if(Array.isArray(n))return yT(n);const i=Bl(r)?r:t,o=Bl(i.namecards)?i.namecards:i,a={};for(const[c,d]of Object.entries(o)){if("string"==typeof d){a[c]={namecard:d};continue}if(!Bl(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:vT(d)})}return a},yT=e=>{const t={};return e.forEach(e=>{if(!Bl(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:vT(e)})}),t},vT=e=>Hh("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),bT=e=>{if(Bl(e))return Hh("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 IT{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 wT=e=>({...e}),CT=e=>({...e,owner:e.owner?{...e.owner}:void 0});class ST{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=wT({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=CT({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=wT(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?wT(this.summarySnapshot):this.detailSnapshot?wT(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?CT(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 TT{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 _T{constructor(){this.groups=new Map,this.joinedGroupById=new Map,this.removedJoinedGroupIds=new Set,this.snapshotMapper=new TT,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 ST(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 RT=0,AT=5,MT=12,ET=13,UT=0,NT=1,kT=2,OT=0,xT=1,LT=2,PT=3,DT=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===UT?"owner":s===NT?"admin":s===kT?"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===OT?"DEFAULT":r===xT?"ALL":r===LT?"AT":r===PT?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,s},qT=e=>e.updatedAt??0,BT=(e,t)=>{if(!e)return!0;return qT(t)>=qT(e)},$T={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 FT=null,GT=!1;const jT=()=>FT||(GT||(Vc.util.Long=mo,Vc.configure(),GT=!0),Sd(),FT=Vc.Root.fromJSON($T),Cd(FT),FT),zT=e=>jT().lookupType(e),KT=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(mo.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}},HT=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:KT(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:KT(t.protocol_version)??KT(t.protocolVersion)??0}};class VT{constructor(){this.requestType=zT("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=zT("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=zT("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:RT}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=KT(t.type);return r!==MT?null:{type:r,header:HT(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:KT(t.last_sync_time)??KT(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=KT(t.type);return r!==ET?null:{type:r,header:HT(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:KT(t.members_count)??KT(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:KT(t.role),mute_expiration:KT(t.mute_expiration)??KT(t.muteExpiration),remind_type:KT(t.remind_type)??KT(t.remindType),create_at:KT(t.create_at)??KT(t.createAt),update_at:KT(t.update_at)??KT(t.updateAt),joined_timestamp:KT(t.joined_timestamp)??KT(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:KT(t.last_sync_finished_ts)??KT(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=KT(t.type);return r!==AT?null:{type:r,header:HT(t.header),code:KT(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class WT{constructor(e){this.batches=[],this.done=!1,this.requestId=e}getResumeCursor(){return this.latestCursor}push(e){if(e.type!==ET)return{done:!1};const t=e.header?.requestId;if(t!==this.requestId)return{done:!1};if(this.done)throw new Hr("Joined groups response received after completion",fr,{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 Hr("Joined groups final batch missing lastSyncFinishedTs",fr,{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 JT=e=>e.type===ET,ZT=e=>e.type===AT;class QT{constructor(e){this.codec=new VT,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new WT(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:JT(t)||ZT(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(JT(e)){if(!r.push(e).done)return;return{done:!0,result:r.buildResult()}}if(ZT(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 Hr(e.message,nt,{details:t("request_send",!1)});case 1602:return new Hr(e.message,fr,{details:t("batch_merge",!0)});case 1002:return new Jr(e.message,{code:dt,details:t("auth",!1)});case 1003:return new Hr(e.message,Fr,{details:t("server_limit",!0)});default:return new Hr(e.message,fr,{details:t("response_decode",!0)})}})(e);return}catch(t){throw t instanceof Hr?t:new Hr("Joined groups frame decode failed",Tr,{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 YT{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 Hr("Group sync websocket urls are unavailable",Cr,{details:{stage:"socket_connect",retryable:!0}});const s=this.buildRequest(),n=await new QT(this.dependencies.getSharedSyncSession()).sync({urls:r,request:s}),i=n.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=DT(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);BT(e,n)?r.set(n.groupId,{...e??{},...n,groupId:n.groupId}):e&&r.set(n.groupId,{...e})}const s=r.size>=Of;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:Of,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 Xr("Joined-group preview persistence failed",{details:{stage:"preview_persist",cause:t instanceof Error?t.message:String(t)}})}Si("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 Hr?e:new Hr("Group sync failed",fr,{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);Si("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}=Qn(e.appKey);return{type:MT,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:t,app:r,username:e.userId,lastSyncTime:0}}}const XT=Gb(jb,{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:{}}}}),e_=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 _T,this.groupEventSync=new IT(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!==we)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 sT(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 Zr("groupId is required",{code:nt,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 HS(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 nT(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=VS(t),n=ZS(r.groupIds,"params.groupIds"),i=eT(s,`/chatgroups/${n.map(e=>encodeURIComponent(e)).join(",")}?joined_time=true&version=v3`),o=await e.get(i,{operation:"getGroupInfoList"});return(Bl(o)&&Array.isArray(o.data)?o.data:[]).map(e=>sh({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===ne?this.resolveLocalGroupName(r.groupId):void 0,n=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(await this.syncRuntimeForEvent(e,r,n),e){case Q:return{groupId:r.groupId,groupName:r.groupName,inviter:this.pickEventUser(r.inviterId,n),reason:r.reason};case Y:return{groupId:r.groupId,groupName:r.groupName,applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case X:return{groupId:r.groupId,groupName:r.groupName,accepter:this.pickEventUser(r.accepterId,n)};case ee:return{groupId:r.groupId,groupName:r.groupName,decliner:this.pickEventUser(r.declinerId,n),applicant:this.pickEventUser(r.applicantId,n),reason:r.reason};case te:case re:return{groupId:r.groupId,invitee:this.pickEventUser(r.inviteeId,n),reason:r.reason};case se:return{groupId:r.groupId,groupName:r.groupName};case ne:return{groupId:r.groupId,groupName:r.groupName??s};case ie:return{groupId:r.groupId,inviter:this.pickEventUser(r.inviterId,n),inviteMessage:r.reason};case oe:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n),muteExpire:r.muteExpire};case ae:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,n)};case ce:case de:return{groupId:r.groupId,allowlist:this.pickEventUsers(r.userIds,n)};case ue:return{groupId:r.groupId,isMuted:Boolean(r.isMuted)};case le:case he:return{groupId:r.groupId,administrator:this.pickEventUser(r.administratorId,n)};case pe:return{groupId:r.groupId,newOwner:this.pickEventUser(r.newOwnerId,n),oldOwner:this.pickEventUser(r.oldOwnerId,n)};case me: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 ge:return{groupId:r.groupId,announcement:r.announcement??""};case ye:return{groupId:r.groupId,sharedFile:this.hydrateEventSharedFile(r.sharedFile,n)};case ve:return{groupId:r.groupId,fileId:r.fileId??""};case be:return{groupId:r.groupId,groupInfo:await this.resolveGroupDetailForEvent(r)};case Ie:{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 we: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){Si("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 iT(this.getRestClient(t),t,e)})}async changeGroupOwner(e){return this.runOperation("changeGroupOwner",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}?resource=${s.encodedResource}`);await e.put(n,{newowner:QS(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/invite?resource=${s.encodedResource}`);await e.post(n,{usernames:ZS(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:QS(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:QS(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(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 oT(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=VS(t),n=ZS(r.userIds,"params.userIds"),i=eT(s,`/chatgroups/${encodeURIComponent(QS(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 aT(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(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 cT(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/mute?resource=${s.encodedResource}`);await e.post(n,{usernames:ZS(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=VS(t),n=ZS(r.userIds,"params.userIds"),i=eT(s,`/chatgroups/${encodeURIComponent(QS(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(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 dT(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/blocks/users?resource=${s.encodedResource}`);await e.post(n,{usernames:ZS(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=VS(t),n=ZS(r.userIds,"params.userIds"),i=eT(s,`/chatgroups/${encodeURIComponent(QS(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 uT(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/white/users?resource=${s.encodedResource}`);await e.post(n,{usernames:ZS(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=VS(t),n=ZS(r.userIds,"params.userIds"),i=eT(s,`/chatgroups/${encodeURIComponent(QS(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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),i=await e.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof i?i:Bl(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=VS(t),n=eT(s,`/sdk/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),i=await e.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof i?i:Bl(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 lT(this.getRestClient(t),t,e)})}async updateGroupAnnouncement(e){return this.runOperation("updateGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(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 hT(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=pT(t,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),s=Gn({file:e.file}),n=nm({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}`,[Ml]:Al()},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 Hr("uploadGroupSharedFile failed",mr,{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=ll(o);throw i?.finish({code:t.code,success:!1,description:t.message}),n?.finish({code:t.code,success:!1,description:t.message}),t.code===$r&&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=VS(t),n=eT(s,`/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(QS(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}${pT(s,e)}`;t=nm({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 Hr("downloadGroupSharedFile request adapter is unavailable",hr);const o=await i.request({url:n,method:"GET",headers:{Authorization:`Bearer ${s.token}`,...e.secret?{"Share-Secret":e.secret}:{},[Ml]:Al()},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 Hr("downloadGroupSharedFile failed",mr);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 Hr?s.code:hr,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 mT(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return fT(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=VS(t),n=eT(s,`/sdk/chatgroups/${encodeURIComponent(QS(r.groupId,"params.groupId"))}/nameCard/batch/get`),i=await e.post(n,{members:ZS(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:gT(i),responseTimestamp:bT(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&&Si("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 Si(`GroupManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`GroupManager ${e} failed: ${t.message}`,Gr):new Hr(`GroupManager ${e} failed`,Gr)}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new ly(e.restBaseUrl,{errorMap:XT,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 Hr("GroupManager is not bound to client",nt);return this.client}getGroupRepository(){return this.groupRepository||(this.groupRepository=new _T),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new IT(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 nT(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 Si("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&&Si("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=Hh("number"==typeof s?s:Number(s));if("number"==typeof e)return e}}collectUpdateTimeCandidates(e,t,r){if(!Bl(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(Bl(s)){this.collectUpdateTimeCandidates(s,t,r);const e=s[t];Bl(e)&&this.collectUpdateTimeCandidates(e,t,r)}const n=e.lastModified??e.last_modified;Bl(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 Kl(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 Si("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 zl(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>zl(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:zl(e.fileOwner,t.get(e.fileOwner.userId),e.fileOwner.userId)}:e}async syncRuntimeForEvent(e,t,r){switch(e){case ue:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{muteAllMembers:Boolean(t.isMuted)}});case pe:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{owner:this.pickEventUser(t.newOwnerId,r)}});case X:case ie:return void this.addCurrentUserJoinedGroupFromEvent(t);case me:{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 se:case ne:return void(await this.removeJoinedGroupLocal(t.groupId));case oe:case ae:case ce:case de:case le:case he:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});default:return}}getMemberEventDeltaCount(e,t){switch(e){case me: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 Si("Joined group detail enrichment skipped",{groupId:e.groupId,error:s}),!1}try{return await this.enrichJoinedGroupFromDetail(e.groupId,t,r)}catch(s){return Si("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 nT(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 Si("Joined group preview persistence failed",{error:r})}"function"==typeof t.flushPending&&t.flushPending().catch(e=>{Si("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=aS(e),s=await this.getRestClient(t).request(iS(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return hS(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(MI(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),s=await LI({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 xI({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 YT(e)}};e_.key="groupManager";let t_=e_;const r_=Gb(jb,{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}}}}}),s_=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};Ci("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};Ci("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`;Ci("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}`;Ci("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};Ci("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 Si(`PresenceManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof Hr?t:t instanceof Error?new Hr(`PresenceManager ${e} failed: ${t.message}`,Gr):new Hr(`PresenceManager ${e} failed`,Gr)}getEventContextOrThrow(){if(!this.eventContext)throw new Zr("PresenceManager is not bound to event context",{code:nt,details:{fields:[{path:"presenceManager.eventContext",message:"PresenceManager is not bound to event context",rule:"required"}]}});return this.eventContext}getClientOrThrow(){if(!this.client)throw new Zr("PresenceManager is not bound to client",{code:nt,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 ly(e.restBaseUrl,{errorMap:r_,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 Zr("Invalid parameters",{code:it,details:{fields:e}})}};s_.key="presenceManager";let n_=s_;const i_=Gb(jb,{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,1500",localErrors:{uploadPushToken:{validation_invalid:{code:110,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}}}}}),o_=["singleChat","groupChat"],a_=["ALL","AT","NONE","DEFAULT"],c_=["ALL","AT","NONE"],d_=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),u_=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null}bind(e,t){this.client=e}async uploadPushToken(e){return this.runOperation(async()=>{this.validateUploadPushTokenParams(e);const t=this.getRestContextOrThrow(),r=this.getRestClient(t),{orgName:s,appName:n}=this.parseAppKey(t.appKey),i=`/${s}/${n}/users/${t.userId}`;Ci("Call uploadPushToken",{deviceId:e.deviceId,notifierName:e.notifierName}),await r.request(i,{method:"PUT",body:{device_id:e.deviceId,device_token:e.deviceToken,notifier_name:e.notifierName},operation:"uploadPushToken"})})}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);Ci("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}`;Ci("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);Ci("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)}`;Ci("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)}`;Ci("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}`;Ci("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`;Ci("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`;Ci("Call getPushLanguage");const i=await t.request(n,{method:"GET",operation:"getPushLanguage"});return{language:this.resolvePushLanguage(i,"")}})}getConversationListByRemindType(e){return this.runOperation(()=>{Ci("Call getConversationListByRemindType",{pageSize:e.pageSize,hasCursor:Boolean(e.cursor)});const t=this.getClientOrThrow(),r=Vg({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 Hr?e:e instanceof Error?new Hr(`PushManager operation failed: ${e.message}`,Gr):new Hr("PushManager operation failed",Gr)}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 ly(e.restBaseUrl,{errorMap:i_,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 Hr("PushManager is not bound to client",nt);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||!o_.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(!d_(e))throw this.buildValidationError(`${t} must be an object`,[{path:t,message:`${t} must be an object`,rule:"invalid_format"}]);switch(e.mode){case"REMIND_TYPE":if(!c_.includes(e.remindType))throw this.buildValidationError("rule.remindType is invalid",[{path:`${t}.remindType`,message:"remindType must be one of ALL/AT/NONE",rule:"invalid_format"}]);this.ensureNoConflictFields(e,t,["mode","remindType"]);break;case"DURATION":if(!Number.isInteger(e.duration)||e.duration<=0)throw this.buildValidationError("rule.duration must be a positive integer",[{path:`${t}.duration`,message:"duration must be a positive integer",rule:"range"}]);this.ensureNoConflictFields(e,t,["mode","duration"]);break;case"INTERVAL":this.validateTimePoint(e.startTime,`${t}.startTime`),this.validateTimePoint(e.endTime,`${t}.endTime`),this.ensureNoConflictFields(e,t,["mode","startTime","endTime"]);break;default:throw this.buildValidationError("rule.mode is invalid",[{path:`${t}.mode`,message:"mode must be one of REMIND_TYPE/DURATION/INTERVAL",rule:"invalid_format"}])}}ensureNoConflictFields(e,t,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(!d_(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(!d_(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(d_(e.data)){const r=e.data[t];if(d_(r))return r}const r=e[t];return d_(r)?r:{}}resolveSilentModeRuleSource(e){if(!d_(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return d_(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":a_.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(d_(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 Zr(e,{code:it,details:{fields:t}})}};u_.key="pushManager";let l_=u_;const h_=e=>{const{orgName:t,appName:r}=Qn(e.appKey);return`/${t}/${r}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},p_=(e,t="params.userIds")=>sS(e,t),m_=e=>{const t=p_(e);if(t.length>100)throw((e,t,r,s=it)=>new Zr(e,{code:s,details:{fields:[{path:t,message:e,rule:r}]}}))("params.userIds must contain at most 100 unique users","params.userIds","range",Fr);return{usernames:t}},f_=(e,t)=>{const r=(e=>p_(e))(t);return`${h_(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},g_=(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}},y_=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],v_=Gb(jb,{common:{},apis:{updateOwnUserInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfo:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},resource_not_found:{code:204,httpStatus:404,retryable:!1},rate_limit:{code:4,httpStatus:429,retryable:!0}}},updateOwnInfoByAttribute:{range:"4,110,204,901",localErrors:{updateOwnInfo:{validation_invalid:{code:110,retryable:!1}},updateOwnInfoByAttribute:{validation_invalid:{code:110,retryable:!1}}},errors:{data_length_exceed:{code:901,httpStatus:403,retryable:!1},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}}}}}),b_=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=g_(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 Ci("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=aS(sS(e.userIds,"params.userIds")),n=iS(t);Ci("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),o.map(e=>e.profile)})}async getUserInfoByAttribute(e){return this.runOperation("getUserInfoByAttribute",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(n=sS(e.userIds,"params.userIds"),i=nS(e.attributes,"params.attributes"),{targets:sS(n),properties:nS(i).map(e=>rS(e,"params.attributes"))});var n,i;const o=iS(t);Ci("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),c.map(e=>e.profile)})}async subscribeUsersInfo(e){return this.runOperation("subscribeUsersInfo",async()=>{const t=this.getRestContextOrThrow(),r=this.getRestClient(t),s=(e=>h_(e))(t),n=m_(e.userIds);Ci("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=f_(t,e.userIds);Ci("UserInfoManager unsubscribeUsersInfo",{userIds:sS(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=>h_(e))(e);Ci("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(pS(t,"nickname",e.nickname,"params.nickname"),pS(t,"avatarurl",e.avatarUrl,"params.avatarUrl"),pS(t,"mail",e.mail,"params.mail"),pS(t,"phone",e.phone,"params.phone"),pS(t,"gender",e.gender,"params.gender"),pS(t,"sign",e.sign,"params.sign"),pS(t,"birth",e.birth,"params.birth"),pS(t,"ext",e.ext,"params.ext"),0===t.length)throw XC("params must include at least one updatable field","params","required");return mS(t)})(e),n=oS(t);Ci("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=rS(e,"attribute"),s=tS(t,"value");if("gender"!==r&&"string"!=typeof s)throw XC("value must be a string","value","invalid_format");return mS([[r,String(s)]])})(e,t),i=oS(r);Ci("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 Hr?t:(Si("UserInfoManager operation failed",{operation:e,message:t instanceof Error?t.message:String(t)}),new Hr(`${e} failed`))}getRestContextOrThrow(){if(this.client)return this.client.getRestContext();throw new Zr("UserInfoManager is not bound to client",{code:nt,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 ly(e.restBaseUrl,{errorMap:v_,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 lS(e,t)}normalizeUpdateEnvelope(e,t,r){const s=Bl(e)?e:null,n=(s&&Bl(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!!Bl(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 y_)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return y_.filter(t=>t in e)}projectToSummary(e){const t=Date.now(),r=Hh(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)}};b_.key="userInfoManager";let I_=b_;return e.AuthenticationError=Jr,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=sg,e.ChatClient=pI,e.ChatManager=Bw,e.ChatRoom=oC,e.ChatRoomManager=vS,e.ChatThread=$w,e.ChatThreadManager=iC,e.ConnectionError=Wr,e.ContactManager=KS,e.Group=HS,e.GroupManager=t_,e.ImageType={ORIGINAL:"original",LARGE:"large"},e.MessageReceiveError=Yr,e.MessageSendError=Qr,e.NetworkError=Vr,e.PresenceManager=n_,e.PushManager=l_,e.RUNTIME_PLATFORMS=Mi,e.RestBusinessError=ts,e.RestTransportError=es,e.SDKError=Hr,e.StorageError=Xr,e.StreamMessageStatus=rt,e.UploadError=rs,e.UserInfoManager=I_,e.ValidationError=Zr,e.createPlatformAdapter=ul,e.detectRuntimePlatform=(e,t)=>co(t,e).platform,e.isSDKError=function(e){if(e instanceof Hr)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.setLogLevel=function(e){yi instanceof gi&&yi.setLevel(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",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=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ru=e=>{const t=Array.isArray(e.contents)?e.contents[0]:void 0;return tu(t)?t:void 0};class su{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,ru(e))};for(const[a,c]of Object.entries(o))void 0!==c&&Object.assign(i,{[a]:c});return o.chatThread&&(i.isChatThread=!0),tu(e.msgConfig)&&e.msgConfig.allowGroupAck&&(i.needReadReceipt=!0),i}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}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:""}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(!tu(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(!tu(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(!tu(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(!tu(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=tu(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.userId?"SEND":"RECEIVE";return{msgServerId:r,msgLocalId:"",from:i,to:o,sender:{userId:i},conversationId:h,conversationType:"groupChat",type:u,sendStatus:"sent",ext:tu(n?.ext)?n.ext:{},timestamp:s,body:l,direct:p}}resolveThreadLastMessagePayload(e){const t=e.payload;if(tu(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:tu(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 tu(e)?e:null}catch{return null}}if(tu(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return tu(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(tu).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 nu=(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""},iu=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,ou="X-Request-Id",au=new Set(["mute"]),cu={name:"name",title:"name",description:"description",max_users:"maxMembers",custom:"ext",mute:"muteAllMembers"},du=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},uu=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},lu=(e,t)=>{const r=e?.map(e=>du(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},hu=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=uu(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},pu=e=>{const t=uu(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(au.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},mu=e=>{const t=uu(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:du(t.operator)??du(t.username)}},fu=(e,t)=>({eventName:e,payload:t}),gu=e=>{const t={chatRoomId:e.chatRoomId,chatRoomName:e.chatRoomName},r=du(e.from?.name),s=(n=e.to,du(n?.[0]?.name));var n;switch(e.operation){case 1:return fu(qe,t);case 10:return fu(Ve,{...t,reason:e.reason,reasonCode:Number.isFinite(Number(e.reason))?Number(e.reason):0,participantId:s??r});case 17:return fu($e,{...t,memberIds:lu(e.members,r),ext:e.ext??e.eventExt});case 18:return fu(je,{...t,memberIds:lu(e.members,r)});case 20:return fu(Ye,{...t,oldOwnerId:r,newOwnerId:s});case 21:return fu(Qe,{...t,adminId:s??r});case 22:return fu(Ze,{...t,adminId:s??r});case 23:{const r=(e=>{const t=uu(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):lu(e.members,s),i=46388736e5;return fu(Ke,{...t,userIds:n,muteMembers:r??Object.fromEntries(n.map(e=>[e,i])),muteExpire:hu(e.reason,e.eventExt)??i})}case 24:return fu(ze,{...t,userIds:lu(e.members,s)});case 25:return fu(Xe,{...t,announcement:e.reason??""});case 26:return fu(Xe,{...t,announcement:""});case 29:return fu(He,{...t,userIds:lu(e.members,s)});case 30:return fu(We,{...t,userIds:lu(e.members,s)});case 31:return fu(Je,{...t,isMuted:!0});case 32:return fu(Je,{...t,isMuted:!1});case 14:return fu(et,{...t,shouldFetchChatRoomDetail:!0,chatRoomPatch:pu(e.eventExt)});case 43:{const s=mu(e.eventExt);return fu(rt,{...t,attributes:s.attributes,from:s.from??r})}case 44:{const s=mu(e.eventExt);return fu(st,{...t,keyList:s.keyList,from:s.from??r})}default:return null}},yu=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),vu=(e,t)=>{if(!e)return t;try{return JSON.parse(e)}catch{return t}},Iu=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],bu=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),_u=e=>({userId:e}),Tu=(e,t,r)=>{const s={userId:r};for(const n of Iu){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},Cu=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,bu(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,_u(o));return s},Su=e=>yu(e)?e:null,Eu=e=>{if("string"==typeof e)return e},wu=e=>{const t=Eu(e)?.trim();return t||void 0},Ru=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}},Au=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},Nu=e=>{const t=Su(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},Ou=e=>{const t=Su(e);return t?Su(t.data)?t.data:t:null},Mu=(e,t)=>{const r=Su(e),s=r&&Su(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return Ru(n[0])},Uu=(e,t)=>{const r=(e=>{const t=Su(e);return t?Ru(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},Lu=e=>wu(e.groupId)??wu(e.groupid)??wu(e.id)??"",ku=e=>Eu(e.name)??Eu(e.groupname)??Eu(e.groupName)??"",Du=e=>{const t=Nu(e),r=Su(t[0])??Ou(e)??{},s=(e=>{const t=Su(e);if(!t)return null;const r=Lu(t);return r?{groupId:r,name:ku(t),description:Eu(t.description),memberCount:Ru(t.memberCount)??Ru(t.affiliations_count),public:Au(t.public),joinApprovalRequired:Au(t.joinApprovalRequired)??Au(t.approval)??Au(t.membersonly)??Au(t.members_only),allowInvites:Au(t.allowInvites)??Au(t.allowinvites)??Au(t.allow_user_invites),maxMembers:Ru(t.maxMembers)??Ru(t.maxusers),role:wu(t.role)??wu(t.permission),disabled:Au(t.disabled)}:null})(r)??{groupId:Lu(r),name:ku(r)},n=wu(r.owner)??wu(r.admin)??wu(r.member),i=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>Su(e)).filter(e=>null!==e).map(e=>Ru(e.joined_time)).find(e=>void 0!==e);return{...s,owner:n?_u(n):void 0,inviteNeedConfirm:Au(r.inviteNeedConfirm)??Au(r.invite_need_confirm),muteAllMembers:Au(r.mute),ext:Eu(r.ext)??Eu(r.custom),createdAt:Ru(r.createdAt)??Ru(r.created),joinedAt:i,avatarUrl:Eu(r.avatar),messageBlocked:Au(r.messageBlocked)??Au(r.isMessageBlocked)??Au(r.shieldgroup)}},Pu=e=>_u(e),xu=e=>Nu(e).map(e=>wu(e)).filter(e=>Boolean(e)).map(e=>Pu(e)),Fu=e=>{const t=Su(e);if(!t)return null;const r=wu(t.fileId)??wu(t.file_id);if(!r)return null;const s=Eu(t.fileName)??Eu(t.file_name)??r,n=wu(t.fileOwner)??wu(t.file_owner);return{fileId:r,fileName:s,fileOwner:n?Pu(n):void 0,fileSize:Ru(t.fileSize)??Ru(t.file_size),createdAt:Ru(t.createdAt)??Ru(t.created)}},Bu=new Set(["public","members_only","allow_user_invites","invite_need_confirm"]),Gu={name:"name",title:"name",description:"description",public:"public",members_only:"joinApprovalRequired",allow_user_invites:"allowInvites",max_users:"maxMembers",invite_need_confirm:"inviteNeedConfirm",custom:"ext"},qu=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},$u=e=>{if(!e)return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch{return null}},ju=(e,t)=>{const r=e?.map(e=>qu(e)).filter(e=>"string"==typeof e)??[];return r.length>0?r:t?[t]:[]},Vu=(e,t)=>{const r=Number(e);if(!Number.isNaN(r)&&Number.isFinite(r)&&r>0)return r;const s=$u(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},Ku=e=>{const t=$u(e);if(!t)return;const r={};for(const[s,n]of Object.entries(t)){const e=Gu[s];if(!e)continue;let t=n;if(Bu.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},zu=(e,t)=>{const r=$u(t)??$u(e);return Fu(r??void 0)??void 0},Hu=(e,t)=>{const r=$u(t)??$u(e);return qu(r?.fileId)??qu(r?.file_id)??qu(e)??""},Wu=(e,t)=>({eventName:e,payload:t}),Ju=e=>{const t={groupId:e.groupId,groupName:e.groupName},r=qu(e.from?.name),s=(n=e.to,qu(n?.[0]?.name));var n;switch(e.operation){case 4:return Wu(X,{...t,applicantId:r,reason:e.reason});case 5:return Wu(ee,{...t,accepterId:r});case 6:return Wu(te,{...t,declinerId:r,applicantId:s,reason:e.reason});case 7:return Wu(Y,{...t,inviterId:r,reason:e.reason});case 8:return Wu(re,{...t,inviteeId:r,reason:e.reason});case 9:return Wu(se,{...t,inviteeId:r,reason:e.reason});case 10:return Wu(ne,t);case 1:return Wu(ie,t);case 19:return Wu(oe,{...t,inviterId:r,reason:e.reason});case 23:{const r=(e=>{const t=$u(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=qu(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):ju(e.members,s);return Wu(ae,{...t,userIds:n,muteExpire:n.map(e=>r?.[e]).find(e=>void 0!==e)??Vu(e.reason,e.eventExt)})}case 24:return Wu(ce,{...t,userIds:ju(e.members,s)});case 29:return Wu(de,{...t,userIds:ju(e.members,s)});case 30:return Wu(ue,{...t,userIds:ju(e.members,s)});case 31:return Wu(le,{...t,isMuted:!0});case 32:return Wu(le,{...t,isMuted:!1});case 21:return Wu(he,{...t,administratorId:s??r});case 22:return Wu(pe,{...t,administratorId:s??r});case 20:return Wu(me,{...t,oldOwnerId:r,newOwnerId:s});case 17:{const s=ju(e.members,r);return Wu(fe,{...t,memberIds:s})}case 18:{const s=ju(e.members,r);return Wu(ge,{...t,memberIds:s})}case 25:return Wu(ye,{...t,announcement:e.reason??""});case 26:return Wu(ye,{...t,announcement:""});case 27:return Wu(ve,{...t,sharedFile:zu(e.reason,e.eventExt)});case 28:return Wu(Ie,{...t,fileId:Hu(e.reason,e.eventExt)});case 14:return Wu(be,{...t,shouldFetchGroupDetail:!0,groupPatch:Ku(e.eventExt)});case 41:return Wu(_e,{...t,shouldFetchGroupDetail:!0,isDisabled:!0});case 42:return Wu(_e,{...t,shouldFetchGroupDetail:!0,isDisabled:!1});case 45:{const s=(e=>{const t=$u(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:qu(t.username),attribute:s}})(e.eventExt);return Wu(Te,{...t,userId:s.userId,attribute:s.attribute,from:r,source:e.source??"direct"})}default:return null}},Qu=new WeakMap,Zu=(e,t)=>{Qu.set(e,t)},Yu=e=>Qu.get(e)??null,Xu=(e,t)=>{const r=Yu(e);r&&Zu(t,r)},el=new WeakMap,tl=e=>el.get(e),rl=new WeakMap,sl=e=>rl.get(e),nl=(e,t)=>{const r=rl.get(e);r&&rl.set(t,r)},il="singleChat",ol="groupChat",al=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}},dl=e=>{if(!Array.isArray(e))return;const t=e.map(e=>al(e)).filter(e=>"string"==typeof e);return t.length>0?t:void 0},ul=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ll=(...e)=>{for(const t of e){const e=al(t);if(e)return e}},hl=(e,t)=>Boolean(e&&t&&e===t),pl=(e,t,r)=>Boolean(e&&e===r.userId&&t&&r.clientResource&&t!==r.clientResource),ml=(e,t,r)=>{const s=dl(e);if(s&&s.length>0)return s;const n=(t??[]).map(e=>al(e.name)).filter(e=>"string"==typeof e);if(n.length>0)return n;const i=al(r?.name);return i?[i]:[]},fl=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}}},gl=(e,t)=>{const r=ll(e.to?.[0]?.clientResource);if(1!==e.to?.length||al(e.to[0]?.name)!==t.userId||!pl(t.userId,r,t))return null;const s=(n=e.from,al(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}},yl=(e,t)=>{if(!e.groupId)return Vs("Discarded MultiDevice group event without groupId",{operation:e.operation}),null;const r=ll(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!pl(al(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=ml(e.members,e.to,e.from);return{category:"group",operation:s,groupId:e.groupId,userIds:n.length>0?n:void 0,operatorId:al(e.from?.name),groupName:e.groupName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},vl=(e,t)=>{if(!e.threadId)return Vs("Discarded MultiDevice thread event without threadId",{operation:e.operation}),null;const r=ll(e.from?.clientResource,e.raw?.resource,e.raw?.clientResource);if(!pl(al(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=ml(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:al(e.from?.name),threadName:e.threadName,deviceId:r,timestamp:e.timestamp,raw:e.raw}},Il=(e,t)=>{if("pin"===e.operation||"pin_delete"===e.operation)return null;const r=ll(e.res,e.raw?.resource,e.raw?.clientResource);if(hl(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?il:ol;var n;const i=al(e.id)??(s===il?al(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?fl(e.ext):void 0,operatorId:al(e.from),deviceId:r,timestamp:cl(e.ts),raw:e.raw}},bl=(e,t)=>{const r=ll(e.resource,e.raw?.resource,e.raw?.clientResource);if(hl(r,t.clientResource))return js("Discarded same-device MultiDevice roaming delete echo",{conversationId:e.to}),null;const s=al(e.to);if(!s)return Vs("Discarded MultiDevice roaming delete event without conversationId",{}),null;const n=al(e.lastMsgId),i=dl(e.msgIdList)??(n?[n]:void 0),o=cl(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?ol:il,messageIds:i,beforeTimestamp:o,deviceId:r,raw:e.raw}},_l=e=>{switch(e){case"contact":return"onMultiDeviceContact";case"group":return"onMultiDeviceGroup";case"thread":return"onMultiDeviceThread";case"conversation":return"onMultiDeviceConversation";case"messageRemoved":return"onMultiDeviceMessageRemoved"}},Tl=2147483647,Cl=e=>{const t=Number(e);if(!Number.isFinite(t)||t<=0)return;const r=Math.floor(t);return r<=0||r>Tl?void 0:r},Sl=e=>{if("number"!=typeof e||!Number.isFinite(e)||e<=0)return;const t=e>Tl?Math.floor(e/1e3):Math.floor(e);return Cl(t)};var El=4096,wl=65547,Rl=15,Al=2113929216,Nl=65536,Ol=65536,Ml=10485760,Ul={MANUAL:0,AUTO_IMMEDIATE:1,AUTO_THRESHOLD:2},Ll={SUCCESS:0,FAILED:-1,NOT_INITIALIZED:-2,INITIALIZED_FAILED:-3,COMPRESS_FAILED:-4,DECOMPRESS_FAILED:-5,PARAM_ERROR:-6,BUFFER_RESIZE_FAILED:-7};function kl(e){if(!(e>0))return Ol;if(e<=Ol)return Ol;if(e>1073741823)return e;for(var t=Ol;t<e;)t*=2;return t}var Dl={byU16:0,byU32:1},Pl=0,xl=1,Fl=2,Bl=0,Gl=1;function ql(e,t){return e[t]|e[t+1]<<8}function $l(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function jl(e,t,r){e[t]=255&r,e[t+1]=r>>>8&255}var Vl="fast";function Kl(e){return 2654435761*(e>>>0)>>>20&4095}function zl(e){return 2654435761*(e>>>0)>>>19&8191}function Hl(e,t,r){if("fast"===Vl){var s=$l(e,t);return r===Dl.byU16?zl(s):Kl(s)}throw new Error("Unsupported hash strategy: "+Vl)}function Wl(e,t,r,s,n){r[t]=e-n}function Jl(e,t,r,s,n){Wl(t,Hl(e,t,s),r,0,n)}function Ql(e,t,r,s){return t[e]+s}function Zl(e,t,r,s,n){return Ql(Hl(e,t,s),r,0,n)}function Yl(e,t,r,s){for(var n=t;t<s-3;){if($l(e,t)!==$l(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 Xl(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>Al)return 0;switch(c){case Pl:default:u=s,l=s;break;case xl:u=s-e.currentOffset,l=s-e.dictSize;break;case Fl:u=s-e.currentOffset,l=s}if(a===Dl.byU16&&n>=wl)return 0;if(n<13)return rh(t,r,b,_,S,E,o);Jl(t,m,p,a,u),h=Hl(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 rh(t,r,b,_,S,E,o);R=Ql(U,p,0,u),c===Fl&&(R<s?(w=I,l=y):(w=0,l=s)),h=Hl(t,N,a),Wl(m,U,p,0,u)}while(d===Gl&&R<f||a!==Dl.byU16&&R+65535<m||!eh(t,g,m,R,w,c,s));for(;m>b&&R+w>l;){var L=R+w-1;if(t[m-1]!==(c===Fl&&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>=Rl){var D=k-Rl;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(jl(r,S,m-R),S+=2,c===Fl&&R<s){var F=m+(v-(R+w));if(F>C&&(F=C),(m+=4+(x=th(t,g,m+4,R+w+4-y+e.dictionaryStart,F,v-y)))===F&&F<C){var B=Yl(t,m,s,C);x+=B,m+=B}}else m+=4+(x=Yl(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(Jl(t,m-2,p,a,u),R=Zl(t,m,p,a,u),c===Fl&&(R<s?(w=I,l=y):(w=0,l=s)),Jl(t,m,p,a,u),!((d!==Gl||R>=f)&&R+65535>=m&&eh(t,g,m,R,w,c,s)))break t;r[A=S++]=0}h=Hl(t,++m,a)}return rh(t,r,b,_,S,E,o)}function eh(e,t,r,s,n,i,o){var a,c=$l(e,r);i===Fl&&s+n<o?a=$l(t,s+n):a=$l(e,s+n);return c===a}function th(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 rh(e,t,r,s,n,i,o){var a=s-r;if(o&&n+a+1+Math.floor((a+255-Rl)/255)>i)return 0;if(a>=Rl){for(t[n++]=240,a-=Rl;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 sh(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 nh(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)===Rl){var S=sh(e,R={ip:p},m-Rl,!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=ql(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=sh(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===Fl&&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 ih(){return{hashTable:new Uint32Array(El),currentOffset:0,initCheck:0,dictionary:null,dictionaryStart:0,dictSize:0,bufferStart:null}}function oh(e){e.hashTable.fill(0),e.currentOffset=0,e.initCheck=0,e.dictionary=null,e.dictionaryStart=0,e.dictSize=0,e.bufferStart=null}function ah(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?Gl:Bl;return e.dictionary&&c===s?(u=Xl(e,t,r,s,n,o||0,a||!1,Dl.byU32,xl,h),e.dictSize+=n,e.currentOffset+=n,u):(u=Xl(e,t,r,s,n,o||0,a||!1,Dl.byU32,Fl,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 dh(){return{externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}function uh(e,t,r,s){return e.prefixSize=s,e.prefixEnd=r+s,e.externalDict=null,e.extDictStart=0,e.extDictSize=0,1}function lh(e,t,r,s,n,i,o){var a;if(e.prefixEnd===i){if((a=nh(t,r,s,n,i,o,!0,0,0,Fl,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=nh(t,r,s,n,i,o,!0,0,0,Fl,i,e.extDictStart,e.extDictSize))<=0)return a;e.prefixSize=a,e.prefixEnd=i+a}return a}function hh(e){var t=(e=e||{}).minWorkArea||Ol,r=e.maxWorkArea||Ml,s=e.shrinkThreshold||t;t<Ol&&(t=Ol),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Nl+t,this.maxBufferSize=Nl+r,this.shrinkThreshold=Nl+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Ul.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.stream=ih()}function ph(e){var t=(e=e||{}).minWorkArea||Ol,r=e.maxWorkArea||Ml,s=e.shrinkThreshold||t;t<Ol&&(t=Ol),r<t&&(r=t),s<t&&(s=t),s>r&&(s=r),this.minBufferSize=Nl+t,this.maxBufferSize=Nl+r,this.shrinkThreshold=Nl+s,this.ringBufferSize=this.minBufferSize,this.shrinkMode=void 0!==e.shrinkMode?e.shrinkMode:Ul.MANUAL,this.ringBuffer=new Uint8Array(this.ringBufferSize),this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}}hh.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Nl?this.offset:Nl,n=this.offset>Nl?this.offset-Nl: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},hh.prototype.compress=function(e,t){var r=e.length;if(r<=0)return Ll.PARAM_ERROR;if(r>this.maxBufferSize-Nl)return Ll.PARAM_ERROR;if(r>this.ringBufferSize-Nl){var s=kl(r),n=Nl+s;if(n>this.maxBufferSize&&(n=this.maxBufferSize),!this._resizeBuffer(n))return Ll.BUFFER_RESIZE_FAILED}this.offset+r>this.ringBufferSize&&(ch(this.stream,this.ringBuffer,0,Nl),this.offset=Nl);var i=this.offset;this.ringBuffer.set(e,i);var o=ah(this.stream,this.ringBuffer,t,i,r,0,t.length,!0);return o<=0?Ll.COMPRESS_FAILED:(this.offset+=r,this._tryAutoShrink(),o)},hh.prototype.reset=function(){this.offset=0,oh(this.stream)},hh.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},hh.prototype._tryAutoShrink=function(){this.shrinkMode!==Ul.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Ul.AUTO_IMMEDIATE||this.shrinkMode===Ul.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},hh.prototype.getWorkArea=function(){return this.ringBufferSize-Nl},hh.prototype.getRingBufferSize=function(){return this.ringBufferSize},hh.prototype.getBaseBufferSize=function(){return this.minBufferSize},hh.prototype.getMaxBufferSize=function(){return this.maxBufferSize},hh.prototype.getCurrentOffset=function(){return this.offset},hh.prototype.getShrinkMode=function(){return this.shrinkMode},hh.prototype.setShrinkMode=function(e){this.shrinkMode=e},hh.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},hh.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Nl,r=this.maxBufferSize-Nl;if(e<t||e>r)return Ll.PARAM_ERROR;this.shrinkThreshold=Nl+e},ph.prototype._resizeBuffer=function(e){var t=new Uint8Array(e),r=0;if(this.offset>0){var s=this.offset<Nl?this.offset:Nl,n=this.offset>Nl?this.offset-Nl:0;t.set(this.ringBuffer.subarray(n,n+s),0),r=s,uh(this.streamDecode,0,0,s)}return this.ringBuffer=t,this.ringBufferSize=e,this.offset=r,!0},ph.prototype.decompress=function(e,t,r){var s=e.length;if(s<=0||r<=0)return Ll.PARAM_ERROR;if(r>this.maxBufferSize-Nl)return Ll.PARAM_ERROR;if(r>this.ringBufferSize-Nl){var n=kl(r),i=Nl+n;if(i>this.maxBufferSize&&(i=this.maxBufferSize),!this._resizeBuffer(i))return Ll.BUFFER_RESIZE_FAILED}if(this.offset+r>this.ringBufferSize){var o=this.offset-Nl;o>0&&this.ringBuffer.set(this.ringBuffer.subarray(o,o+Nl),0),uh(this.streamDecode,this.ringBuffer,0,Nl),this.offset=Nl}var a=lh(this.streamDecode,e,this.ringBuffer,0,s,this.offset,r);return a<=0?Ll.DECOMPRESS_FAILED:(t.set(this.ringBuffer.subarray(this.offset,this.offset+a),0),this.offset+=a,this._tryAutoShrink(),a)},ph.prototype.reset=function(){this.offset=0,this.streamDecode={externalDict:null,extDictStart:0,extDictSize:0,prefixEnd:0,prefixSize:0}},ph.prototype.shrink=function(){this.ringBufferSize>this.minBufferSize&&this._resizeBuffer(this.minBufferSize)},ph.prototype._tryAutoShrink=function(){this.shrinkMode!==Ul.MANUAL&&(this.ringBufferSize<=this.minBufferSize||(this.shrinkMode===Ul.AUTO_IMMEDIATE||this.shrinkMode===Ul.AUTO_THRESHOLD&&this.ringBufferSize>this.shrinkThreshold)&&this.shrink())},ph.prototype.getWorkArea=function(){return this.ringBufferSize-Nl},ph.prototype.getRingBufferSize=function(){return this.ringBufferSize},ph.prototype.getBaseBufferSize=function(){return this.minBufferSize},ph.prototype.getMaxBufferSize=function(){return this.maxBufferSize},ph.prototype.getCurrentOffset=function(){return this.offset},ph.prototype.getShrinkMode=function(){return this.shrinkMode},ph.prototype.setShrinkMode=function(e){this.shrinkMode=e},ph.prototype.getShrinkThreshold=function(){return this.shrinkThreshold},ph.prototype.setShrinkThreshold=function(e){var t=this.minBufferSize-Nl,r=this.maxBufferSize-Nl;if(e<t||e>r)return Ll.PARAM_ERROR;this.shrinkThreshold=Nl+e};const mh={LZ4_MAX_INPUT_SIZE:Al,BLOCK_MAX_SIZE:65536,DICT_SIZE:Nl,DEFAULT_WORK_AREA:Ol,DEFAULT_MAX_WORK:Ml,SHRINK_MODE:Ul,LZ4_ERROR:Ll,alignToPowerOf2:kl,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".');Vl=e},getHashStrategy:function(){return Vl},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>Al)return 0;if(0===s)return t.length>n?(t[n]=0,1):0;var i=s<wl?Dl.byU16:Dl.byU32;return Xl({hashTable:new Uint32Array(i===Dl.byU16?8192:El),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,0,!1,i,Pl,Bl)},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>Al)return 0;if(i<1)return 0;if(0===s)return t[n]=0,1;var o=s<wl?Dl.byU16:Dl.byU32;return Xl({hashTable:new Uint32Array(o===Dl.byU16?8192:El),currentOffset:0,dictSize:0,dictionary:null,dictionaryStart:0},e,t,r,s,i,!0,o,Pl,Bl)},compressBound:function(e){return e<0||e>Al?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:nh(e,t,r,s,n,i,!0,0,0,Pl,n,null,0))},decompressFast:function(e,t,r,s,n){return nh(e,t,r=r||0,0,s=s||0,n,!1,0,0,xl,s-65536,0,65536)},createStream:ih,resetStream:oh,loadDict:function(e,t,r,s){if(e.initCheck&&oh(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;)Jl(t,i,e.hashTable,Dl.byU32,n),i+=3;return s},compressContinue:ah,saveDict:ch,createStreamDecode:dh,setStreamDecode:uh,decompressSafeContinue:lh,RingBufferEncoder:hh,RingBufferDecoder:ph,_hashU16:zl,_hashU32:Kl,_TABLE_TYPE:Dl},fh=268435455,gh=new Uint32Array(256);let yh=!1;function vh(e){!function(){if(!yh){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;gh[e]=t>>>0}yh=!0}}();let t=4294967295;for(let r=0;r<e.length;r+=1){const s=e[r]??0;t=t>>>8^(gh[255&(t^255&s)]??0)}return(4294967295^t)>>>0}var Ih=(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))(Ih||{});const bh=268435455;class _h{constructor(){this.mode=-1,this.enableUplinkCompression=!1,this.enableDownlinkCompression=!1;const e={minWorkArea:mh.DEFAULT_WORK_AREA,maxWorkArea:mh.DEFAULT_MAX_WORK,shrinkMode:mh.SHRINK_MODE.MANUAL};this.encoder=new mh.RingBufferEncoder(e),this.decoder=new mh.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>bh)throw new Error(`Data size exceeds maximum allowed: ${t.length}`);const r=mh.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>fh)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=vh(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>bh)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=vh(o);if(c!==n)throw new Error(`CRC32 checksum mismatch: expected ${n}, got ${c}`);return o}reset(){this.encoder.reset(),this.decoder.reset()}}const Th=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ch=(e,t)=>ka(e,t).finish();class Sh{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.payloadDecoder=new su(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=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=Ch(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:iu()};return Ch(r,i)}encodeHeartbeat(){const e=Kd(),t=e.lookupType("easemob.pb.CommUnreadUL"),r=e.lookupType("easemob.pb.MSync"),s=Ch(t,{}),n={version:0,encryptType:[sr],command:Tt,payload:s,traceId:iu()};return Ch(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=Ch(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=Ch(s,a);return Ch(n,{version:0,encryptType:[sr],command:_t,payload:c,traceId:iu()})}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(Th):void 0),n=Th(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.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: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(!Th(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(!Th(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=gl({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=vl({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=yl({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?gu({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}):Ju({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&&el.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:Th(s.data)?s.data:s}}]}if("conv"===n){const e=Th(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=Il({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=Th(s.data)?s.data:s,t=bl({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(!ul(s))continue;const e=ll(s.operator_resource,s.resource,s.clientResource);if(hl(e,t.clientResource))continue;const n=al(s.group)??al(s.user);if(!n||!ul(s.data))continue;const i=al(s.group)?ol:il,o=s.data;r.push({category:"conversation",operation:"CONVERSATION_MUTE_INFO_CHANGED",conversationId:n,conversationType:i,remindType:al(o.type),silentMode:o,deviceId:e,raw:s})}return r})(Th(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:_l(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=Ch(r,{queue:e}),i={version:0,encryptType:[sr],command:_t,payload:n,traceId:iu()};return Ch(s,i)}encodeLastSession(e,t){const r=Kd(),s=r.lookupType("easemob.pb.CommSyncUL"),n=r.lookupType("easemob.pb.MSync"),i=Ch(s,{queue:e,key:t}),o={version:0,encryptType:[sr],command:_t,payload:i,traceId:iu()};return Ch(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=Ch(s,{meta:i}),a={version:0,encryptType:[sr],command:_t,payload:o,traceId:iu()};return Ch(n,a)}encodeCombineMessageMeta(e){const t=Kd().lookupType("easemob.pb.Meta"),r=Zd(e.msgServerId||e.msgLocalId),s=this.buildChatMeta(e,r,!0);return Ch(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=Ch(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=Ch(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=Ch(n,{meta:l}),p={version:0,encryptType:[sr],command:_t,payload:h,traceId:iu()};return Ch(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=Ch(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=Ch(n,{meta:c}),u={version:0,encryptType:[sr],command:_t,payload:d,traceId:iu()};return Ch(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(!Th(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(!Th(e)||!Th(e.status))continue;const r=e.status.chatroomInfo;if("string"!=typeof r||""===r)continue;const s=JSON.parse(r);if(!Th(s))continue;const i=s[this.context.userId];if(!Th(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.resolveProfileVersionTime(t.userInfoUpdateTime),v=this.resolveProfileVersionTime(t.namecardUpdateTime),I=this.payloadDecoder.decodeMetadata(t,n,c,e.meta),b={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)};Zu(b,{userInfoUpdateTime:y,namecardUpdateTime:v});const _=I.stream;return _&&(b.type="text",b.body={content:_.fullText},b.stream=_),void 0!==f&&(b.isBroadcast=f),void 0!==g&&(b.priority=g),Object.assign(b,I),b}resolveMessageProfileVersionFields(e){const t=Yu(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 Cl(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}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:sl(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){return this.payloadDecoder.decodeContent(e)}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=nu(t.from,e.from),o=nu(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 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"}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 _h);const r=this.resolveCompressionMode(t);this.compressor.mode=r,this.compressor.enableUplinkCompression=r===Ih.UPLINK_ONLY||r===Ih.BIDIRECTIONAL,this.compressor.enableDownlinkCompression=r===Ih.DOWNLINK_ONLY||r===Ih.BIDIRECTIONAL}resolveCompressionMode(e){return 0===e?Ih.UPLINK_ONLY:1===e?Ih.DOWNLINK_ONLY:2===e?Ih.BIDIRECTIONAL:Ih.NONE}disableCompression(){this.compressor&&(this.compressor.mode=Ih.NONE,this.compressor.enableUplinkCompression=!1,this.compressor.enableDownlinkCompression=!1)}}const Eh=1e3,wh="direct";class Rh{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 Ah{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 Nh={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},Oh=()=>{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 Mh{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??Oh;const t=new Ah({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 Rh({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:Nh[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??wh,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??wh,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 Uh;const Lh=e=>{Uh?.updateSession(e)},kh=e=>{Uh?.applyDnsSwitch(e)},Dh=e=>{Uh?.updateNetworkType(e)},Ph=e=>{if("disabled"!==Uh?.state)return Uh?.startOperation(e)},xh=()=>{Uh?.reset(),Uh=void 0},Fh=e=>new ht("Connection attempt cancelled",{code:ot.CONNECTION_CANCELLED,details:{stage:e,cancelled:!0,retryable:!0}}),Bh=e=>e instanceof ht&&e.code===ot.CONNECTION_CANCELLED&&!0===e.details?.cancelled;class Gh{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 Sh({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?.(Fh("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=Fh("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(Bh(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(!Bh(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=Fh(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(Fh("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(Fh("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=Ph({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 qh=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()}},$h=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},jh=()=>{const e=fn().crypto;return e&&"function"==typeof e.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},Vh=new Uint8Array([99,109]),Kh=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),zh=e=>Array.isArray(e)&&e.every(Kh),Hh=e=>"string"==typeof e?e:void 0,Wh=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Jh=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},Qh=(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},Zh=e=>{let t=0;for(let r=2;r<e.length;r+=1)r%2==1&&(t^=e[r]??0);return t},Yh=(e,t)=>{const r=Kd().lookupType(e).decode(t);if(!Kh(r))throw new Error(`${e} decoded result is invalid`);return r},Xh=e=>Kh(e)&&"string"==typeof e.name?e.name:"",ep=(e,t,r)=>{const s=(zh(e.contents)?e.contents:[])[0];if(!s)throw new Error("MessageBody contents is empty");const n=(e=>{const t=Wh(e.type)??Dt,r=Boolean(Hh(e.remotePath))||Boolean(Hh(e.title))||Boolean(Hh(e.summary))||(Wh(e.combineLevel)??0)>0,s=t===Dt&&0===e.subType&&r;if(t===jt||s){const t=Wh(e.combineLevel)??0;return{type:"combine",body:{title:Hh(e.title)??"",summary:Hh(e.summary)??"",filename:Hh(e.displayName)??"combine",filetype:"application/octet-stream",url:Hh(e.remotePath),secret:Hh(e.secretKey),fileLength:Wh(e.fileLength),combineLevel:t},combineLevel:t}}if(t===Dt)return{type:"text",body:{content:Hh(e.text)??""}};if(t===qt)return{type:"cmd",body:{action:Hh(e.action)??""}};if(t===$t){const t=eu(zh(e.customExts)?e.customExts:void 0);return{type:"custom",body:{event:Hh(e.customEvent)??"",params:t}}}if(t===Ft)return{type:"location",body:{latitude:Wh(e.latitude)??0,longitude:Wh(e.longitude)??0,address:Hh(e.address),buildingName:Hh(e.buildingName)}};if(t===Pt){const t=Kh(e.size)?e.size:{},r=Hh(e.remotePath)??"",s=Ts(r),n=Hh(e.thumbnailRemotePath),i=Ss(e.imageType)===hs;return{type:"image",body:{localUrl:"",filename:Hh(e.displayName)??"image",filetype:"application/octet-stream",width:Wh(t.width)??0,height:Wh(t.height)??0,isGif:1===e.subType,isOriginalImage:i,originalImageUrl:s.originalImageUrl,bigImageUrl:s.bigImageUrl,secret:Hh(e.secretKey),fileLength:Wh(e.fileLength),thumbnailUrl:n??s.thumbnailUrl}}}if(t===xt){const t=Kh(e.size)?e.size:{};return{type:"video",body:{url:Hh(e.remotePath)??"",filename:Hh(e.displayName)??"video",filetype:"application/octet-stream",duration:Wh(e.duration)??0,width:Wh(t.width),height:Wh(t.height),secret:Hh(e.secretKey),fileLength:Wh(e.fileLength),thumbnailUrl:Hh(e.thumbnailRemotePath)}}}if(t===Bt)return{type:"voice",body:{url:Hh(e.remotePath)??"",filename:Hh(e.displayName)??"voice",filetype:"application/octet-stream",duration:Wh(e.duration)??0,secret:Hh(e.secretKey),fileLength:Wh(e.fileLength)}};if(t===Gt)return{type:"file",body:{url:Hh(e.remotePath)??"",filename:Hh(e.displayName)??"file",filetype:"application/octet-stream",secret:Hh(e.secretKey),fileLength:Wh(e.fileLength)}};return null})(s);if(!n)throw new Error("MessageBody content type is unsupported");const i=Xh(e.from)||Xh(r?.from)||`unknown-${t}`,o=Xh(e.to)||Xh(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(zh(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},tp=(e,t)=>{const r=[];try{const n=Yh("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=Yh("easemob.pb.MessageBody",i);return ep(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=Yh("easemob.pb.MessageBody",e);return ep(r,t)}catch(n){r.push(n instanceof Error?n.message:String(n))}try{const r=Yh("easemob.pb.MessageBody.Content",e);return ep({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("; "))},rp=(e,t)=>{const r=Hs(e);try{const e=JSON.parse(r);if(!Kh(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 tp(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)}})}}},sp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),np=(e,t,r)=>{throw new mt(e,{code:r,details:{fields:[{path:t,message:e,rule:"invalid_format"}]}})},ip=e=>{if("combine"!==e.type)return 0;const t=e.combineLevel;return"number"==typeof t?t:sp(e.body)&&"number"==typeof e.body.combineLevel?e.body.combineLevel:0},op=(e,t)=>{if(e.sender.userId||np(`messageList[${t}] sender.userId is required`,`messageList[${t}].sender.userId`,ot.COMBINE_INVALID_INPUT),e.conversationId&&["singleChat","groupChat","chatRoom"].includes(e.conversationType)||np(`messageList[${t}] conversation is invalid`,`messageList[${t}].conversationId`,ot.COMBINE_INVALID_INPUT),(!Number.isInteger(e.timestamp)||e.timestamp<=0)&&np(`messageList[${t}] timestamp must be positive integer`,`messageList[${t}].timestamp`,ot.COMBINE_INVALID_INPUT),sp(e.body)||np(`messageList[${t}] body must be object`,`messageList[${t}].body`,ot.COMBINE_INVALID_INPUT),"combine"===e.type){const r=ip(e);(!Number.isInteger(r)||r<0)&&np(`messageList[${t}] combineLevel is invalid`,`messageList[${t}].combineLevel`,ot.COMBINE_INVALID_INPUT),r>10&&np(`messageList[${t}] combineLevel exceeds limit`,`messageList[${t}].combineLevel`,ot.COMBINE_LEVEL_EXCEEDED)}},ap=(e,t=300)=>{(!Number.isInteger(e)||e<=0)&&np("messageList must not be empty","messageList",ot.COMBINE_INVALID_INPUT),(!Number.isInteger(t)||t<=0||t>300)&&np("max items is invalid","maxItems",ot.COMBINE_INVALID_INPUT),e>t&&np(`messageList max length is ${t}`,"messageList",ot.COMBINE_ITEM_LIMIT_EXCEEDED)},cp=e=>{ap(e.length);for(let t=0;t<e.length;t+=1){const r=e[t];void 0!==r?op(r,t):np(`messageList[${t}] is required`,`messageList[${t}]`,ot.COMBINE_INVALID_INPUT)}},dp=e=>{let t=0;for(const r of e){if("combine"!==r.type)continue;const e=ip(r);e>t&&(t=e)}return t+1},up=e=>{(!Number.isInteger(e)||e<=0)&&np("combineLevel must be positive integer","combineLevel",ot.COMBINE_INVALID_INPUT),e>10&&np("combineLevel must be <= 10","combineLevel",ot.COMBINE_LEVEL_EXCEEDED)},lp=e=>"groupChat"===e?1:"chatRoom"===e?2:0;class hp{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"};Xu(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"};Xu(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 Xu(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:lp(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:lp(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??[];cp(r);const s=dp(r);up(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=Vh.length+r.reduce((e,t)=>e+4+t.length,0)+1,n=new Uint8Array(s);let i=0;n.set(Vh,i),i+=Vh.length;for(const e of r){const t=Jh(e.length);n.set(t,i),i+=t.length,n.set(e,i),i+=e.length}const o=Zh(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=$h(o);if(!a&&!this.attachmentUploader)throw new ft("Combine payload local url generation failed",{code:ot.COMBINE_ENCODE_FAILED});qh.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 Xu(e,c),nl(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};Xu(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||qh.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"};Xu(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)>=Eh){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=Ph({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<Eh&&(this.messageReportSaturated=!1)):(this.chatRoomReportCount=Math.max(0,this.chatRoomReportCount-1),this.chatRoomReportCount<Eh&&(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 mp{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 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 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 gp=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);class yp{constructor(e,t,r){this.eventHub=r,this.messageSender=t,this.msyncCodec=e,this.streamMessageHandler=new mp(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{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(!gp(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(!gp(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(!gp(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(!gp(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(!gp(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(!gp(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(!gp(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(!gp(e.data))return;const t=e.data;if("string"!=typeof t.messageId||"string"!=typeof t.conversationId||"string"!=typeof t.conversationType||!gp(t.message)||"string"!=typeof t.message.type||!gp(t.message.body)||!gp(t.message.ext))return;const r={type:t.message.type,body:this.normalizeUpdatedMessageBody(t.message.type,t.message.body),ext:t.message.ext,...gp(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)gp(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)!gp(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 vp=()=>{const e=globalThis;return"function"==typeof e.fetch?e.fetch:void 0},Ip=()=>oc({fetchImpl:vp()})??{request:e=>Promise.reject(dn("Request capability is missing for current platform.",{code:sn,stage:Zs,retryable:!1,details:{capability:"request"}}))},bp=e=>e??Ip(),_p=e=>e instanceof Error?e.message:String(e);class Tp{constructor(e){this.requestAdapter=bp(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;ap(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:{[ou]:iu()}});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<Vh.length+1)throw new gt("Combine payload is too short",{code:ot.COMBINE_PARSE_FAILED});const t=e.subarray(0,Vh.length);if(t[0]!==Vh[0]||t[1]!==Vh[1])throw new gt("Combine payload header is invalid",{code:ot.COMBINE_PARSE_FAILED});const r=e.subarray(0,e.length-1),s=Zh(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=Vh.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=Qh(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=rp(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 ap(n.length,r),cp(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:_p(n),url:s}})}}}const Cp=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"}},Sp=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 Ep{constructor(e){this.requestAdapter=bp(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:{[ou]:iu()}})}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:Cp(e),mimeType:Sp(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 wp=(e,t,r)=>({Authorization:`Bearer ${e}`,Accept:t,[ou]:iu(),...r??{}}),Rp=async e=>{const t=wp(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},Ap=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:wp(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}})}},Np=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=>bp(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 Rp({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=Ap({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 Rp({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},Op=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}`,[ou]:iu()},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))}},Mp=Lc(),Up=e=>Object.prototype.toString.call(e),Lp=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:Up(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}},kp=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}),Dp=e=>"image"===e||"video"===e||"voice"===e||"file"===e||"combine"===e,Pp=e=>"object"==typeof e&&null!==e,xp=(e,t)=>{const r=Pp(t)?t:void 0,s=r?.code===sn&&r.stage===tn;return"miniapp-path"===e&&(e=>{if(!Pp(e))return!1;const t=Pp(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 Fp{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(!Dp(e.type))return e;const r=e.body;if(this.hasUploadedRemoteResource(e.type,r))return e;const s=this.resolveUploadUrl(e.type,r),n=qh.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:Lp(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=Ph({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:kp(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:kp(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:kp(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:kp(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:kp(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(!Dp(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(xp(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:kp(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:kp(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"}),Mp;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(bp(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(!Dp(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(!Dp(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:kp(t.fileInfo),multipartEnabled:a,uploadMode:c?"multipart":"simple"}),c)try{return await Np(o)}catch(d){const e=d instanceof bt?d.details:void 0;if(e&&"object"==typeof e&&"init"===e.stage)return Op(o);throw d}return this.config.uploadAdapter?(Vs("Attachment upload adapter selected",{operation:"upload.adapter.selected",messageType:n,source:kp(t.fileInfo),adapter:"platform",hasUploadAdapter:!0}),this.uploadByAdapter(this.config.uploadAdapter,e,t,i,r)):Op(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(!Dp(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}`,[ou]:iu()},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:kp(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 Xu(e,n),nl(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 Xu(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 Xu(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 Xu(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 Xu(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(!xp(t.md5FileInfo.source.sourceType,n))throw n;Vs("Attachment upload continues without md5",{operation:"upload.md5.unavailable",messageType:e,source:kp(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 Bp{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 Gp="__internal:core";class qp{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 Gh({...e,socketAdapter:e.socketAdapter??e.platformAdapter?.socket},this.eventHub);const r=this.connectionManager.getMsyncCodec(),s=e.restBaseUrl?new Fp({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 hp(r,null,this.eventHub,s),this.messageReceiver=new yp(r,this.messageSender,this.eventHub),e.enableDeliveryReceipt&&this.messageReceiver.setDeliveryAckEnabled(!0),this.combineMessageDownloader=new Tp(e.platformAdapter?.request),this.attachmentDownloader=new Ep(e.platformAdapter?.request),this.connectionManager.setMessageReceiver(this.messageReceiver),this.platformAdapter=e.platformAdapter??null,this.setupEventHandlers(),this.registerNetworkListeners()}setupEventHandlers(){this.eventHub.addEventHandler(Gp,{[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 Bp(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(Gp),qh.clear()}}var $p,jp,Vp;(jp=$p||($p={})).assertEqual=e=>{},jp.assertIs=function(e){},jp.assertNever=function(e){throw new Error},jp.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},jp.getValidEnumValues=e=>{const t=jp.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(const s of t)r[s]=e[s];return jp.objectValues(r)},jp.objectValues=e=>jp.objectKeys(e).map(function(t){return e[t]}),jp.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},jp.find=(e,t)=>{for(const r of e)if(t(r))return r},jp.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,jp.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},jp.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(Vp||(Vp={})).mergeShapes=(e,t)=>({...e,...t});const Kp=$p.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),zp=e=>{switch(typeof e){case"undefined":return Kp.undefined;case"string":return Kp.string;case"number":return Number.isNaN(e)?Kp.nan:Kp.number;case"boolean":return Kp.boolean;case"function":return Kp.function;case"bigint":return Kp.bigint;case"symbol":return Kp.symbol;case"object":return Array.isArray(e)?Kp.array:null===e?Kp.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?Kp.promise:"undefined"!=typeof Map&&e instanceof Map?Kp.map:"undefined"!=typeof Set&&e instanceof Set?Kp.set:"undefined"!=typeof Date&&e instanceof Date?Kp.date:Kp.object;default:return Kp.unknown}},Hp=$p.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 Wp 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 Wp))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$p.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()}}Wp.create=e=>new Wp(e);const Jp=(e,t)=>{let r;switch(e.code){case Hp.invalid_type:r=e.received===Kp.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Hp.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,$p.jsonStringifyReplacer)}`;break;case Hp.unrecognized_keys:r=`Unrecognized key(s) in object: ${$p.joinValues(e.keys,", ")}`;break;case Hp.invalid_union:r="Invalid input";break;case Hp.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${$p.joinValues(e.options)}`;break;case Hp.invalid_enum_value:r=`Invalid enum value. Expected ${$p.joinValues(e.options)}, received '${e.received}'`;break;case Hp.invalid_arguments:r="Invalid function arguments";break;case Hp.invalid_return_type:r="Invalid function return type";break;case Hp.invalid_date:r="Invalid date";break;case Hp.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}"`:$p.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Hp.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 Hp.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 Hp.custom:r="Invalid input";break;case Hp.invalid_intersection_types:r="Intersection results could not be merged";break;case Hp.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Hp.not_finite:r="Number must be finite";break;default:r=t.defaultError,$p.assertNever(e)}return{message:r}};let Qp=Jp;function Zp(e,t){const r=Qp,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===Jp?void 0:Jp].filter(e=>!!e)});e.common.issues.push(s)}class Yp{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 Xp;"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 Yp.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 Xp;if("aborted"===n.status)return Xp;"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 Xp=Object.freeze({status:"aborted"}),em=e=>({status:"dirty",value:e}),tm=e=>({status:"valid",value:e}),rm=e=>"aborted"===e.status,sm=e=>"dirty"===e.status,nm=e=>"valid"===e.status,im=e=>"undefined"!=typeof Promise&&e instanceof Promise;var om,am;(am=om||(om={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},am.toString=e=>"string"==typeof e?e:e?.message;class cm{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 dm=(e,t)=>{if(nm(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 Wp(e.common.issues);return this._error=t,this._error}}};function um(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 lm{get description(){return this._def.description}_getType(e){return zp(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:zp(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Yp,ctx:{common:e.parent.common,data:e.data,parsedType:zp(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(im(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:zp(e)},s=this._parseSync({data:e,path:r.path,parent:r});return dm(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zp(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return nm(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=>nm(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:zp(e)},s=this._parse({data:e,path:r.path,parent:r}),n=await(im(s)?s:Promise.resolve(s));return dm(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:Hp.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 lf({schema:this,typeName:Tf.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 hf.create(this,this._def)}nullable(){return pf.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Wm.create(this)}promise(){return uf.create(this,this._def)}or(e){return Zm.create([this,e],this._def)}and(e){return Xm.create(this,e,this._def)}transform(e){return new lf({...um(this._def),schema:this,typeName:Tf.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new mf({...um(this._def),innerType:this,defaultValue:t,typeName:Tf.ZodDefault})}brand(){return new yf({typeName:Tf.ZodBranded,type:this,...um(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new ff({...um(this._def),innerType:this,catchValue:t,typeName:Tf.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return vf.create(this,e)}readonly(){return If.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const hm=/^c[^\s-]{8,}$/i,pm=/^[0-9a-z]+$/,mm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fm=/^[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,gm=/^[a-z0-9_-]{21}$/i,ym=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vm=/^[-+]?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)?)??$/,Im=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let bm;const _m=/^(?:(?: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])$/,Tm=/^(?:(?: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])$/,Cm=/^(([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]))$/,Sm=/^(([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])$/,Em=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,wm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Rm="((\\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])))",Am=new RegExp(`^${Rm}$`);function Nm(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 Om(e){return new RegExp(`^${Nm(e)}$`)}function Mm(e){let t=`${Rm}T${Nm(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 Um(e,t){return!("v4"!==t&&t||!_m.test(e))||!("v6"!==t&&t||!Cm.test(e))}function Lm(e,t){if(!ym.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 km(e,t){return!("v4"!==t&&t||!Tm.test(e))||!("v6"!==t&&t||!Sm.test(e))}class Dm extends lm{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==Kp.string){const t=this._getOrReturnCtx(e);return Zp(t,{code:Hp.invalid_type,expected:Kp.string,received:t.parsedType}),Xp}const t=new Yp;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),Zp(r,{code:Hp.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),Zp(r,{code:Hp.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?Zp(r,{code:Hp.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&Zp(r,{code:Hp.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)Im.test(e.data)||(r=this._getOrReturnCtx(e,r),Zp(r,{validation:"email",code:Hp.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)bm||(bm=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),bm.test(e.data)||(r=this._getOrReturnCtx(e,r),Zp(r,{validation:"emoji",code:Hp.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)fm.test(e.data)||(r=this._getOrReturnCtx(e,r),Zp(r,{validation:"uuid",code:Hp.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)gm.test(e.data)||(r=this._getOrReturnCtx(e,r),Zp(r,{validation:"nanoid",code:Hp.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)hm.test(e.data)||(r=this._getOrReturnCtx(e,r),Zp(r,{validation:"cuid",code:Hp.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)pm.test(e.data)||(r=this._getOrReturnCtx(e,r),Zp(r,{validation:"cuid2",code:Hp.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)mm.test(e.data)||(r=this._getOrReturnCtx(e,r),Zp(r,{validation:"ulid",code:Hp.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),Zp(r,{validation:"url",code:Hp.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),Zp(r,{validation:"regex",code:Hp.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),Zp(r,{code:Hp.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),Zp(r,{code:Hp.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),Zp(r,{code:Hp.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty());else if("datetime"===s.kind){Mm(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Zp(r,{code:Hp.invalid_string,validation:"datetime",message:s.message}),t.dirty())}else if("date"===s.kind){Am.test(e.data)||(r=this._getOrReturnCtx(e,r),Zp(r,{code:Hp.invalid_string,validation:"date",message:s.message}),t.dirty())}else if("time"===s.kind){Om(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Zp(r,{code:Hp.invalid_string,validation:"time",message:s.message}),t.dirty())}else"duration"===s.kind?vm.test(e.data)||(r=this._getOrReturnCtx(e,r),Zp(r,{validation:"duration",code:Hp.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?Um(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Zp(r,{validation:"ip",code:Hp.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?Lm(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),Zp(r,{validation:"jwt",code:Hp.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?km(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Zp(r,{validation:"cidr",code:Hp.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?Em.test(e.data)||(r=this._getOrReturnCtx(e,r),Zp(r,{validation:"base64",code:Hp.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?wm.test(e.data)||(r=this._getOrReturnCtx(e,r),Zp(r,{validation:"base64url",code:Hp.invalid_string,message:s.message}),t.dirty()):$p.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:Hp.invalid_string,...om.errToObj(r)})}_addCheck(e){return new Dm({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...om.errToObj(e)})}url(e){return this._addCheck({kind:"url",...om.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...om.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...om.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...om.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...om.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...om.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...om.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...om.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...om.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...om.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...om.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...om.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,...om.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,...om.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...om.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...om.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...om.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...om.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...om.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...om.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...om.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...om.errToObj(t)})}nonempty(e){return this.min(1,om.errToObj(e))}trim(){return new Dm({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Dm({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Dm({...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 Pm(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}Dm.create=e=>new Dm({checks:[],typeName:Tf.ZodString,coerce:e?.coerce??!1,...um(e)});class xm extends lm{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)!==Kp.number){const t=this._getOrReturnCtx(e);return Zp(t,{code:Hp.invalid_type,expected:Kp.number,received:t.parsedType}),Xp}let t;const r=new Yp;for(const s of this._def.checks)if("int"===s.kind)$p.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Zp(t,{code:Hp.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),Zp(t,{code:Hp.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),Zp(t,{code:Hp.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==Pm(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),Zp(t,{code:Hp.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Zp(t,{code:Hp.not_finite,message:s.message}),r.dirty()):$p.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,om.toString(t))}gt(e,t){return this.setLimit("min",e,!1,om.toString(t))}lte(e,t){return this.setLimit("max",e,!0,om.toString(t))}lt(e,t){return this.setLimit("max",e,!1,om.toString(t))}setLimit(e,t,r,s){return new xm({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:om.toString(s)}]})}_addCheck(e){return new xm({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:om.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:om.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:om.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:om.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:om.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:om.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:om.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:om.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:om.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&&$p.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)}}xm.create=e=>new xm({checks:[],typeName:Tf.ZodNumber,coerce:e?.coerce||!1,...um(e)});class Fm extends lm{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)!==Kp.bigint)return this._getInvalidInput(e);let t;const r=new Yp;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),Zp(t,{code:Hp.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),Zp(t,{code:Hp.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),Zp(t,{code:Hp.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):$p.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Zp(t,{code:Hp.invalid_type,expected:Kp.bigint,received:t.parsedType}),Xp}gte(e,t){return this.setLimit("min",e,!0,om.toString(t))}gt(e,t){return this.setLimit("min",e,!1,om.toString(t))}lte(e,t){return this.setLimit("max",e,!0,om.toString(t))}lt(e,t){return this.setLimit("max",e,!1,om.toString(t))}setLimit(e,t,r,s){return new Fm({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:om.toString(s)}]})}_addCheck(e){return new Fm({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:om.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:om.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:om.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:om.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:om.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}}Fm.create=e=>new Fm({checks:[],typeName:Tf.ZodBigInt,coerce:e?.coerce??!1,...um(e)});class Bm extends lm{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==Kp.boolean){const t=this._getOrReturnCtx(e);return Zp(t,{code:Hp.invalid_type,expected:Kp.boolean,received:t.parsedType}),Xp}return tm(e.data)}}Bm.create=e=>new Bm({typeName:Tf.ZodBoolean,coerce:e?.coerce||!1,...um(e)});class Gm extends lm{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==Kp.date){const t=this._getOrReturnCtx(e);return Zp(t,{code:Hp.invalid_type,expected:Kp.date,received:t.parsedType}),Xp}if(Number.isNaN(e.data.getTime())){return Zp(this._getOrReturnCtx(e),{code:Hp.invalid_date}),Xp}const t=new Yp;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),Zp(r,{code:Hp.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),Zp(r,{code:Hp.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):$p.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Gm({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:om.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:om.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}}Gm.create=e=>new Gm({checks:[],coerce:e?.coerce||!1,typeName:Tf.ZodDate,...um(e)});class qm extends lm{_parse(e){if(this._getType(e)!==Kp.symbol){const t=this._getOrReturnCtx(e);return Zp(t,{code:Hp.invalid_type,expected:Kp.symbol,received:t.parsedType}),Xp}return tm(e.data)}}qm.create=e=>new qm({typeName:Tf.ZodSymbol,...um(e)});class $m extends lm{_parse(e){if(this._getType(e)!==Kp.undefined){const t=this._getOrReturnCtx(e);return Zp(t,{code:Hp.invalid_type,expected:Kp.undefined,received:t.parsedType}),Xp}return tm(e.data)}}$m.create=e=>new $m({typeName:Tf.ZodUndefined,...um(e)});class jm extends lm{_parse(e){if(this._getType(e)!==Kp.null){const t=this._getOrReturnCtx(e);return Zp(t,{code:Hp.invalid_type,expected:Kp.null,received:t.parsedType}),Xp}return tm(e.data)}}jm.create=e=>new jm({typeName:Tf.ZodNull,...um(e)});class Vm extends lm{constructor(){super(...arguments),this._any=!0}_parse(e){return tm(e.data)}}Vm.create=e=>new Vm({typeName:Tf.ZodAny,...um(e)});class Km extends lm{constructor(){super(...arguments),this._unknown=!0}_parse(e){return tm(e.data)}}Km.create=e=>new Km({typeName:Tf.ZodUnknown,...um(e)});class zm extends lm{_parse(e){const t=this._getOrReturnCtx(e);return Zp(t,{code:Hp.invalid_type,expected:Kp.never,received:t.parsedType}),Xp}}zm.create=e=>new zm({typeName:Tf.ZodNever,...um(e)});class Hm extends lm{_parse(e){if(this._getType(e)!==Kp.undefined){const t=this._getOrReturnCtx(e);return Zp(t,{code:Hp.invalid_type,expected:Kp.void,received:t.parsedType}),Xp}return tm(e.data)}}Hm.create=e=>new Hm({typeName:Tf.ZodVoid,...um(e)});class Wm extends lm{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==Kp.array)return Zp(t,{code:Hp.invalid_type,expected:Kp.array,received:t.parsedType}),Xp;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(Zp(t,{code:e?Hp.too_big:Hp.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&&(Zp(t,{code:Hp.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&&(Zp(t,{code:Hp.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 cm(t,e,t.path,r)))).then(e=>Yp.mergeArray(r,e));const n=[...t.data].map((e,r)=>s.type._parseSync(new cm(t,e,t.path,r)));return Yp.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new Wm({...this._def,minLength:{value:e,message:om.toString(t)}})}max(e,t){return new Wm({...this._def,maxLength:{value:e,message:om.toString(t)}})}length(e,t){return new Wm({...this._def,exactLength:{value:e,message:om.toString(t)}})}nonempty(e){return this.min(1,e)}}function Jm(e){if(e instanceof Qm){const t={};for(const r in e.shape){const s=e.shape[r];t[r]=hf.create(Jm(s))}return new Qm({...e._def,shape:()=>t})}return e instanceof Wm?new Wm({...e._def,type:Jm(e.element)}):e instanceof hf?hf.create(Jm(e.unwrap())):e instanceof pf?pf.create(Jm(e.unwrap())):e instanceof ef?ef.create(e.items.map(e=>Jm(e))):e}Wm.create=(e,t)=>new Wm({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Tf.ZodArray,...um(t)});class Qm extends lm{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=$p.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Kp.object){const t=this._getOrReturnCtx(e);return Zp(t,{code:Hp.invalid_type,expected:Kp.object,received:t.parsedType}),Xp}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof zm&&"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 cm(r,t,r.path,a)),alwaysSet:a in r.data})}if(this._def.catchall instanceof zm){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&&(Zp(r,{code:Hp.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 cm(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=>Yp.mergeObjectSync(t,e)):Yp.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return om.errToObj,new Qm({...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:om.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new Qm({...this._def,unknownKeys:"strip"})}passthrough(){return new Qm({...this._def,unknownKeys:"passthrough"})}extend(e){return new Qm({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Qm({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Tf.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Qm({...this._def,catchall:e})}pick(e){const t={};for(const r of $p.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new Qm({...this._def,shape:()=>t})}omit(e){const t={};for(const r of $p.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new Qm({...this._def,shape:()=>t})}deepPartial(){return Jm(this)}partial(e){const t={};for(const r of $p.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new Qm({...this._def,shape:()=>t})}required(e){const t={};for(const r of $p.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof hf;)e=e._def.innerType;t[r]=e}return new Qm({...this._def,shape:()=>t})}keyof(){return af($p.objectKeys(this.shape))}}Qm.create=(e,t)=>new Qm({shape:()=>e,unknownKeys:"strip",catchall:zm.create(),typeName:Tf.ZodObject,...um(t)}),Qm.strictCreate=(e,t)=>new Qm({shape:()=>e,unknownKeys:"strict",catchall:zm.create(),typeName:Tf.ZodObject,...um(t)}),Qm.lazycreate=(e,t)=>new Qm({shape:e,unknownKeys:"strip",catchall:zm.create(),typeName:Tf.ZodObject,...um(t)});class Zm extends lm{_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 Wp(e.ctx.common.issues));return Zp(t,{code:Hp.invalid_union,unionErrors:r}),Xp});{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 Wp(e));return Zp(t,{code:Hp.invalid_union,unionErrors:n}),Xp}}get options(){return this._def.options}}function Ym(e,t){const r=zp(e),s=zp(t);if(e===t)return{valid:!0,data:e};if(r===Kp.object&&s===Kp.object){const r=$p.objectKeys(t),s=$p.objectKeys(e).filter(e=>-1!==r.indexOf(e)),n={...e,...t};for(const i of s){const r=Ym(e[i],t[i]);if(!r.valid)return{valid:!1};n[i]=r.data}return{valid:!0,data:n}}if(r===Kp.array&&s===Kp.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let s=0;s<e.length;s++){const n=Ym(e[s],t[s]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===Kp.date&&s===Kp.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Zm.create=(e,t)=>new Zm({options:e,typeName:Tf.ZodUnion,...um(t)});class Xm extends lm{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if(rm(e)||rm(s))return Xp;const n=Ym(e.value,s.value);return n.valid?((sm(e)||sm(s))&&t.dirty(),{status:t.value,value:n.data}):(Zp(r,{code:Hp.invalid_intersection_types}),Xp)};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}))}}Xm.create=(e,t,r)=>new Xm({left:e,right:t,typeName:Tf.ZodIntersection,...um(r)});class ef extends lm{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Kp.array)return Zp(r,{code:Hp.invalid_type,expected:Kp.array,received:r.parsedType}),Xp;if(r.data.length<this._def.items.length)return Zp(r,{code:Hp.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Xp;!this._def.rest&&r.data.length>this._def.items.length&&(Zp(r,{code:Hp.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 cm(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>Yp.mergeArray(t,e)):Yp.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new ef({...this._def,rest:e})}}ef.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ef({items:e,typeName:Tf.ZodTuple,rest:null,...um(t)})};class tf extends lm{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!==Kp.object)return Zp(r,{code:Hp.invalid_type,expected:Kp.object,received:r.parsedType}),Xp;const s=[],n=this._def.keyType,i=this._def.valueType;for(const o in r.data)s.push({key:n._parse(new cm(r,o,r.path,o)),value:i._parse(new cm(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?Yp.mergeObjectAsync(t,s):Yp.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new tf(t instanceof lm?{keyType:e,valueType:t,typeName:Tf.ZodRecord,...um(r)}:{keyType:Dm.create(),valueType:e,typeName:Tf.ZodRecord,...um(t)})}}class rf extends lm{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!==Kp.map)return Zp(r,{code:Hp.invalid_type,expected:Kp.map,received:r.parsedType}),Xp;const s=this._def.keyType,n=this._def.valueType,i=[...r.data.entries()].map(([e,t],i)=>({key:s._parse(new cm(r,e,r.path,[i,"key"])),value:n._parse(new cm(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 Xp;"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 Xp;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}}rf.create=(e,t,r)=>new rf({valueType:t,keyType:e,typeName:Tf.ZodMap,...um(r)});class sf extends lm{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Kp.set)return Zp(r,{code:Hp.invalid_type,expected:Kp.set,received:r.parsedType}),Xp;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(Zp(r,{code:Hp.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&&(Zp(r,{code:Hp.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 Xp;"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 cm(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>i(e)):i(o)}min(e,t){return new sf({...this._def,minSize:{value:e,message:om.toString(t)}})}max(e,t){return new sf({...this._def,maxSize:{value:e,message:om.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}sf.create=(e,t)=>new sf({valueType:e,minSize:null,maxSize:null,typeName:Tf.ZodSet,...um(t)});class nf extends lm{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})}}nf.create=(e,t)=>new nf({getter:e,typeName:Tf.ZodLazy,...um(t)});class of extends lm{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Zp(t,{received:t.data,code:Hp.invalid_literal,expected:this._def.value}),Xp}return{status:"valid",value:e.data}}get value(){return this._def.value}}function af(e,t){return new cf({values:e,typeName:Tf.ZodEnum,...um(t)})}of.create=(e,t)=>new of({value:e,typeName:Tf.ZodLiteral,...um(t)});class cf extends lm{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return Zp(t,{expected:$p.joinValues(r),received:t.parsedType,code:Hp.invalid_type}),Xp}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 Zp(t,{received:t.data,code:Hp.invalid_enum_value,options:r}),Xp}return tm(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 cf.create(e,{...this._def,...t})}exclude(e,t=this._def){return cf.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}cf.create=af;class df extends lm{_parse(e){const t=$p.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Kp.string&&r.parsedType!==Kp.number){const e=$p.objectValues(t);return Zp(r,{expected:$p.joinValues(e),received:r.parsedType,code:Hp.invalid_type}),Xp}if(this._cache||(this._cache=new Set($p.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=$p.objectValues(t);return Zp(r,{received:r.data,code:Hp.invalid_enum_value,options:e}),Xp}return tm(e.data)}get enum(){return this._def.values}}df.create=(e,t)=>new df({values:e,typeName:Tf.ZodNativeEnum,...um(t)});class uf extends lm{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Kp.promise&&!1===t.common.async)return Zp(t,{code:Hp.invalid_type,expected:Kp.promise,received:t.parsedType}),Xp;const r=t.parsedType===Kp.promise?t.data:Promise.resolve(t.data);return tm(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}uf.create=(e,t)=>new uf({type:e,typeName:Tf.ZodPromise,...um(t)});class lf extends lm{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Tf.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=>{Zp(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 Xp;const s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?Xp:"dirty"===s.status||"dirty"===t.value?em(s.value):s});{if("aborted"===t.value)return Xp;const s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?Xp:"dirty"===s.status||"dirty"===t.value?em(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?Xp:("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?Xp:("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(!nm(e))return Xp;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=>nm(e)?Promise.resolve(s.transform(e.value,n)).then(e=>({status:t.value,value:e})):Xp)}$p.assertNever(s)}}lf.create=(e,t,r)=>new lf({schema:e,typeName:Tf.ZodEffects,effect:t,...um(r)}),lf.createWithPreprocess=(e,t,r)=>new lf({schema:t,effect:{type:"preprocess",transform:e},typeName:Tf.ZodEffects,...um(r)});class hf extends lm{_parse(e){return this._getType(e)===Kp.undefined?tm(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}hf.create=(e,t)=>new hf({innerType:e,typeName:Tf.ZodOptional,...um(t)});class pf extends lm{_parse(e){return this._getType(e)===Kp.null?tm(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pf.create=(e,t)=>new pf({innerType:e,typeName:Tf.ZodNullable,...um(t)});class mf extends lm{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===Kp.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}mf.create=(e,t)=>new mf({innerType:e,typeName:Tf.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...um(t)});class ff extends lm{_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 im(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Wp(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new Wp(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ff.create=(e,t)=>new ff({innerType:e,typeName:Tf.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...um(t)});class gf extends lm{_parse(e){if(this._getType(e)!==Kp.nan){const t=this._getOrReturnCtx(e);return Zp(t,{code:Hp.invalid_type,expected:Kp.nan,received:t.parsedType}),Xp}return{status:"valid",value:e.data}}}gf.create=e=>new gf({typeName:Tf.ZodNaN,...um(e)});class yf extends lm{_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 vf extends lm{_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?Xp:"dirty"===e.status?(t.dirty(),em(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?Xp:"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 vf({in:e,out:t,typeName:Tf.ZodPipeline})}}class If extends lm{_parse(e){const t=this._def.innerType._parse(e),r=e=>(nm(e)&&(e.value=Object.freeze(e.value)),e);return im(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function bf(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function _f(e,t={},r){return e?Vm.create().superRefine((s,n)=>{const i=e(s);if(i instanceof Promise)return i.then(e=>{if(!e){const e=bf(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=bf(t,s),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}}):Vm.create()}var Tf,Cf;If.create=(e,t)=>new If({innerType:e,typeName:Tf.ZodReadonly,...um(t)}),(Cf=Tf||(Tf={})).ZodString="ZodString",Cf.ZodNumber="ZodNumber",Cf.ZodNaN="ZodNaN",Cf.ZodBigInt="ZodBigInt",Cf.ZodBoolean="ZodBoolean",Cf.ZodDate="ZodDate",Cf.ZodSymbol="ZodSymbol",Cf.ZodUndefined="ZodUndefined",Cf.ZodNull="ZodNull",Cf.ZodAny="ZodAny",Cf.ZodUnknown="ZodUnknown",Cf.ZodNever="ZodNever",Cf.ZodVoid="ZodVoid",Cf.ZodArray="ZodArray",Cf.ZodObject="ZodObject",Cf.ZodUnion="ZodUnion",Cf.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Cf.ZodIntersection="ZodIntersection",Cf.ZodTuple="ZodTuple",Cf.ZodRecord="ZodRecord",Cf.ZodMap="ZodMap",Cf.ZodSet="ZodSet",Cf.ZodFunction="ZodFunction",Cf.ZodLazy="ZodLazy",Cf.ZodLiteral="ZodLiteral",Cf.ZodEnum="ZodEnum",Cf.ZodEffects="ZodEffects",Cf.ZodNativeEnum="ZodNativeEnum",Cf.ZodOptional="ZodOptional",Cf.ZodNullable="ZodNullable",Cf.ZodDefault="ZodDefault",Cf.ZodCatch="ZodCatch",Cf.ZodPromise="ZodPromise",Cf.ZodBranded="ZodBranded",Cf.ZodPipeline="ZodPipeline",Cf.ZodReadonly="ZodReadonly";const Sf=Dm.create,Ef=xm.create,wf=Bm.create;Vm.create;const Rf=Km.create,Af=zm.create,Nf=Wm.create,Of=Qm.create,Mf=Zm.create;Xm.create,ef.create;const Uf=tf.create,Lf=cf.create;uf.create,hf.create,pf.create;const kf=Uf(Rf()),Df={text:Of({content:Sf()}),image:Of({isGif:wf(),isOriginalImage:wf()}),video:Of({duration:Ef()}),voice:Of({duration:Ef()}),file:kf,location:Of({latitude:Ef(),longitude:Ef()}),cmd:Of({action:Sf()}),custom:Of({event:Sf()}),combine:Of({title:Sf(),summary:Sf(),filename:Sf(),filetype:Sf(),combineLevel:Ef()})},Pf=Of({msgServerId:Sf(),msgLocalId:Sf(),from:Sf(),to:Sf(),sender:Of({userId:Sf(),nickname:Sf().optional(),avatarUrl:Sf().optional()}),conversationId:Sf(),conversationType:Lf(["singleChat","groupChat","chatRoom"]),type:Lf(["text","image","video","voice","file","location","cmd","custom","combine"]),sendStatus:Lf(["sending","sent","failed"]),timestamp:Ef(),ext:kf,body:kf});const xf=wf().optional().catch(void 0),Ff=Ef().finite().optional().catch(void 0),Bf=Sf().optional().catch(void 0),Gf=Of({msgLocalId:Bf,sendStatus:Lf(["sending","sent","failed"]).optional().catch(void 0),direct:Lf(["SEND","RECEIVE"]).optional().catch(void 0),isOnline:xf,receiverList:Nf(Sf()).optional().catch(void 0),deliverOnlineOnly:xf,webhookEnv:Bf,priority:Lf(["high","normal","low"]).optional().catch(void 0),isBroadcast:xf,isContentReplaced:xf,combineLevel:Ff,modifiedInfo:Of({operatorId:Sf(),operationCount:Ef().finite(),operationTime:Ef().finite()}).optional().catch(void 0),reactions:Nf(Of({reaction:Sf(),count:Ef(),userList:Nf(Sf()),isAddedBySelf:wf().optional(),op:Nf(Of({operator:Sf(),reactionType:Lf(["create","delete"])})).optional()})).optional().catch(void 0),groupReadCount:Ef().int().nonnegative().optional().catch(void 0),isPeerRead:xf,needReadReceipt:xf,isChatThread:xf,chatThread:Of({messageId:Sf(),parentId:Sf(),chatThreadName:Sf().optional()}).optional().catch(void 0),chatThreadOverview:Of({chatThreadId:Sf(),parentId:Sf(),name:Sf().optional(),lastMessage:_f(e=>{const t=Pf.safeParse(e);return t.success&&Df[t.data.type].safeParse(t.data.body).success}).transform(function(e){return{...Pf.parse(e),body:e.body,...qf(e)}}).nullable().optional().catch(null),createdAt:Ef().optional(),updatedAt:Ef().optional(),messageCount:Ef().optional()}).optional().catch(void 0),stream:Of({customType:Sf().optional(),seq:Ef(),status:Lf(["STREAM_START","STREAM_START_COMPLETED","STREAM_IN_PROGRESS","STREAM_COMPLETED","STREAM_FULL","STREAM_ERROR"]),errorType:Ef(),finishReason:Ef().optional(),deltaText:Sf(),fullText:Sf()}).optional().catch(void 0),userInfoUpdateTime:Ff,namecardUpdateTime:Ff}),qf=e=>{const t=Gf.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},$f=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),jf=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)},Kf=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)},zf=e=>{const t=new Uint8Array(fa.util.base64.length(e));return fa.util.base64.decode(e,t,0),t};class Hf{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:Kf(s),ct:Kf(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=zf(t.iv),s=zf(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 Wf="conversationMap",Jf="userInfoMap",Qf="groupNamecardMap",Zf="contactRelationMap",Yf="contactVersion",Xf="contactMeta",eg="sessionListMap",tg="sessionListCheckpoint",rg="joinedGroupPreview",sg="metadata",ng=(e,t)=>`IMSDK_${e.appKey}_${e.userId}_${t}_v${e.schemaVersion}`;class ig{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 og=()=>{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 ag{constructor(e,t){this.storage=t??ag.createLocalStorageAdapter(),this.cryptoAdapter=e??null}static createLocalStorageAdapter(){if(!ag.checkAvailable())return null;const e=og();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=og();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 vu(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 cg={version:"",lastVersionCheckAt:0,lastVersionSource:"metadata"},dg={cacheIntegrity:"incomplete",reason:"first_sync_pending",lastSyncTs:0,lastSuccessfulVersion:"",lastSyncMode:"skipped"};class ug{constructor(){this.items=new Map,this.versionState=cg,this.meta=dg}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(!yu(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 yu(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"}:cg}normalizeMeta(e){return yu(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"}:dg}}const lg=(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}},hg=(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}},pg=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 mg{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=lg(this.items,e,t);return this.items=[...r.kept],r.removed.length>0}evictByLru(e){const t=hg(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:pg(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(!yu(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=yu(e.body)?e.body:{};return t?{...qf(e),msgId:t,from:"string"==typeof e.from?e.from:void 0,to:"string"==typeof e.to?e.to:void 0,sender:yu(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:jf(n),ext:yu(e.ext)?e.ext:void 0,timestamp:s}:null}}const fg=(e,t)=>`${e}:${t}`;class gg{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(fg(e.groupId,e.userId),e)}}getAll(){return Array.from(this.items.values())}get(e,t,r,s){const n=fg(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(fg(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=fg(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(fg(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=lg(n,e,t),o=new Set(i.removed.map(e=>fg(e.groupId,e.userId)));this.items.clear();for(const a of s)o.has(fg(a.groupId,a.userId))||this.items.set(fg(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=hg(s,Math.min(e,s.length)),i=new Set(n.removed.map(e=>fg(e.groupId,e.userId)));this.items.clear();for(const o of r)i.has(fg(o.groupId,o.userId))||this.items.set(fg(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||!yu(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 yg=100,vg=3e3,Ig=e=>({...e}),bg=e=>"object"==typeof e&&null!==e,_g=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 Tg{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:yg,serverLimit:vg,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:yg,serverLimit:vg,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return bg(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:_g(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,yg),this.meta=(e=>{const t=bg(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:yg,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:vg,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=>Ig(e)).slice(0,yg),this.meta={...e.meta,source:"localPreview",storageLimit:yg,serverLimit:vg,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>Ig(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>Ig(e)),meta:{...this.meta,source:"localPreview"}}}}const Cg=e=>"singleChat"===e||"groupChat"===e||"chatRoom"===e?e:null,Sg=e=>{if(!yu(e))return null;const t="string"==typeof e.msgServerId?e.msgServerId:null;if(null===t||"string"!=typeof e.from||"number"!=typeof e.timestamp||!yu(e.body))return null;const r=((e,t)=>{if(yu(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=Cg(e.conversationType);return{...qf({...e,sendStatus:e.sendStatus??e.status}),msgServerId:t,from:e.from,to:"string"==typeof e.to?e.to:"",sender:r,body:jf(e.body),ext:yu(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}:{}}},Eg=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},wg=(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 Rg{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(wg)}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(wg)}exportItems(){return this.items.map(({updatedAt:e,...t})=>t)}normalizeItem(e,t){if(!yu(e))return null;const r=e,s="string"==typeof r.conversationId?r.conversationId:"";if(!s)return null;const n=Cg(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:Sg(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:Eg(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 Ag{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=lg(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=hg(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(!yu(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 Ng=e=>"number"==typeof e.pinnedTimestamp?e.pinnedTimestamp:0,Og=e=>e.lastMessageAt??e.updatedAt,Mg=e=>[...e].sort((e,t)=>{const r=Ng(t)-Ng(e);if(0!==r)return r;const s=Og(t)-Og(e);return 0!==s?s:e.conversationId.localeCompare(t.conversationId)}),Ug=e=>`${e.conversationType}:${e.conversationId}`,Lg=(e,t)=>t.lastMessage?e.lastMessage?t.lastMessage.timestamp>=e.lastMessage.timestamp?t.lastMessage:e.lastMessage:t.lastMessage:e.lastMessage,kg=(e,t)=>((e,t)=>Og(t)>Og(e))(e,t)?{...e,unreadCount:Math.max(e.unreadCount,t.unreadCount),lastMessage:Lg(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,Dg=e=>{const t=new Map,r=new Set;for(const i of e.snapshot)r.add(Ug(i));for(const i of e.existing)t.set(Ug(i),i);const s=e.snapshot.map(e=>{const r=t.get(Ug(e));return r?kg(e,r):e}),n=e.existing.filter(t=>!r.has(Ug(t))&&((e,t)=>"number"==typeof t&&e.updatedAt>t)(t,e.syncStartedAt));return Mg([...s,...n])},Pg=["userId","nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],xg=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),Fg=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 Bg{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,Pg.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 Gg=["conversation","userInfo","groupNamecard","sessionList","joinedGroupPreview","contactRelation","contactVersion","contactMeta"];class qg{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 Hf(e.appKey,e.userId);this.store=new ag(t??void 0,e.storageAdapter);const r={appKey:e.appKey,userId:e.userId,schemaVersion:this.config.schemaVersion};this.conversationKey=ng(r,Wf),this.userInfoKey=ng(r,Jf),this.groupNamecardKey=ng(r,Qf),this.sessionListKey=ng(r,eg),this.sessionListCheckpointKey=ng(r,tg),this.joinedGroupPreviewKey=ng(r,rg),this.contactRelationKey=ng(r,Zf),this.contactVersionKey=ng(r,Yf),this.contactMetaKey=ng(r,Xf),this.metadataKey=ng(r,sg),this.metadataStore=new ig(this.store,this.metadataKey,this.config.schemaVersion),this.conversationCache=new mg,this.userInfoCache=new Ag,this.groupNamecardCache=new gg,this.sessionListCache=new Rg,this.joinedGroupPreviewCache=new Tg,this.contactCache=new ug,this.userInfoRuntimeStore=new Bg,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 Tg;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=Dg({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?xg(t):void 0;return this.userInfoRuntimeStore.applyPatch(e,r)}updateUserInfoSummaryFromRuntime(e){const t=this.userInfoRuntimeStore.get(e,!1);t&&this.setUserInfoSummaries([Fg(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=>({...qf(e),...e.type?{type:e.type}:{},...e.body?{body:jf(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 $f(e)===$f(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=Ug(e.nextRecord),r=e.existing.filter(e=>Ug(e)!==t);return Mg([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&&yu(n)&&Array.isArray(n.items)?n.items:[];this.sessionListCache.load(i,e);const o=(n&&yu(n)&&yu(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&&yu(t)&&Array.isArray(t.items)?t.items:[]}async readValue(e,t){return await this.store.readAsync(e,t)}normalizeSessionListCheckpoint(e){return e&&yu(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 Gg)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=>Ng(e)>0),r=new Map;for(const n of e.incoming)r.set(Ug(n),n);const s=t.length>0?e.existing.filter(e=>!r.has(Ug(e))&&0===Ng(e)):e.existing.filter(e=>!r.has(Ug(e)));return Mg([...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(Dg({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=$f(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=Yu(e);return{userInfoUpdateTime:t?.userInfoUpdateTime,namecardUpdateTime:"groupChat"===e.conversationType?t?.namecardUpdateTime:void 0}})(e);return{...qf(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,body:this.normalizeMessageBody(e.body),ext:e.ext,timestamp:e.timestamp,userInfoUpdateTime:t.userInfoUpdateTime,namecardUpdateTime:t.namecardUpdateTime,modifiedInfo:e.modifiedInfo}}normalizeMessageBody(e){return jf(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=Vf({conversationId:e.conversationId,conversationType:e.type,currentUserId:this.userId,from:h,to:t.to,direct:t.direct}),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?{...qf(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,ext:d.ext??{}}: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?xg(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=$f(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 $g{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 jg={maxAttempts:3,initialDelay:1e3,maxDelay:6e4,backoffMultiplier:2,jitter:!0};function Vg(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 Kg(e){return new Promise(t=>setTimeout(t,e))}const zg=(e,t)=>JSON.stringify([t,e]),Hg=(e,t,r)=>{const s=e.lastMessage;if(!s)return null;const n=((e,t,r)=>{const s=e.lastMessage,n=r.get(zg(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{...qf(i),...qf(s),from:o,to:l,sender:{...d,userId:o},direct:u,ext:s?.ext??i?.ext??{}}})(e,t,r);return{...qf(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:jf(s.body),ext:n.ext}},Wg=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},Jg=async(e,t)=>{const r=await Wg(e,t),s=(e=>{const t=new Map,r=e.getCacheManager()?.loadSessionList?.()??[];for(const s of r)s.lastMessage&&t.set(zg(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:Hg(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 Qg{constructor(e=`session-list-${jh()}`){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 Zg=0,Yg=5,Xg=10,ey=11,ty=1,ry=2,sy=1,ny=2,iy=3,oy=e=>e===ty?"groupChat":e===ry?"chatRoom":"singleChat",ay=()=>Kd().lookupType("easemob.pb.MessageBody"),cy=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}},dy=e=>{const t={...e};return delete t.type,t},uy=(e,t,r)=>{if(!e)return"";const s=`${t}_${r}_`;return e.startsWith(s)?e.slice(s.length):e},ly=(e,t,r)=>{if(!e)return null;const s=nu(r.payload?.from,{name:uy(e.from?.name,r.org,r.app)}),n=((e,t)=>{if(!e)return{};const r=new su(t.currentUserId,t.useCustomAttachmentUpload),s=ru(e),n=s?r.decodeContent(s):null,i=r.decodeMetadata(e,t.conversationType,t.from===t.currentUserId?"SEND":void 0),o={userInfoUpdateTime:Cl(Yd(e.userInfoUpdateTime)),namecardUpdateTime:Cl(Yd(e.namecardUpdateTime))};return{...i,...n?{type:i.stream?"text":n.type,body:i.stream?{content:i.stream.fullText}:{...n.body}}:{},ext:eu(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:nu(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,body:n.body??dy(t),ext:n.ext??r.ext??{}};var o},hy=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},py=(e,t,r,s,n)=>e.sessions.map(e=>{const i=(e=>{if(!e||0===e.byteLength)return null;try{return ay().toObject(ay().decode(e),{longs:Number,bytes:Uint8Array})}catch{return null}})(e.last_message?.payload),o=e.session_id??"",a=oy(e.session_type),c=(e=>{const t=e.session_id??"",r=oy(e.session_type);return"groupChat"===r||"chatRoom"===r?{conversationName:e.group_name??t,conversationAvatar:e.group_avatar}:cy(e)})(e);return{conversationId:o,conversationType:a,unreadCount:e.unread_count??0,lastMessage:ly(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:hy(e.marks),readAt:e.read_receipt,remindType:(d=e.remind_type,d===sy?"ALL":d===ny?"AT":d===iy?"NONE":"DEFAULT"),conversationName:c.conversationName,conversationAvatar:c.conversationAvatar};var d}),fy={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 gy=null,yy=!1;const vy=()=>gy||(yy||(fa.util.Long=Dn,fa.configure(),yy=!0),Va(),gy=fa.Root.fromJSON(fy),ja(gy),gy),Iy=e=>vy().lookupType(e),by=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}},_y=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:by(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:by(t.protocol_version)??by(t.protocolVersion)??0}},Ty=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}},Cy=e=>{if(!e||"object"!=typeof e)return;const t=e;return{id:"string"==typeof t.id?t.id:void 0!==by(t.id)?String(by(t.id)):void 0,from:Ty(t.from),timestamp:by(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 Sy{constructor(){this.requestType=Iy("easemob.sessionlist.GetSessionListRequest"),this.responseType=Iy("easemob.sessionlist.GetSessionListResponse"),this.errorType=Iy("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:Zg}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=by(t.type);return r!==Xg?null:{type:r,header:_y(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:by(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=by(t.type);return r!==ey?null:{type:r,header:_y(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:by(t.session_type),last_message:Cy(t.last_message),updated_at:by(t.updated_at),pinned_time:by(t.pinned_time),unread_count:by(t.unread_count),marks:Array.isArray(t.marks)?t.marks.filter(e=>"string"==typeof e):void 0,read_receipt:by(t.read_receipt),remind_type:by(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:by(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=by(t.type);return r!==Yg?null:{type:r,header:_y(t.header),code:by(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown session-list error"}}catch{return null}}}const Ey=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 Sy;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,js("Decoded session-list sync raw response",{requestId:e.session.getRequestId(),batchSequence:u,response:o});const c=py(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}}}})},wy=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"}]}}),Ry=(e,t,r)=>{const s=e+t;return s<r?String(s):""},Ay=e=>({...e}),Ny=e=>{const t=(e=>e?{...qf(e),msgId:e.msgServerId,from:e.from,to:e.to,sender:{...e.sender},type:e.type??"unknown",body:jf(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}},Oy=e=>"AT"===e||"NONE"===e||"ALL"===e?e:null,My=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 wy(t);const r=Number.parseInt(e,10);if(!Number.isSafeInteger(r)||r<0)throw wy(t);return r})(e.cursor,"cursor"),r=[];for(const s of e.items){if("chatRoom"===s.conversationType)continue;const e=Oy(s.remindType);e&&r.push({conversationId:s.conversationId,conversationType:s.conversationType,remindType:e})}return{conversations:r.slice(t,t+e.pageSize),cursor:Ry(t,e.pageSize,r.length)}},Uy=()=>Date.now(),Ly={maxAttempts:3,initialDelay:3e3,maxDelay:5e3,backoffMultiplier:1,jitter:!0},ky=(e,t)=>({status:e,determinedAt:Uy(),reason:t}),Dy=e=>e instanceof ut&&(e.code===ot.SERVER_BUSY||1103===e.code),Py=e=>({dataType:"conversation",code:e.code,stage:"fallback",message:e.message,retryable:Dy(e)});class xy{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 Qg,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={...jg,...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=Vg(o,s);await Kg(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 Ey({client:this.client,session:r,params:t})}catch(s){throw this.cancelled||r.fail(),s}},e=>!this.cancelled&&Dy(e),Ly);if(this.cancelled)return[];const d={result:c,syncStartedAt:e.getStartedAt()},u=d.result.items;this.capabilityState={status:"available",determinedAt:Uy()};const l={lastSyncTime:d.result.lastSyncFinishedTs,lastSyncFinishedTs:d.result.lastSyncFinishedTs,sessionsLastSyncTs:d.result.lastSyncFinishedTs,lastSuccessfulAt:Uy()};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:Py(t)}),r.loadSessionList()}const h=r.loadSessionList();return r.updateConversationsFromServer(h.map(Ny),{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:ky("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:Py(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=ky("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 Qg}async buildFallbackSessionList(e){return await(async(e,t)=>await Jg(e,t))(e.loadConversationSummaries(),this.client)}}const Fy=e=>"[object ArrayBuffer]"===Object.prototype.toString.call(e),By=async e=>{if("string"==typeof e||Fy(e)||ArrayBuffer.isView(e))return(e=>"string"==typeof e?(new TextEncoder).encode(e):Fy(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}})},Gy=e=>{const t=Math.max(e-1,0),r=1e3*Math.pow(2,t);return Math.min(r,5e3)},qy=async e=>{await new Promise(t=>{setTimeout(t,e)})},$y=e=>e instanceof Error?e:new Error(String(e));class jy{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,$y(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=$y(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=Gy(this.attempt);Vs("sync websocket retry scheduled",this.buildLogContext({delayMs:r,reason:e.message})),await qy(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 By(e);if(!(await this.routeFrame(t)))return}catch(t){const e=$y(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($y(s)),this.closeIfComplete()}return!0}t.requestId||1!==t.type||r||(r={pending:n,frame:t.frame})}catch(s){t.push($y(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($y(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 Vy=(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 Ky(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(Vy(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 zy(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 Hy={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"}},Wy=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase();class Jy{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=bp(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=Hy[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_${Wy(e)}`,operationType:r}})(t.operation):void 0,a=o?Ph(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[ou]=iu()),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=Ky(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 zy({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 zy({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 Qy=async(e,t,r)=>{const{orgName:s,appName:n}=fs(e.appKey),i=`/${s}/${n}/user/${encodeURIComponent(e.userId)}/roster/metadata/version`,o=new Jy(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(yu(e))return yu(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 Zy{static validate(e,t){try{return{success:!0,data:e.parse(t)}}catch(r){if(r instanceof Wp){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 Yy=e=>Sf().regex(/^https?:\/\/\S+$/i,e),Xy=Of({appKey:Sf().min(1,"appKey is required").optional(),appId:Sf().min(1,"appId is required").optional(),enableUserInfoSync:wf().optional(),enableSyncData:Nf(Lf(["conversation","contact","group"])).optional(),enableDeliveryReceipt:wf().optional(),deleteConversationOnGroupDestroyed:wf().optional(),syncConversationListConfig:Of({includeEmpty:wf().optional()}).strict().optional(),useCustomAttachmentUpload:wf().optional(),useFixedDeviceId:wf().optional(),deviceId:Sf().min(1,"deviceId is required").optional(),serviceConfig:Of({dnsConfigUrls:Nf(Yy("serviceConfig.dnsConfigUrls item must be a valid URL")).nonempty().optional(),serverUrls:Of({restApiUrl:Yy("serviceConfig.serverUrls.restApiUrl must be a valid URL").optional(),wsUrl:(ev="serviceConfig.serverUrls.wsUrl must be a valid URL",Sf().regex(/^wss?:\/\/\S+$/i,ev)).optional()}).optional()}).optional(),useReplacedMessageContents:wf().optional(),customDeviceName:Sf().min(1,"customDeviceName is required").optional(),customOSPlatform:Ef().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:Sf().min(1,"uiKitVersion is required").optional(),loginExtensionInfo:Sf().max(1024,"loginExtensionInfo must be at most 1024 characters").optional(),managers:Nf(Rf()).optional(),platformAdapterOptions:Of({prefer:Lf(["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:_f(e=>"object"==typeof e&&null!==e).optional(),transportAdapter:_f(e=>"object"==typeof e&&null!==e).optional(),overrides:_f(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:Hp.custom,path:["appKey"],message:"appKey or appId is required"}):r>1&&t.addIssue({code:Hp.custom,path:["appId"],message:"appKey and appId cannot be used together"}),"enableMd5Check"in e&&t.addIssue({code:Hp.custom,path:["enableMd5Check"],message:"enableMd5Check is removed; attachment precheck is controlled by DNS_CONFIG"}),"enableHttpDns"in e&&t.addIssue({code:Hp.custom,path:["enableHttpDns"],message:"enableHttpDns is removed; configure serviceConfig.serverUrls for fixed URLs"}),"dnsConfigUrls"in e&&t.addIssue({code:Hp.custom,path:["dnsConfigUrls"],message:"dnsConfigUrls is moved to serviceConfig.dnsConfigUrls"}),"serverUrls"in e&&t.addIssue({code:Hp.custom,path:["serverUrls"],message:"serverUrls is moved to serviceConfig.serverUrls"}),"profileSync"in e&&t.addIssue({code:Hp.custom,path:["profileSync"],message:"profileSync is internal; profile sync scheduling uses SDK defaults"}),"cacheEncryptionMode"in e&&t.addIssue({code:Hp.custom,path:["cacheEncryptionMode"],message:"cacheEncryptionMode is internal; cache encryption defaults to auto"}),"enableAutoSyncContacts"in e&&t.addIssue({code:Hp.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:Hp.custom,path:["serviceConfig"],message:"serviceConfig.dnsConfigUrls and serviceConfig.serverUrls cannot be used together"}),n&&(void 0!==e.appId&&t.addIssue({code:Hp.custom,path:["serviceConfig","serverUrls"],message:"serviceConfig.serverUrls cannot be used when initialized with appId"}),n?.restApiUrl||t.addIssue({code:Hp.custom,path:["serviceConfig","serverUrls","restApiUrl"],message:"serviceConfig.serverUrls.restApiUrl is required when serverUrls is configured"}),n?.wsUrl||t.addIssue({code:Hp.custom,path:["serviceConfig","serverUrls","wsUrl"],message:"serviceConfig.serverUrls.wsUrl is required when serverUrls is configured"}))});var ev;const tv=Of({userId:Sf().min(1,"userId is required"),token:Sf().min(1,"token is required")}),rv=Of({timeoutMs:Ef().int("timeoutMs must be an integer").min(5e3,"timeoutMs must be at least 5000").max(Zr,"timeoutMs must be at most 120000").optional()}).strict(),sv=Sf().trim().min(1,"token is required"),nv=Of({channelName:Sf().trim().min(1,"channelName is required").optional()}).optional(),iv=Nf(Ef({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))),ov=Of({protocol:Sf(),domain:Sf().optional(),ip:Sf().optional(),port:Mf([Sf(),Ef()]).optional()}).passthrough(),av=Of({app_key:Sf().optional(),rest:Of({hosts:Nf(ov).nonempty()}),"msync-wx":Of({hosts:Nf(ov).nonempty()}),"sync-ws":Of({hosts:Nf(ov).nonempty()}).optional(),enableReportLogs:Lf(["true","false"]).optional(),reportInterval:Ef().positive().finite().optional(),enableDataReport:Lf(["true","false"]).optional(),enableMd5Check:Lf(["true","false"]).optional(),uploadinparts_enable:Lf(["true","false"]).optional()}).passthrough(),cv=e=>encodeURIComponent(e).replace(/[!'()~]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g,"+"),dv=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])=>`${cv(e)}=${cv(t)}`).join("&")}})(e),uv="5.1.3",lv=["https://rs.chat.rtnsvc.com","https://rs.easemob.com","https://rs.chat.realtimemesh.com"],hv=["msync-wx","msync-ws","msync","msync-web","websocket","websocket-im","im-websocket","im-ws","socket"];function pv(e){return"object"==typeof e&&null!==e}function mv(e){return Array.isArray(e)?{hosts:e}:function(e){return pv(e)&&"hosts"in e&&Array.isArray(e.hosts)}(e)?{hosts:e.hosts}:void 0}function fv(e){if(!pv(e))return Zy.validateOrThrow(av,e);const t=mv(e.rest),r=function(e,t,r){for(const s of t){const t=mv(e[s]);if(t)return{key:s,section:t}}for(const[s,n]of Object.entries(e)){if(!r(s))continue;const e=mv(n);if(e)return{key:s,section:e}}}(e,hv,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}),Zy.validateOrThrow(av,s)}function gv(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 yv(e,t){return"https"===e?"https":"http"===e?"http":t}function vv(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 Iv(e,t){const r=e.filter(e=>e.protocol===t);return r.length>0?r:"http"===t?e.filter(e=>"https"===e.protocol):[]}function bv(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 _v(e,t,r,s){const n=new Jy(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?dv({app_id:t.appId,sdk_version:uv,file_version:"1"}):dv({app_key:t.appKey,_v:String(Date.now())})).toString()}`}return fv(await n.get(i,{timeout:s}))}async function Tv(e){const t=e.baseUrls&&e.baseUrls.length>0?e.baseUrls:lv;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 _v(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=bv(Iv(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=Iv(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=>gv(e,yv(e.protocol,r))),p=gv(d,yv(d.protocol,r));return{appKey:a,websocketUrl:p,websocketUrls:h,baseUrl:o,restBaseUrl:vv(l,yv(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 Cv=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`},Sv=e=>new mt(e,{code:ot.VALIDATION_INVALID_FORMAT,details:{reason:"invalid_rest_response"}}),Ev=e=>{if(!yu(e))throw Sv("Invalid REST response");return yu(e.data)?e.data:e},wv=(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}}},Rv=(e,t)=>{for(const r of t){const t=e[r];if("string"==typeof t)return t}},Av=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}`},Nv=async(e,t)=>{const r=await e.get((e=>`${Av(e)}/sdk/users/${encodeURIComponent(e.userId)}/token/expires`)(t),{operation:"getTokenExpireTimestamp"});return(e=>{const t=Ev(e),r=wv(t,["expire_timestamp","expireTimestamp","expireAt"]);if(void 0===r)throw Sv("Invalid token expires response");return r})(r)},Ov=async(e,t,r)=>{const s=await e.get(((e,t)=>{const r=dv({channelName:t?.channelName??"*"});return`${Av(e)}/users/${encodeURIComponent(e.userId)}/token/rtc?${r.toString()}`})(t,r),{operation:"getRtcTokenInfo"});return(e=>{const t=Ev(e);return{appId:Rv(t,["app_id","appId"])??"",rtcToken:Rv(t,["rtc_token","rtcToken","RTCToken"])??"",channelName:Rv(t,["channel_name","channelName"])??"",rtcUid:wv(t,["rtcUid","RTCUId","rtc_uid"])??0,expireAt:wv(t,["expires_in","expire","expireAt"])??0}})(s)},Mv=async(e,t,r)=>{const s=await e.post((e=>`${Av(e)}/rtc_mapper/batch/get`)(t),{data:r},{operation:"getUserIdsWithRtcUids"});return(e=>{const t=Ev(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)},Uv=async(e,t)=>{const r=await e.get((e=>`${Av(e)}/users/${encodeURIComponent(e.userId)}/resources`)(t),{operation:"getSelfIdsOnOtherPlatform"});return((e,t)=>{const r=yu(e)&&Array.isArray(e.data)?e.data:[],s=[];for(const n of r){if(!yu(n))continue;const e=Rv(n,["res","resource","clientResource"]);e&&e!==t.clientResource&&s.push(`${t.userId}/${e}`)}return s})(r,t)},Lv=(...e)=>{const t={},r={};for(const s of e)Object.assign(t,s.common),Object.assign(r,s.apis);return{common:t,apis:r}},kv={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:{}},Dv=e=>({userId:e}),Pv=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),xv=e=>e,Fv=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,Pv(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,xv(t))}for(const o of r)s.has(o)||s.set(o,Dv(o));return s};class Bv{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 Gv{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 qv{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 $v=0,jv=1,Vv=2,Kv=3,zv=4,Hv=5,Wv=0,Jv=0,Qv=1,Zv=1001,Yv=1002,Xv=1003,eI=1004,tI=1005,rI=1101,sI=Lv(kv,{common:{},apis:{getSelfIdsOnOtherPlatform:{range:"202,300-303",errors:{}},getTokenExpireTimestamp:{range:"",errors:{}},getRtcTokenInfo:{range:"",errors:{}},getUserIdsWithRtcUids:{range:"",errors:{}}}}),nI=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 $g,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 Gv({windowMs:this.config.profileSync.userInfoWindowMs,batchSize:this.config.profileSync.userInfoBatchSize,maxConcurrency:3,maxRetries:1,onFlush:async e=>{await this.flushUserInfoHydrationTargets(e)}}),this.groupNamecardHydrationQueue=new Bv({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),[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=>{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 su(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=Zy.validateOrThrow(Xy,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=Zy.validateOrThrow(tv,n),a=Zy.validateOrThrow(rv,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 qv(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=>{Uh?.reset(),Uh=new Mh(e)})({requestAdapter:s.request,onDiagnostic:(e,t)=>{Vs(e,t)}});const n=(e=>Uh?.startSession(e))({appKey:e??"default#appkey",uid:o.userId,sdkVersion:uv,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=>{Dh(e)}).catch(()=>{Dh("unknown")});const a=Ph({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(Tv(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,Lh({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=Cv(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}),kh(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}),kh(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}),kh(void 0),this.updateState(t),d.dispose(),e}h=e.wsUrl,m=e.restApiUrl;const r=Cv(m);y=this.config.enableMd5Check,this.contactSyncWsUrls=[r],this.syncConversationListConfigWsUrls=[r],this.contactSyncDnsResolved=!1,kh(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),xh(),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,xh(),d.dispose(),e}const b=new qp({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,Lh({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),xh()}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(),xh()}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(),xh()}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=Zy.validateOrThrow(sv,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 Jy(n.restBaseUrl,{errorMap:sI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});i.setAuthToken(t),Vs("Renew token started",{userId:r.userId});const o=await Nv(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=Zy.validateOrThrow(nv,e),r=this.getRestContext(),s=new Jy(r.restBaseUrl,{errorMap:sI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),Vs("Get RTC token info started",{userId:r.userId,hasChannelName:Boolean(t?.channelName)}),Ov(s,r,t)}async getUserIdsWithRTCUids(e){const t=Zy.validateOrThrow(iv,e),r=this.getRestContext(),s=new Jy(r.restBaseUrl,{errorMap:sI,requestAdapter:this.platformAdapter?.request,includeRequestId:!0});return s.setAuthToken(r.token),Vs("Get userIds with RTC UIDs started",{userId:r.userId,count:t.length}),Mv(s,r,t)}async getSelfIdsOnOtherPlatform(){const e=this.getRestContext(),t=new Jy(e.restBaseUrl,{errorMap:sI,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}),Uv(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 jy({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:tl(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 Fv([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=Yu(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=>{Qu.delete(e)})(e);const t={userInfoUpdateTime:this.resolveCurrentUserInfoUpdateTime(),namecardUpdateTime:"groupChat"===e.conversationType?this.resolveCurrentGroupNamecardUpdateTime(e.conversationId):void 0};Zu(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 qg({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(Ay),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 xy(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 Qy(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 Tv(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=[Cv(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:Kv,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(),xh()}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??lv,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)}};nI.instance=null;let iI=nI;const oI=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),aI=(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()},cI=e=>`mark_${String(e)}`,dI=(e,t)=>{if("singleChat"===e||"groupChat"===e||"chatRoom"===e)return e;throw oI(t,`${t} must be one of singleChat, groupChat, chatRoom`)},uI=e=>"singleChat"===e?"chat":"groupChat"===e?"groupchat":"chatroom",lI=e=>"string"==typeof e&&e.length>0?e:void 0,hI=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}},pI=e=>yu(e)?e:void 0,mI=(e,t)=>{const r=pI(e);if(!r)return;const s=(e=>"string"==typeof e?vu(e,{}):pI(e)??{})(r.payload),n=Array.isArray(s.bodies)?s.bodies:[],i=pI(n[0])??pI(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:lI(t.msg)??lI(t.content)??""};if("custom"===e){const e=pI(t.customExts)??pI(t.params)??{},r={};for(const[t,s]of Object.entries(e))"string"==typeof s&&(r[t]=s);return{event:lI(t.customEvent)??lI(t.event)??"",params:r}}if("cmd"===e)return{action:lI(t.action)??""};if("image"===e){const e=lI(t.url)??lI(t.remotePath)??"";return{localUrl:"",filename:lI(t.filename)??lI(t.displayName),filetype:lI(t.filetype)??"application/octet-stream",width:hI(t.width),height:hI(t.height),isGif:!0===t.isGif||1===t.subType,isOriginalImage:!0===t.isOriginalImage,originalImageUrl:e,bigImageUrl:lI(t.bigImageUrl),thumbnailUrl:lI(t.thumbnailUrl)??lI(t.thumbnailRemotePath),secret:lI(t.secret)??lI(t.secretKey),fileLength:hI(t.fileLength)}}return"file"===e?{url:lI(t.url)??lI(t.remotePath),filename:lI(t.filename)??lI(t.displayName),filetype:lI(t.filetype)??"application/octet-stream",fileSize:hI(t.fileSize),fileLength:hI(t.fileLength),secret:lI(t.secret)??lI(t.secretKey)}:"voice"===e?{url:lI(t.url)??lI(t.remotePath),filename:lI(t.filename)??lI(t.displayName),filetype:lI(t.filetype)??"application/octet-stream",duration:hI(t.duration)??0,fileLength:hI(t.fileLength),secret:lI(t.secret)??lI(t.secretKey)}:"video"===e?{url:lI(t.url)??lI(t.remotePath),filename:lI(t.filename)??lI(t.displayName),filetype:lI(t.filetype)??"application/octet-stream",duration:hI(t.duration)??0,width:hI(t.width),height:hI(t.height),fileLength:hI(t.fileLength),secret:lI(t.secret)??lI(t.secretKey),thumbnailUrl:lI(t.thumbnailUrl)??lI(t.thumbnailRemotePath)}:"location"===e?{latitude:hI(t.latitude)??0,longitude:hI(t.longitude)??0,address:lI(t.address),buildingName:lI(t.buildingName)}:null})(o,i);if(!a)return;const c=lI(s.from)??lI(r.from)??"",d=lI(s.to)??t.conversationId,u=pI(s.sender),l={userId:lI(u?.userId)??c,nickname:lI(u?.nickname),avatarUrl:lI(u?.avatarUrl)},h=pI(s.ext)??{},p=(e=>{const t=pI(e);if(!t)return;const r=lI(t.operatorId)??lI(t.operator),s=hI(t.operationCount)??hI(t.count),n=hI(t.operationTime)??hI(t.edit_time);return r&&void 0!==s&&void 0!==n?{operatorId:r,operationCount:s,operationTime:n}:void 0})(s.modifiedInfo??pI(s.meta)?.edit_msg);return{msgServerId:lI(r.id)??t.messageId,msgLocalId:lI(r.msgLocalId)??"",from:c,to:d,sender:l,conversationId:t.conversationId,conversationType:t.conversationType,type:o,sendStatus:"sent",ext:h,timestamp:hI(r.timestamp)??t.timestamp,body:a,direct:c===t.currentUserId?"SEND":"RECEIVE",...p?{modifiedInfo:p}:{}}},fI=e=>`${e.conversationType}:${e.conversationId}`,gI=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},yI=async(e,t,r,s)=>{const n=gI(t),i=(e=>{const t=e,r=t.conversations;if(void 0!==r){if(!Array.isArray(r)||0===r.length)throw oI("params.conversations","params.conversations must be a non-empty array");return r.map((e,t)=>{if(!yu(e))throw oI(`params.conversations.${String(t)}`,`params.conversations.${String(t)} must be an object`);return{conversationId:aI(e.conversationId,`params.conversations.${String(t)}.conversationId`),conversationType:dI(e.conversationType,`params.conversations.${String(t)}.conversationType`)}})}return[{conversationId:aI(t.conversationId,"params.conversationId"),conversationType:dI(t.conversationType,"params.conversationType")}]})(r),o=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0||e>19)throw oI(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:cI(o),targets:i.map(e=>({to:e.conversationId,type:uI(e.conversationType)}))},operation:s?"addConversationMark":"removeConversationMark"}),c=(e=>{if(!Array.isArray(e))return new Set;const t=new Set;return e.forEach(e=>{if(!yu(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(fI({conversationId:r,conversationType:s}))}),t})((yu(a)&&yu(a.data)?a.data:{}).ignore),d=[],u=[];for(const l of i){const e={conversationId:l.conversationId,conversationType:l.conversationType};c.has(fI(l))?u.push({...e,reason:"ignored_by_server"}):d.push(e)}return{succeeded:d,failed:u,mark:o,operation:s?"addMark":"removeMark"}},vI=async(e,t,r,s)=>{const n=gI(t),i=aI(r.conversationId,"params.conversationId"),o=dI(r.conversationType,"params.conversationType"),a=aI(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:uI(o),pin_msg_id:a},operation:s?"pinMessage":"unpinMessage"}),{conversationId:i,conversationType:o,messageId:a,operation:s?"pin":"unpin"}},II=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],bI=(e,t)=>`${e}\0${t}`,_I=(e,t,r)=>{const s={userId:e};for(const n of II){const e=r?.[n]??t?.[n];void 0!==e&&(s[n]=e)}return s},TI=e=>_I(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),CI=(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(bI(n.groupId,n.user.userId),t.namecard)}return s},SI=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}),[]}},EI=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})}}))},wI=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=bI(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,TI(n));return r})(e.cacheManager,r),n=r.filter(e=>!s.has(e)),i=new Set(n),o=CI(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=bI(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([SI(n,e.fetchUserInfos),EI(a,e.hydrateGroupNamecards)]),d=new Map(c.map(e=>[e.userId,e])),u=CI(e.cacheManager,t,e.includeNameCard),l=new Map;for(const h of t){const e=h.user.userId,t=bI(h.groupId,e),r=_I(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))}},RI=async e=>{const t=await wI({...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(bI(e.groupId.trim(),n));i&&r.set(n,i)}return{usersById:r,fetchedUserInfos:t.fetchedUserInfos,missingUserIds:t.missingUserIds}},AI=Lf(["singleChat","groupChat","chatRoom"]),NI=Uf(Rf()).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"),OI=Of({path:Sf().min(1,"data.path is required"),size:Ef().optional(),name:Sf().optional(),type:Sf().optional()}),MI=Of({uri:Sf().min(1,"data.uri is required"),size:Ef().optional(),name:Sf().optional(),type:Sf().optional()}),UI=Mf(["undefined"!=typeof File?((e,t={message:`Input not instance of ${e.name}`})=>_f(t=>t instanceof e,t))(File):Af(),OI,MI]),LI=Of({conversationId:Sf().min(1,"conversationId is required"),conversationType:AI,ext:NI.optional(),timestamp:Ef().int().positive("timestamp must be a positive integer").optional(),receiverList:Nf(Sf().min(1,"receiverList item is required")).nonempty("receiverList must not be empty").optional(),deliverOnlineOnly:wf().optional(),webhookEnv:Sf().optional(),priority:Lf(["high","normal","low"]).optional(),needReadReceipt:wf().optional(),isChatThread:wf().optional()}),kI=Of({type:Sf().min(1,"messageList.type is required"),sender:Of({userId:Sf().min(1,"messageList.sender.userId is required"),nickname:Sf().optional(),avatarUrl:Sf().optional()}),conversationId:Sf().min(1,"messageList.conversationId is required"),conversationType:AI,timestamp:Ef().int().positive("messageList.timestamp must be positive"),body:Uf(Rf()),combineLevel:Ef().int().min(0).max(10).optional()}).passthrough(),DI=e=>e.superRefine((e,t)=>{e.receiverList&&"singleChat"===e.conversationType&&t.addIssue({code:Hp.custom,message:"receiverList is only allowed for group or chat room conversation",path:["receiverList"]}),e.isChatThread&&"groupChat"!==e.conversationType&&t.addIssue({code:Hp.custom,message:"isChatThread is only allowed for group conversation",path:["isChatThread"]}),e.needReadReceipt&&"chatRoom"===e.conversationType&&t.addIssue({code:Hp.custom,message:"needReadReceipt is not allowed for chatRoom conversation",path:["needReadReceipt"]})}),PI=DI(LI.extend({content:Sf().min(1,"content is required"),targetLanguages:Nf(Sf().min(1)).optional()})),xI=DI(LI.extend({originalUrl:Sf().min(1,"originalUrl is required").optional(),filename:Sf().min(1,"filename is required").optional(),filetype:Sf().min(1,"filetype is required").optional(),width:Ef().positive("width must be positive").optional(),height:Ef().positive("height must be positive").optional(),isGif:wf().optional(),isOriginalImage:wf().optional(),fileLength:Ef().positive("fileLength must be positive").optional(),data:UI.optional(),thumbnailUrl:Sf().min(1).optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),FI=DI(LI.extend({originalUrl:Sf().min(1,"originalUrl is required").optional(),filename:Sf().min(1,"filename is required").optional(),filetype:Sf().min(1,"filetype is required").optional(),fileSize:Ef().positive("fileSize must be positive").optional(),fileLength:Ef().positive("fileLength must be positive").optional(),data:UI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),BI=DI(LI.extend({originalUrl:Sf().min(1,"originalUrl is required").optional(),filename:Sf().min(1,"filename is required").optional(),filetype:Sf().min(1,"filetype is required").optional(),duration:Ef().positive("duration must be positive"),fileLength:Ef().positive("fileLength must be positive").optional(),data:UI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),GI=DI(LI.extend({originalUrl:Sf().min(1,"originalUrl is required").optional(),filename:Sf().min(1,"filename is required").optional(),filetype:Sf().min(1,"filetype is required").optional(),duration:Ef().positive("duration must be positive"),width:Ef().positive("width must be positive").optional(),height:Ef().positive("height must be positive").optional(),fileLength:Ef().positive("fileLength must be positive").optional(),thumbnailUrl:Sf().min(1).optional(),data:UI.optional()}).refine(e=>Boolean(e.originalUrl||e.data),{message:"originalUrl or data is required",path:["originalUrl"]})),qI=DI(LI.extend({latitude:Ef(),longitude:Ef(),address:Sf().min(1).optional(),buildingName:Sf().min(1).optional()})),$I=DI(LI.extend({action:Sf().min(1,"action is required")})),jI=DI(LI.extend({event:Sf().min(1,"event is required"),params:Uf(Sf()).optional()})),VI=DI(LI.extend({title:Sf().min(1,"title is required"),summary:Sf().min(1,"summary is required"),compatibleText:Sf().min(1).optional(),messageList:Nf(kI).min(1,"messageList must not be empty").max(300,"messageList max length is 300")})),KI=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}},zI=()=>jh(),HI=(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=$h(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},WI=e=>!!e.isGif||(e.isOriginalImage??!1),JI=(e,t,r,s,n)=>({msgServerId:"",msgLocalId:n??jh(),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}),QI=(e,t)=>{const r=Zy.validateOrThrow(VI,e),s=r.messageList,n=KI(t);cp(s);const i=dp(s);up(i);const o={title:r.title,summary:r.summary,messageList:s,filename:"combine",filetype:"application/octet-stream",combineLevel:i},a=JI(r,n,"combine",o);return((e,t)=>{t&&rl.set(e,t)})(a,r.compatibleText),a},ZI=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}`},YI=e=>{const t=new Uint8Array(fa.util.base64.length(e));return fa.util.base64.decode(e,t,0),t},XI=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),eb=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})}},tb=e=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):"",rb=e=>{if("string"!=typeof e)return"";const t=e.trim();return t&&"undefined"!==t&&"null"!==t?t:""},sb=e=>({userId:e}),nb=(e,t)=>{if(!XI(e)||!XI(e.data))throw zy({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},ib=(e,t)=>{if(!XI(e)||!Array.isArray(e.data))throw zy({apiName:t,message:`${t} response data is invalid`,mapped:!1});return e.data},ob=(e,t)=>Array.isArray(e)?e:ib(e,t),ab={txt:"text",img:"image",video:"video",file:"file",loc:"location",custom:"custom",combine:"combine"},cb={text:"txt",image:"img",video:"video",file:"file",location:"loc",custom:"custom",combine:"combine"},db={chat:"singleChat",chatroom:"chatRoom",groupchat:"groupChat",singleChat:"singleChat",chatRoom:"chatRoom",groupChat:"groupChat"},ub=(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)},lb=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},hb=(e,t,r)=>{const s=tb(r.contentType??r.type),n=cb[s];if(!n)return null;const i=XI(r.content)?r.content:{},o=((e,t)=>{const r=tb(t.conversationType);if("groupchat"===r||"chatroom"===r)return tb(t.receiverId);const s=tb(t.senderId);return s===e?tb(t.receiverId):s})(t,r),a=db[tb(r.conversationType)]??"singleChat",c={msgServerId:tb(r.messageId),msgLocalId:tb(r.messageId),from:tb(r.senderId),to:tb(r.receiverId),conversationId:o,conversationType:a,type:n,ext:XI(r.ext)?r.ext:{},timestamp:"number"==typeof r.sentTime?r.sentTime:new Date(tb(r.sentTime)).getTime(),sender:{userId:tb(r.senderId)},highlight:lb(r.highlight),text:"string"==typeof r.text?r.text:void 0};let d;const u=tb(i.remotePath??i.url),l=tb(i.secret??i.secretKey);switch(n){case"txt":d={type:"txt",content:tb(i.message??r.text)};break;case"img":{const t=ub(e,u,l);d={type:"img",url:t,thumb:i.thumb?ub(e,tb(i.thumb),tb(i.thumb_secret??i.thumbnailSecretKey)):`${t}&thumbnail=true`,secret:l,width:Number(i.width??(XI(i.size)?i.size.width:0))||0,height:Number(i.height??(XI(i.size)?i.size.height:0))||0,fileLength:Number(i.file_length??i.fileLength??0)};break}case"video":d={type:"video",url:ub(e,u,l),thumb:i.thumb||i.thumbnailRemotePath?ub(e,tb(i.thumb??i.thumbnailRemotePath),tb(i.thumb_secret??i.thumbnailSecretKey)):"",secret:l,filename:tb(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:ub(e,u,l),secret:l,filename:tb(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:tb(i.addr??i.address),buildingName:tb(i.buildingName)};break;case"custom":d={type:"custom",customEvent:tb(i.customEvent),customExts:XI(i.customExts)?i.customExts:{}};break;default:return null}return{...c,body:d}},pb=async(e,t,r)=>{const s=`${ZI(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=>ab[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=XI(i)?i:{},a=XI(o.data)?o.data:o,c=XI(a.data)?a.data:a,d=Array.isArray(c.items)?c.items:Array.isArray(c.list)?c.list:[],u=XI(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(!XI(g))continue;const e=hb(t,t.userId,g);e&&f.push(e)}return{messages:f,pageNum:l,pageSize:h,totalPages:p,isLast:m}},mb=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/api/sdk/v1/${t}/${r}`},fb=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),gb=e=>fb(e)&&"string"==typeof e.path&&e.path.trim().length>0,yb=e=>(e=>"undefined"!=typeof File&&e instanceof File)(e)||gb(e),vb=e=>{if(!fb(e))return;return{data:fb(e.data)?e.data:void 0,error:fb(e.error)?e.error:void 0}},Ib=(e,t)=>{const r=vb(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},bb=(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}),_b=e=>!(void 0===e||fb(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))),Tb=e=>{if(!e)return;const t=(e.split("#")[0]?.split("?")[0]??"").split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0},Cb=e=>{const{serviceCode:t,serviceMessage:r}=(e=>{const t=e instanceof ut&&fb(e.details)?e.details:void 0,r=vb(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 bb("File upload failed",ot.UPLOAD_REQUEST_FAILED,{cause:e.details});if(e instanceof ut&&!t)return e;if(t)switch(t){case"4041001":return bb("File not found",ot.VOICE_TO_TEXT_FILE_NOT_FOUND,{serviceCode:t,serviceMessage:r});case"4001002":return bb("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{serviceCode:t,serviceMessage:r},"validation");case"5021001":return bb("File upload failed",ot.UPLOAD_REQUEST_FAILED,{serviceCode:t,serviceMessage:r});case"4001003":return bb("Voice duration exceeds 60 seconds",ot.VOICE_TO_TEXT_FILE_DURATION_TOO_LONG,{serviceCode:t,serviceMessage:r},"validation");case"4031001":return bb("Voice-to-text service is not enabled",ot.SERVICE_NOT_ENABLED,{serviceCode:t,serviceMessage:r});case"4031002":return bb("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)?bb("File too large",ot.VOICE_TO_TEXT_FILE_TOO_LARGE,{serviceCode:t,serviceMessage:r}):bb(r||"Missing or invalid request parameter",ot.VALIDATION_REQUIRED,{serviceCode:t,serviceMessage:r},"validation");case"5021003":case"5001003":return bb("Voice-to-text failed",ot.VOICE_TO_TEXT_FAILED,{serviceCode:t,serviceMessage:r});case"4011001":return bb(r||"Unauthorized or invalid token",ot.AUTH_UNAUTHORIZED,{serviceCode:t,serviceMessage:r},"auth");default:return bb(r||(e instanceof Error?e.message:"Voice-to-text failed"),ot.VOICE_TO_TEXT_FAILED,{serviceCode:t,serviceMessage:r})}return e instanceof ut?bb(e.message,e.code,e.details):bb(e instanceof Error?e.message:"Voice-to-text failed",ot.VOICE_TO_TEXT_FAILED)},Sb=(e,t)=>{if(!fb(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 bb("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody"},"validation");var r;if(_b(t))throw bb("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!e.url)throw bb("File not found",ot.VOICE_TO_TEXT_FILE_NOT_FOUND,{path:"voiceMessageBody.url"});if(!Tb(e.url))throw bb("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceMessageBody.url"},"validation");return e},Eb=(e,t)=>{if(_b(t))throw bb("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"voiceParams"},"validation");if(!yb(e))throw bb("Invalid file",ot.VOICE_TO_TEXT_FILE_INVALID,{path:"file"},"validation");return e},wb=async(e,t,r,s)=>{const n=Sb(r,s),i=Tb(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(`${mb(t)}/speech/transcriptions`,{data:{fileId:i,username:t.userId,...s?{audio:s}:{}}},{operation:"voiceMessageToText"});return{text:Ib(r,"voiceMessageToText")}}catch(o){throw Cb(o)}},Rb=Of({keywordList:Nf(Sf()).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:Lf(["or","and"]).optional(),conversationId:Sf().min(1).optional(),conversationType:Lf(["singleChat","groupChat","chatRoom"]).optional(),msgTypes:Nf(Lf(["txt","img","video","file","loc","custom","combine"])).optional(),startTime:Ef().optional(),endTime:Ef().optional(),searchScope:Lf(["none","with","only"]).optional(),direction:Lf(["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"}),Ab=Of({option:Rb,pageNum:Ef().int().min(1).default(1),pageSize:Ef().int().min(1).max(100).default(20)}),Nb=Lv(kv,{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"]}}}}}),Ob=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=Zy.validateOrThrow(PI,e),s=KI(t),n=zI(),i={content:r.content};return r.targetLanguages&&(i.targetLanguages=r.targetLanguages),JI(r,s,"text",i,n)})(e,this.buildMessageSenderOrThrow())}createImageMessage(e){return((e,t,r)=>{const s=Zy.validateOrThrow(xI,e),n=KI(t),i=zI(),o=s.data?HI(void 0,s.data):"",a=s.originalUrl?Ts(s.originalUrl,{deriveVariants:!r?.useCustomAttachmentUpload}):void 0;s.data&&qh.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:WI({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),JI(s,n,"image",d,i)})(e,this.buildMessageSenderOrThrow(),this.getClientOrThrow().getMessageCreationOptions())}createFileMessage(e){return((e,t)=>{const r=Zy.validateOrThrow(FI,e),s=KI(t),n=zI(),i=HI(r.originalUrl,r.data);r.data&&qh.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),JI(r,s,"file",o,n)})(e,this.buildMessageSenderOrThrow())}createVoiceMessage(e){return((e,t)=>{const r=Zy.validateOrThrow(BI,e),s=KI(t),n=zI(),i=HI(r.originalUrl,r.data);r.data&&qh.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),JI(r,s,"voice",o,n)})(e,this.buildMessageSenderOrThrow())}createVideoMessage(e){return((e,t)=>{const r=Zy.validateOrThrow(GI,e),s=KI(t),n=zI(),i=HI(r.originalUrl,r.data);r.data&&qh.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),JI(r,s,"video",o,n)})(e,this.buildMessageSenderOrThrow())}createLocationMessage(e){return((e,t)=>{const r=Zy.validateOrThrow(qI,e),s=KI(t),n={latitude:r.latitude,longitude:r.longitude};return r.address&&(n.address=r.address),r.buildingName&&(n.buildingName=r.buildingName),JI(r,s,"location",n)})(e,this.buildMessageSenderOrThrow())}createCmdMessage(e){return((e,t)=>{const r=Zy.validateOrThrow($I,e),s=KI(t),n={action:r.action};return void 0!==r.deliverOnlineOnly&&(n.deliverOnlineOnly=r.deliverOnlineOnly),JI(r,s,"cmd",n)})(e,this.buildMessageSenderOrThrow())}createCustomMessage(e){return((e,t)=>{const r=Zy.validateOrThrow(jI,e),s=KI(t),n={event:r.event};return r.params&&(n.params=r.params),JI(r,s,"custom",n)})(e,this.buildMessageSenderOrThrow())}createCombineMessage(e){return QI(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(Ay);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=gI(t),n=aI(r.conversationId,"params.conversationId"),i=dI(r.conversationType,"params.conversationType"),o=r.deleteRoamingMessages??!1;if("boolean"!=typeof o)throw oI("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":uI(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=gI(t),n=aI(r.conversationId,"params.conversationId"),i=dI(r.conversationType,"params.conversationType");if("boolean"!=typeof r.pinned)throw oI("params.pinned","params.pinned must be a boolean");const o="groupChat"===i?"groupChat":uI(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=yu(a)&&yu(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)=>yI(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)=>yI(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=gI(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)=>vI(e,t,r,!0))(this.getRestClient(t),t,e))}async unpinMessage(e){const t=this.getRestContextOrThrow();await this.executeRestOperation(()=>(async(e,t,r)=>vI(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=gI(t),n=aI(r.conversationId,"params.conversationId"),i=dI(r.conversationType,"params.conversationType"),o=await e.get(`/${s.orgName}/${s.appName}/sdk/user/${s.encodedUserId}/user_channel/pin?to=${encodeURIComponent(n)}&type=${encodeURIComponent(uI(i))}&limit=${String(20)}`,{operation:"getPinnedMessageList"}),a=yu(o)&&yu(o.data)?o.data:{},c=(Array.isArray(a.msg_infos)?a.msg_infos:[]).reduce((e,r)=>{if(!yu(r))return e;const s="string"==typeof r.pin_msg_id?r.pin_msg_id:yu(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=mI(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});const t=this.requireConnectedClient(),r=this.getCurrentUserIdOrThrow();await t.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 s=Date.now(),n=t.getCurrentUserId()===r?t.getCacheManager():null,i=n?.loadSessionList().find(t=>t.conversationId===e.conversationId&&t.conversationType===e.conversationType&&t.lastMessage?.msgServerId===e.messageId)?.lastMessage,o=i?.modifiedInfo??n?.loadConversationSummaries().find(t=>t.conversationId===e.conversationId&&t.type===e.conversationType&&t.lastMessage?.msgId===e.messageId)?.lastMessage?.modifiedInfo,a={operatorId:r,operationCount:(o?.operationCount??0)+1,operationTime:s},c={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:s,body:e.message.body,direct:"SEND",modifiedInfo:a};return t.getCurrentUserId()===r&&t.patchConversationLastMessage(e,{type:c.type,body:{...c.body},ext:c.ext,modifiedInfo:a}),c}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=`${ZI(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=nb(i,"getHistoryMessages"),a=Array.isArray(o.msgs)?o.msgs:[],c=[];for(const d of a){if(!XI(d)||"string"!=typeof d.msg||0===d.msg.length)continue;const e=s(YI(d.msg));e&&c.push(e)}return{items:c,cursor:rb(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=Zy.validateOrThrow(Ab,e),r=this.getRestContextOrThrow();return this.executeRestOperation(()=>pb(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?`${ZI(t)}/sdk/message/roaming/${n}/user/${t.userId}?${s}=${encodeURIComponent(r.conversationId)}&msgIdList=${encodeURIComponent(r.messageIds.join(","))}&resource=${i}`:`${ZI(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=dv();s.set("limit",String(r.pageSize??10)),r.cursor&&s.set("key",r.cursor);const n=`${ZI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/${encodeURIComponent(r.messageId)}?${s.toString()}`,i=await e.get(n,{operation:"getGroupMessageReadUsers"}),o=nb(i,"getGroupMessageReadUsers"),a=XI(o.group_ack)?o.group_ack:o,c=(Array.isArray(a.userlist)?a.userlist:[]).map(e=>XI(e)&&"string"==typeof e.username?{userId:e.username,user:sb(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:rb(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=`${ZI(t)}/chatgroups/${encodeURIComponent(r.groupId)}/acks/batch`,n=await e.post(s,{messageIds:r.messageIds},{operation:"getGroupMessageReadReceipts"});return ib(n,"getGroupMessageReadReceipts").map(e=>XI(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(`${ZI(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=`${ZI(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=dv(),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(`${ZI(t)}/reaction/user/${t.userId}?${s.toString()}`,{operation:"getReactionList"});return ib(i,"getReactionList").map(e=>{if(!XI(e)||"string"!=typeof e.msgId)return null;const t=Array.isArray(e.reactionList)?e.reactionList:[];return{messageId:e.msgId,reactions:t.map(e=>XI(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=dv();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(`${ZI(t)}/reaction/user/${t.userId}/detail?${s.toString()}`,{operation:"getReactionDetail"}),i=nb(n,"getReactionDetail"),o=Array.isArray(i.reactionUserList)?i.reactionUserList.map(e=>XI(e)&&"string"==typeof e.userId?{userId:e.userId,user:sb(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:sb(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:rb(i.cursor),hasMore:rb(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 eb(()=>e.get(`${ZI(t)}/users/${t.userId}/translate/support/language`,{operation:"getSupportedTranslationLanguages"}));return ob(r,"getSupportedTranslationLanguages").map(e=>XI(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 eb(()=>e.post(`${ZI(t)}/users/${t.userId}/translate`,{text:r.text,to:[...r.targetLanguages]},{operation:"translateMessage"})),n=ob(s,"translateMessage"),i=XI(n[0])?n[0]:null;if(!i)throw zy({apiName:"translateMessage",message:"translateMessage response data is invalid",mapped:!1});const o=Array.isArray(i.translations)?i.translations:[],a=XI(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=>XI(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){Sb(e,t);const r=this.getRestContextOrThrow();return this.executeRestOperation(()=>wb(this.getRestClient(r),r,e,t))}async voiceFileToText(e,t){Eb(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=Eb(r,s),i=os({file:n,fallbackName:gb(n)?"voice.amr":void 0,fallbackMimeType:"audio/amr"});try{const r=await e.upload({url:`${t.restBaseUrl}${mb(t)}/speech/recognitions`,headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json",[ou]:iu()},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:Ib(n,"voiceFileToText")}}catch(o){if(o instanceof ut)throw Cb(o);throw Cb(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 Jy(e.restBaseUrl,{errorMap:Nb,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 RI({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)}};Ob.key="chatManager";let Mb=Ob;class Ub{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 Lb=e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),kb=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),Db=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw Lb(t);return e.trim()},Pb=(e,t)=>{if(void 0===e)return"";if("string"!=typeof e)throw kb(t,`${t} must be a string`);return e},xb=(e,t)=>{if(void 0===e)return 20;if("number"!=typeof e||!Number.isInteger(e)||e<=0||e>50)throw kb(t,`${t} must be an integer between 1 and 50`);return e},Fb=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},Bb=e=>yu(e)?e:null,Gb=e=>{const t=Bb(e);return t?.data??e},qb=e=>{const t=Bb(e);if(Array.isArray(t?.entities))return t.entities;const r=Gb(e);if(Array.isArray(r))return r;const s=Bb(r);return Array.isArray(s?.entities)?s.entities:Array.isArray(s?.affiliations)?s.affiliations:[]},$b=e=>{const t=Bb(e),r=Bb(t?.data),s=Bb(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)??""},jb=e=>{const t=Bb(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?vu(n,{}):Bb(n)??{},o=Array.isArray(i.bodies)?i.bodies:[],a=Bb(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}},Vb=e=>{const t=Bb(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:jb(t.lastMessage??t.last_message)}:null},Kb=e=>({items:qb(e).map(e=>Vb(e)).filter(e=>null!==e),cursor:$b(e)}),zb=async(e,t,r)=>{const s=Fb(t),n=Db(r,"chatThreadId");return(e=>{const t=Gb(e),r=Array.isArray(t)?t[0]:t,s=Vb(r);if(!s)throw kb("response.data","response.data is invalid");return s})(await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}`,{operation:"getChatThreadInfo"}))},Hb=async(e,t,r)=>{const s=Fb(t),n=Db(r.chatThreadId,"params.chatThreadId"),i=xb(r.pageSize,"params.pageSize"),o=Pb(r.cursor,"params.cursor"),a=dv({limit:String(i),cursor:o}),c=await e.get(`/${s.orgName}/${s.appName}/thread/${encodeURIComponent(n)}/users?${a.toString()}`,{operation:"getChatThreadMemberList"});return{items:qb(d=c).map(e=>{if("string"==typeof e)return{memberId:e};const t=Bb(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:$b(d)};var d},Wb=async(e,t,r)=>{const s=Fb(t);if(!Array.isArray(r.chatThreadIds)||0===r.chatThreadIds.length)throw Lb("params.chatThreadIds");if(r.chatThreadIds.length>20)throw kb("params.chatThreadIds","params.chatThreadIds must contain at most 20 items");const n=r.chatThreadIds.map((e,t)=>Db(e,`params.chatThreadIds[${t}]`)),i=await e.post(`/${s.orgName}/${s.appName}/thread/message`,{threadIds:n},{operation:"getChatThreadLastMessageList"});return{items:qb(i).map(e=>{const t=Bb(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:jb(t.lastMessage??t.last_message)}:null}).filter(e=>null!==e)}},Jb=Lv(kv,{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"]}}}}}),Qb=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 Ub(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=Fb(t),n=Db(r.parentId,"params.parentId"),i=Db(r.name,"params.name"),o=Db(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=Bb(Gb(a)),d="string"==typeof c?.thread_id?c.thread_id:void 0;if(!d)throw kb("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=Fb(t),n=Db(r.parentId,"params.parentId"),i=xb(r.pageSize,"params.pageSize"),o=Pb(r.cursor,"params.cursor"),a=dv({limit:String(i),cursor:o}),c=await e.get(`/${s.orgName}/${s.appName}/threads/chatgroups/${encodeURIComponent(n)}?${a.toString()}`,{operation:"getChatThreadList"});return Kb(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=Fb(t),n=xb(r.pageSize,"params.pageSize"),i=Pb(r.cursor,"params.cursor"),o=dv({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 Kb(c)})(this.getRestClient(t),t,e)})}async getChatThreadInfo(e){return this.runOperation("getChatThreadInfo",async()=>{const t=this.getRestContextOrThrow();return zb(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=Fb(t),n=Db(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=Fb(t),n=Db(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=Fb(t),n=Db(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=Fb(t),n=Db(r.chatThreadId,"params.chatThreadId"),i=Db(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 Hb(this.getRestClient(t),t,e)})}async removeChatThreadMember(e){return this.runOperation("removeChatThreadMember",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=Fb(t),n=Db(r.chatThreadId,"params.chatThreadId"),i=Db(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 Wb(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 Jy(e.restBaseUrl,{errorMap:Jb,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}}};Qb.key="chatThreadManager";let Zb=Qb;class Yb{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 Xb=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],e_=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},t_=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),r_=e=>({userId:e}),s_=(e,t,r)=>{const s={userId:r};for(const n of Xb){const r=t?.[n]??e?.[n];void 0!==r&&(s[n]=r)}return s},n_=async(e,t)=>{const r=e_(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,t_(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,r_(o));return s},i_=e=>yu(e)?e:null,o_=e=>"string"==typeof e?e:void 0,a_=e=>{const t=o_(e)?.trim();return t||void 0},c_=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}},d_=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},u_=e=>{const t=i_(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},l_=e=>{const t=i_(e);return t?i_(t.data)?t.data:t:null},h_=(e,t)=>{const r=i_(e),s=r&&i_(r.params),n=s?.[t];if(Array.isArray(n)&&0!==n.length)return c_(n[0])},p_=e=>a_(e.chatRoomId)??a_(e.chatroomid)??a_(e.id)??"",m_=e=>o_(e.name)??o_(e.title)??o_(e.groupname)??"",f_=e=>r_(e),g_=(e,t)=>{const r=(e=>{const t=o_(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(a_(e.owner)===t)return"owner";const s=Array.isArray(e.affiliations)?e.affiliations:[];for(const n of s){const e=i_(n);if(e){if(a_(e.owner)===t)return"owner";if(a_(e.admin)===t)return"admin";if(a_(e.member)===t)return"member"}}},y_=(e,t)=>{const r=i_(e);if(!r)return null;const s=p_(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)})(a_(r.owner)):a_(r.owner);return{chatRoomId:s,name:m_(r),owner:n?f_(n):void 0,memberCount:c_(r.memberCount)??c_(r.affiliations_count),disabled:d_(r.disabled)}},v_=(e,t)=>{const r=(e=>{const t=i_(e);return t?c_(t.count):void 0})(e),s=u_(e).map(e=>y_(e,t)).filter(e=>null!==e),n=h_(e,"pagenum"),i=h_(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}},I_=e=>u_(e).map(e=>a_(e)).filter(e=>Boolean(e)).map(e=>f_(e)),b_=(e,t)=>{const r=l_(e)??{},s=Array.isArray(r.successKeys)?r.successKeys.filter(e=>"string"==typeof e):[],n=i_(r.errorKeys)??{},i={};for(const[o,a]of Object.entries(n))"string"==typeof a&&(i[o]={code:T_(a),message:a});return{chatRoomId:t,appliedKeys:s,failedKeys:i}},__=e=>{const t=i_(e),r=t?.data,s=Array.isArray(r)?r:void 0!==r?[r]:[],n=[],i=[];return s.forEach(e=>{const t=i_(e),r=(e=>{const t=i_(e);if(!t)return null;const r=a_(t.user),s=a_(t.chatRoomId)??a_(t.chatroomid)??a_(t.id),n=o_(t.action),i=d_(t.result);return r&&s&&void 0!==n&&void 0!==i?{chatRoomId:s,user:f_(r),action:n,reason:o_(t.reason),...i?{}:{reason:o_(t.reason)??"failed"}}:null})(e);if(!r||!t)return;d_(t.result)?n.push(r):i.push(r)}),{succeeded:n,failed:i}},T_=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,C_=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},S_=e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),E_=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),w_=(e,t)=>`/${e.orgName}/${e.appName}${t}`,R_=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw E_(t,`${t} must be a string`);return e}},A_=(e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw E_(t,`${t} must be a number`);return e}},N_=(e,t)=>{const r=dv();"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}`:""},O_=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw S_(t);return e.trim()},M_=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw S_(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw E_(`${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 S_(t);return r},U_=(e,t)=>M_(e,t),L_=async(e,t,r)=>{const s=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=w_(s,`/chatrooms/${encodeURIComponent(n)}?joined_time=true&version=v3`);return((e,t)=>{const r=u_(e),s=i_(r[0])??l_(e)??{},n=y_(s)??{chatRoomId:p_(s),name:m_(s)},i=g_(s,t);return{...n,description:o_(s.description),maxMembers:c_(s.maxMembers)??c_(s.maxusers)??c_(s.max_users),createdAt:c_(s.createdAt)??c_(s.created),ext:o_(s.ext)??o_(s.custom),muteAllMembers:d_(s.mute),permissionType:i}})(await e.get(i,{operation:"getChatRoomInfo"}),t.userId)},k_=async(e,t,r)=>{const s=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i={},o=R_(r.name,"params.name"),a=R_(r.description,"params.description"),c=A_(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 S_("params");const d=w_(s,`/chatrooms/${encodeURIComponent(n)}?resource=${s.encodedResource}`);return(e=>{const t=l_(e)??{};return{nameUpdated:d_(t.groupname),descriptionUpdated:d_(t.description),maxMembersUpdated:d_(t.maxusers)}})(await e.put(d,i,{operation:"updateChatRoomInfo"}))},D_=async(e,t,r)=>{const s=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=w_(s,`/chatrooms/${encodeURIComponent(n)}/users${(e=>{const t=dv();"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 u_(e)){const e=i_(n);if(!e)continue;const r=a_(e.owner),s=a_(e.admin),i=a_(e.member),o=r??s??i;o&&t.push({user:f_(o),role:r?"owner":s?"admin":"member",joinedAt:c_(e.joinedAt)??c_(e.joined_time)})}const r=i_(e),s=r?a_(r.cursor):void 0;return{items:t,cursor:s,hasMore:"string"==typeof s&&s.length>0}})(await e.get(i,{operation:"getChatRoomMemberList"}))},P_=async(e,t,r)=>{const s=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=w_(s,`/chatrooms/${encodeURIComponent(n)}/admin`),o=await e.get(i,{operation:"getChatRoomAdminList"});return I_(o)},x_=async(e,t,r)=>{const s=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=dv();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=w_(s,`/chatrooms/${encodeURIComponent(n)}/mute?${i.toString()}`);return(e=>{const t=u_(e);if(t.every(e=>"string"==typeof e))return I_(e).map(e=>({user:e}));const r=[];for(const s of t){const e=i_(s);if(!e)continue;const t=a_(e.user)??a_(e.member)??a_(e.owner)??a_(e.admin);t&&r.push({user:f_(t),muteExpire:c_(e.muteExpire)??c_(e.expire)??c_(e.expired)})}return r.map(e=>({user:e.user,muteExpire:e.muteExpire}))})(await e.get(o,{operation:"getChatRoomMuteList"}))},F_=async(e,t,r)=>{const s=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=w_(s,`/sdk/chatrooms/${encodeURIComponent(n)}/mute/${s.encodedUserId}?version=v3`);return(e=>{const t=l_(e)??{};return{muted:d_(t.muted)??d_(t.value)??Boolean(t.data),muteExpireAt:c_(t.muteExpireAt)??c_(t.expire)??c_(t.mute_expire)}})(await e.get(i,{operation:"isCurrentUserMutedInChatRoom"}))},B_=async(e,t,r)=>{const s=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=N_(r),o=i?"&":"",a=w_(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users?version=v3${o}${i.replace("?","")}`),c=await e.get(a,{operation:"getChatRoomBlocklist"});return I_(c).map(e=>({user:e}))},G_=async(e,t,r)=>{const s=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=w_(s,`/chatrooms/${encodeURIComponent(n)}/white/users`),o=await e.get(i,{operation:"getChatRoomAllowlist"});return I_(o).map(e=>({user:e}))},q_=async(e,t,r)=>{const s=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=w_(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${s.encodedUserId}?version=v3`);return(e=>{const t=l_(e)??{};return d_(t.value)??d_(t.white)??!1})(await e.get(i,{operation:"checkIfInChatRoomAllowList"}))},$_=async(e,t,r)=>{const s=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=w_(s,`/chatrooms/${encodeURIComponent(n)}/announcement`);return(e=>{const t=l_(e)??{};return{announcement:o_(t.announcement)??""}})(await e.get(i,{operation:"getChatRoomAnnouncement"}))},j_=async(e,t,r)=>{const s=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=w_(s,`/metadata/chatroom/${encodeURIComponent(n)}`);return((e,t)=>{const r=l_(e)??{};return{chatRoomId:t,attributes:Object.fromEntries(Object.entries(r).filter(e=>"string"==typeof e[1]))}})(await e.post(i,{keys:r.keys?U_(r.keys,"params.keys"):void 0},{operation:"getChatRoomAttributes"}),n)},V_=async(e,t,r)=>{const s=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw E_(t,`${t} must be an object`);const r=Object.entries(e);if(0===r.length)throw S_(t);return Object.fromEntries(r.map(([e,r])=>{if("string"!=typeof e||0===e.trim().length)throw E_(t,`${t} contains invalid key`);if("string"!=typeof r)throw E_(`${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=w_(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${c}`),u=await e.put(d,{metaData:i,autoDelete:o?"DELETE":"NO_DELETE"},{operation:"setChatRoomAttributes"});return b_(u,n)},K_={nickname:"nickname",avatarUrl:"avatarurl",mail:"mail",phone:"phone",gender:"gender",sign:"sign",birth:"birth",ext:"ext"},z_=(e,t,r)=>new mt(e,{code:"required"===r?ot.VALIDATION_REQUIRED:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:t,message:e,rule:r}]}}),H_=(e,t)=>{if("string"!=typeof e)throw z_(`${t} must be a string`,t,"invalid_format");return e},W_=(e,t)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;throw z_(`${t} must be a string, number, or boolean`,t,"invalid_format")},J_=(e,t="attribute")=>{const r=K_[e];if(!r)throw z_(`${t} is invalid`,t,"invalid_format");return r},Q_=(e,t="params.userIds")=>{if(!Array.isArray(e)||0===e.length)throw z_(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,i]of e.entries()){const e=H_(i,`${t}[${n}]`).trim();e&&(s.has(e)||(s.add(e),r.push(e)))}if(0===r.length)throw z_(`${t} is required`,t,"required");return r},Z_=(e,t="params.attributes")=>{if(!Array.isArray(e)||0===e.length)throw z_(`${t} is required`,t,"required");const r=[],s=new Set;for(const[n,i]of e.entries()){const e=H_(i,`${t}[${n}]`);if(!(e in K_))throw z_(`${t}[${n}] is invalid`,`${t}[${n}]`,"invalid_format");s.has(e)||(s.add(e),r.push(e))}if(0===r.length)throw z_(`${t} is required`,t,"required");return r},Y_=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}/metadata/user/get`},X_=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}/metadata/user/${encodeURIComponent(e.userId)}`},eT=e=>({targets:Q_(e)}),tT=e=>!!yu(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),rT=(e,t)=>{if(Array.isArray(e))for(const r of e){if(!yu(r))continue;const e="string"==typeof r.username?r.username:"";e&&t.set(e,r)}},sT=(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},nT=(e,t)=>{const r=(e=>{const t=new Map,r=yu(e)?e:null;if(r?.data&&yu(r.data))for(const[s,n]of Object.entries(r.data))tT(n)&&t.set(s,n);return rT(r?.entities,t),rT(r?.data&&yu(r.data)?r.data.entities:void 0,t),t})(e),s=(e=>{const t=new Map,r=yu(e)?e:null;if(!r?.lastModified||!yu(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:sT(i,e),lastModified:s.get(i)})}return n},iT=(e,t)=>nT(e,t).map(e=>e.profile),oT=(e,t,r,s)=>{void 0!==r&&("gender"!==t?e.push([t,H_(r,s)]):e.push([t,String(W_(r,s))]))},aT=e=>e.map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"),cT={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},dT=Lv(kv,{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}}}}}),uT=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=cT[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=cT[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=C_(t),n=w_(s,`/chatrooms${N_(r)}`),i=await e.get(n,{operation:"getChatRoomList"});return v_(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 Yb(t,this);return this.chatRoomRegistry.set(t,s),s}async getChatRoomInfo(e){return this.runOperation("getChatRoomInfo",async()=>{const t=this.getRestContextOrThrow(),r=await L_(this.getRestClient(t),t,e);return this.hydrateChatRoomDetailUsers(r)})}async updateChatRoomInfo(e){return this.runOperation("updateChatRoomInfo",async()=>{const t=this.getRestContextOrThrow();return k_(this.getRestClient(t),t,e)})}async joinChatRoom(e){return this.runOperation("joinChatRoom",async()=>{const t=this.requireClient(),r=O_(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=O_(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 D_(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=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=M_(r.userIds,"params.userIds"),o=w_(s,`/chatrooms/${encodeURIComponent(n)}/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"removeChatRoomMembers"});return __(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAdminList(e){return this.runOperation("getAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await P_(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=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=O_(r.userId,"params.userId"),o=w_(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=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=O_(r.userId,"params.userId"),o=w_(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 x_(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=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=M_(r.userIds,"params.userIds"),o=A_(r.duration,"params.duration"),a=w_(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=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=M_(r.userIds,"params.userIds"),o=w_(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=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=w_(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=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=w_(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 F_(this.getRestClient(t),t,e)})}async getBlocklist(e){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await B_(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=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=M_(r.userIds,"params.userIds"),o=1===i.length,a=w_(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)})(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=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=M_(r.userIds,"params.userIds"),o=w_(s,`/chatrooms/${encodeURIComponent(n)}/blocks/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"unblockChatRoomMembers"});return __(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async getAllowlist(e){return this.runOperation("getAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await G_(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=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=M_(r.userIds,"params.userIds"),o=w_(s,`/chatrooms/${encodeURIComponent(n)}/white/users?resource=${s.encodedResource}`),a=await e.post(o,{usernames:i},{operation:"addUsersToChatRoomAllowlist"});return __(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=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=M_(r.userIds,"params.userIds"),o=w_(s,`/chatrooms/${encodeURIComponent(n)}/white/users/${i.map(e=>encodeURIComponent(e)).join(",")}?resource=${s.encodedResource}`),a=await e.delete(o,{operation:"removeUsersFromChatRoomAllowlist"});return __(a)})(this.getRestClient(t),t,e);return this.hydrateActionListResult(r)})}async checkIfInAllowList(e){return this.runOperation("checkIfInAllowList",async()=>{const t=this.getRestContextOrThrow();return q_(this.getRestClient(t),t,e)})}async getAnnouncement(e){return this.runOperation("getAnnouncement",async()=>{const t=this.getRestContextOrThrow();return $_(this.getRestClient(t),t,e)})}async updateAnnouncement(e){return this.runOperation("updateAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=R_(r.announcement,"params.announcement");if(void 0===i)throw S_("params.announcement");const o=w_(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 j_(this.getRestClient(t),t,e)})}async setAttributes(e){return this.runOperation("setAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await V_(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=C_(t),n=O_(r.chatRoomId,"params.chatRoomId"),i=U_(r.keys,"params.keys"),{isForced:o=!1}=r,a=o?"/forced":"",c=w_(s,`/metadata/chatroom/${encodeURIComponent(n)}/user/${s.encodedUserId}${a}`),d=await e.request(c,{method:"DELETE",body:{keys:i},operation:"removeChatRoomAttributes"});return b_(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 Jy(e.restBaseUrl,{errorMap:dT,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(e.token),this.restBaseUrl=e.restBaseUrl,this.restToken=e.token),this.restClient}requireClient(){if(!this.client)throw new 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 n_(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=e_(e),s=await n_(r,t);return r.map(e=>s_(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=eT(e),s=await this.getRestClient(t).request(Y_(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return iT(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 s_(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>s_(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:s_(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:s_(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:s_(e.owner,t.get(e.owner.userId),e.owner.userId)}}};uT.key="chatRoomManager";let lT=uT;const hT={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:{}}}},pT="User ID is invalid: cannot add yourself as a contact",mT=(e,t,r)=>{if(!yu(e)||!yu(e.data))return;const s=e.data[t];if(Array.isArray(s))for(const n of s)if(yu(n)&&"string"==typeof n.failReason&&n.failReason.toLowerCase().includes(r))return n.failReason},fT=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},gT=e=>yu(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):[],yT=(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&&yu(e),s},vT=async(e,t,r)=>{const s=fT(t),n=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/contacts/apply?resource=${s.encodedResource}`;(e=>{const t=mT(e,"applyYourselfUsers","user cannot apply to become a new friend");if(t)throw new mt(pT,{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:pT,rule:"invalid_format"}]}});const r=mT(e,"notExistUsers","the users not exist");if(!r)return;const s=Ky(hT,"addContact",{error:"USER_NOT_FOUND"});if(!s)throw zy({apiName:"addContact",serverMessage:r,mapped:!1,reasonKey:"USER_NOT_FOUND"});throw zy({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"}))},IT=async(e,t)=>{const r=fT(t),s=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/blocks/users`,n=await e.get(s,{operation:"getBlocklist"});return gT(n).map(e=>({userId:e}))},bT=async(e,t,r)=>{const s=fT(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:gT(i).map(e=>({userId:e})),failed:[]}},_T={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 TT=!1,CT=null;const ST=()=>CT||(TT||(fa.util.Long=Dn,fa.configure(),TT=!0),Va(),CT=fa.Root.fromJSON(_T),ja(CT),CT),ET=e=>"number"==typeof e?e:Dn.isLong(e)?e.toNumber():0,wT=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:ET(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:ET(t.protocolVersion)}};class RT{encodeRequest(e){const t=ST().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=Wv){const t=ST().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:Vv,status:e})).finish()}decode(e){const t=ST(),r=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(r.type){case jv:return{type:jv};case Vv:{const r=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:Vv,status:ET(r.status)}}case zv:{const r=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:zv,header:wT(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:ET(t.createdAt),updatedAt:ET(t.updatedAt),metadataUpdatedAt:ET(t.metadataUpdatedAt)}})(e)):[],cursor:ET(r.cursor),version:"string"==typeof r.version?r.version:"",responseType:ET(r.responseType)||Jv}}case Hv:{const r=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:Hv,header:wT(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:$v}}}}class AT{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===Qv?"incremental":"full",version:this.version,pages:this.pages}}}const NT=e=>e.type===zv,OT=e=>"message"in e&&"code"in e;class MT{constructor(e){this.codec=new RT,this.sharedSession=e}async sync(e){const t=new AT(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:NT(t)||OT(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(e,r)=>{try{if(e.type===jv)return void(await r.send(this.codec.encodePong()));if(NT(e)){if(!t.push(e).done)return;return{done:!0,result:t.buildResult()}}if(OT(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 Yv:return new pt(e.message,{code:ot.AUTH_UNAUTHORIZED,details:r(!1)});case Xv:return new ut(e.message,ot.SERVICE_LIMIT_EXCEEDED,{details:r(!0)});case Zv:return new ut(e.message,ot.VALIDATION_REQUIRED,{details:r(!1)});case eI:return new ut(e.message,ot.VALIDATION_INVALID_FORMAT,{details:r(!1)});case tI:return new ut(e.message,ot.REST_BUSINESS_UNKNOWN,{details:r(!0)});case rI: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 UT=e=>e.versionState.version?"incremental":"full",LT=e=>{const{metadata:t,metadataFailed:r,state:s}=e,n=s.versionState.version;return r||!t?{decision:"complete"===s.cacheMeta.cacheIntegrity?UT(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}},kT=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{}}},DT=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},PT=(e,t,r,s)=>({code:t,stage:e,message:`${e}: ${r}`,retryable:s}),xT=e=>{Vs("Contact sync duration",e)};class FT{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=LT({metadata:s,state:e}),"skip"===r.decision)return this.dependencies.onFinish(),void xT({outcome:"skip",decision:r.decision,durationMs:Date.now()-t,version:r.version,hasUsableSnapshot:e.cachedSnapshot.complete})}catch(s){if(DT(s)){const r=LT({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:PT("metadata",n.code,n.message,!1)}),void xT({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=LT({metadataFailed:!0,state:e}),e.cachedSnapshot.complete)return this.dependencies.onFinish({error:PT("metadata",ot.CONTACT_SYNC_METADATA_FAILED,s instanceof Error?s.message:String(s),!0)}),void xT({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 MT(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=kT(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(),xT({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:PT(o,n.code,n.message,!0)}),xT({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 BT={items:[],loaded:!1,source:"server"},GT=Lv(kv,hT),qT=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=BT,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=BT,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(pT,[{path:"params.userId",message:pT,rule:"invalid_format"}]);const n=this.getRestClient(s);js("ContactManager addContact",{userId:t,hasMessage:"string"==typeof r&&r.length>0}),await vT(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=fT(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=fT(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=fT(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=fT(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 IT(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=yT(e,"params.userIds"),s=this.getRestClient(t);js("ContactManager addUsersToBlocklist",{userIds:r,inputCount:e.userIds.length,normalizedCount:r.length});const n=await bT(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=yT(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=fT(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 Jy(e.restBaseUrl,{errorMap:GT,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=BT)}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 Fv(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=eT(e),s=await this.getRestClient(t).request(Y_(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return iT(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 FT(e)}};qT.key="contactManager";let $T=qT;class jT{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 VT=e=>{const{orgName:t,appName:r}=fs(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},KT=e=>new mt(`${e} is required`,{code:ot.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),zT=(e,t)=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),HT=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw KT(t);const r=[],s=new Set;if(e.forEach((e,n)=>{if("string"!=typeof e)throw zT(`${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 KT(t);return r},WT=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw KT(t);return e.trim()},JT=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw zT(t,`${t} must be a string`);return e}},QT=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw zT(t,`${t} must be a boolean`);return e}},ZT=(e,t)=>`/${e.orgName}/${e.appName}${t}`,YT=new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),XT=e=>{const t=dv();"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}`:""},eC=async(e,t,r)=>{const s=VT(t),n=ZT(s,`/chatgroups?resource=${s.encodedResource}`);return(e=>{const t=Nu(e),r=Su(t[0]),s=Ou(e)??r;return{groupId:s&&Lu(s)||r&&Lu(r)||""}})(await e.post(n,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?HT(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"}))},tC=async(e,t,r)=>{const s=VT(t),n=WT(r.groupId,"params.groupId"),i=ZT(s,`/chatgroups/${encodeURIComponent(n)}?joined_time=true&version=v3`),o=await e.get(i,{operation:"getGroupInfo"});return Du(o)},rC=async(e,t,r)=>{const s=VT(t),n=WT(r.groupId,"params.groupId"),i={},o=JT(r.name,"params.name"),a=JT(r.description,"params.description"),c=JT(r.avatar,"params.avatar"),d=JT(r.ext,"params.ext"),u=QT(r.public,"params.public"),l=QT(r.joinApprovalRequired,"params.joinApprovalRequired"),h=QT(r.allowInvites,"params.allowInvites"),p=QT(r.inviteNeedConfirm,"params.inviteNeedConfirm"),m=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw zT(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 KT("params");const f=ZT(s,`/chatgroups/${encodeURIComponent(n)}?resource=${s.encodedResource}&version=v3`);await e.put(f,i,{operation:"updateGroupInfo"})},sC=async(e,t,r)=>{const s=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/users${(e=>{const t=dv();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 Nu(e)){const e=Su(i);if(!e)continue;const r=wu(e.owner),s=wu(e.admin),n=wu(e.member),o=r??s??n;if(!o)continue;const a=Ru(e.joinedAt)??Ru(e.joined_time);t.push({user:Pu(o),role:r?"owner":s?"admin":"member",...void 0===a?{}:{joinedAt:a}})}const r=Mu(e,"pagenum"),s=Mu(e,"pagesize"),n=Uu(e,s);return{items:t,pageNum:r,pageSize:s,...void 0===n?{}:{hasMore:n}}})(await e.get(n,{operation:"getGroupMemberList"}))},nC=async(e,t,r)=>{const s=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/admin`),i=await e.get(n,{operation:"getGroupAdminList"});return xu(i)},iC=async(e,t,r)=>{const s=VT(t),n=WT(r.groupId,"params.groupId"),i=XT(r),o=i?"&":"",a=ZT(s,`/chatgroups/${encodeURIComponent(n)}/mute?version=v3${o}${i.replace("?","")}`);return(e=>{const t=[];for(const r of Nu(e)){const e=wu(r);if(e){t.push({user:Pu(e)});continue}const s=Su(r);if(!s)continue;const n=wu(s.user);if(!n)continue;const i=Ru(s.expire);t.push({user:Pu(n),...void 0===i?{}:{muteExpire:i}})}return t})(await e.get(a,{operation:"getGroupMuteList"}))},oC=async(e,t,r)=>{const s=VT(t),n=WT(r.groupId,"params.groupId"),i=XT(r),o=i?"&":"",a=ZT(s,`/chatgroups/${encodeURIComponent(n)}/blocks/users?version=v3${o}${i.replace("?","")}`),c=await e.get(a,{operation:"getGroupBlocklist"});return xu(c).map(e=>({user:e}))},aC=async(e,t,r)=>{const s=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/white/users`),i=await e.get(n,{operation:"getGroupAllowlist"});return xu(i).map(e=>({user:e}))},cC=async(e,t,r)=>{const s=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=Ou(e)??{};return{announcement:Eu(t.announcement)??""}})(await e.get(n,{operation:"getGroupAnnouncement"}))},dC=async(e,t,r)=>{const s=VT(t),n=dv();n.set("pagenum",String(r.pageNum??1)),n.set("pagesize",String(r.pageSize??20));const i=ZT(s,`/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/share_files?${n.toString()}`);return(e=>{const t=Mu(e,"pagenum"),r=Mu(e,"pagesize"),s=Uu(e,r);return{items:Nu(e).map(e=>Fu(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===s?{}:{hasMore:s}}})(await e.get(i,{operation:"getGroupSharedFileList"}))},uC=(e,t)=>{const r=VT(e);return ZT(r,`/chatgroups/${encodeURIComponent(WT(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(WT(t.fileId,"params.fileId"))}`)},lC=async(e,t,r)=>{const s=VT(t),n=WT(r.groupId,"params.groupId"),i=WT(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(!YT.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=ZT(s,`/sdk/chatgroups/${encodeURIComponent(n)}/nameCard`);return await e.put(t,o,{operation:"setGroupMemberAttributes"})}const a=ZT(s,`/sdk/metadata/chatgroup/${encodeURIComponent(n)}/user/${encodeURIComponent(i)}?resource=${s.encodedResource}`);return await e.put(a,{metaData:r.memberAttributes},{operation:"setGroupMemberAttributes"})},hC=async(e,t,r)=>{const s=VT(t),n=ZT(s,`/sdk/metadata/chatgroup/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/get`);return(e=>{const t=Ou(e)??{},r=Su(t.data)??t,s={};for(const[n,i]of Object.entries(r)){const e=Su(i);e&&(s[n]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:s}})(await e.post(n,{targets:HT(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},pC=e=>{const t=yu(e)?e:{},r=t.data,s=yu(r)?r.data:void 0,n=Array.isArray(r)?r:Array.isArray(s)?s:null;if(Array.isArray(n))return mC(n);const i=yu(r)?r:t,o=yu(i.namecards)?i.namecards:i,a={};for(const[c,d]of Object.entries(o)){if("string"==typeof d){a[c]={namecard:d};continue}if(!yu(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:fC(d)})}return a},mC=e=>{const t={};return e.forEach(e=>{if(!yu(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:fC(e)})}),t},fC=e=>Sl("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),gC=e=>{if(yu(e))return Sl("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 yC{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 vC=e=>({...e}),IC=e=>({...e,owner:e.owner?{...e.owner}:void 0});class bC{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=vC({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=IC({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=vC(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?vC(this.summarySnapshot):this.detailSnapshot?vC(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?IC(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 _C{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 TC{constructor(){this.groups=new Map,this.joinedGroupById=new Map,this.removedJoinedGroupIds=new Set,this.snapshotMapper=new _C,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 bC(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 CC=0,SC=5,EC=12,wC=13,RC=0,AC=1,NC=2,OC=0,MC=1,UC=2,LC=3,kC=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===RC?"owner":s===AC?"admin":s===NC?"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===OC?"DEFAULT":r===MC?"ALL":r===UC?"AT":r===LC?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,s},DC=e=>e.updatedAt??0,PC=(e,t)=>{if(!e)return!0;return DC(t)>=DC(e)},xC={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 FC=null,BC=!1;const GC=()=>FC||(BC||(fa.util.Long=Dn,fa.configure(),BC=!0),Va(),FC=fa.Root.fromJSON(xC),ja(FC),FC),qC=e=>GC().lookupType(e),$C=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}},jC=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:$C(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:$C(t.protocol_version)??$C(t.protocolVersion)??0}};class VC{constructor(){this.requestType=qC("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=qC("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=qC("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:CC}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=$C(t.type);return r!==EC?null:{type:r,header:jC(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:$C(t.last_sync_time)??$C(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=$C(t.type);return r!==wC?null:{type:r,header:jC(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:$C(t.members_count)??$C(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:$C(t.role),mute_expiration:$C(t.mute_expiration)??$C(t.muteExpiration),remind_type:$C(t.remind_type)??$C(t.remindType),create_at:$C(t.create_at)??$C(t.createAt),update_at:$C(t.update_at)??$C(t.updateAt),joined_timestamp:$C(t.joined_timestamp)??$C(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:$C(t.last_sync_finished_ts)??$C(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=$C(t.type);return r!==SC?null:{type:r,header:jC(t.header),code:$C(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class KC{constructor(e){this.batches=[],this.done=!1,this.requestId=e}getResumeCursor(){return this.latestCursor}push(e){if(e.type!==wC)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 zC=e=>e.type===wC,HC=e=>e.type===SC;class WC{constructor(e){this.codec=new VC,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new KC(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:zC(t)||HC(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(zC(e)){if(!r.push(e).done)return;return{done:!0,result:r.buildResult()}}if(HC(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 JC{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 WC(this.dependencies.getSharedSyncSession()).sync({urls:r,request:s}),i=n.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=kC(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);PC(e,n)?r.set(n.groupId,{...e??{},...n,groupId:n.groupId}):e&&r.set(n.groupId,{...e})}const s=r.size>=vg;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:yg,serverLimit:vg,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:EC,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:t,app:r,username:e.userId,lastSyncTime:0}}}const QC=Lv(kv,{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:{}}}}),ZC=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 TC,this.groupEventSync=new yC(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 eC(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 jT(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 tC(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=VT(t),n=HT(r.groupIds,"params.groupIds"),i=ZT(s,`/chatgroups/${n.map(e=>encodeURIComponent(e)).join(",")}?joined_time=true&version=v3`),o=await e.get(i,{operation:"getGroupInfoList"});return(yu(o)&&Array.isArray(o.data)?o.data:[]).map(e=>Du({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 rC(this.getRestClient(t),t,e)})}async changeGroupOwner(e){return this.runOperation("changeGroupOwner",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}?resource=${s.encodedResource}`);await e.put(n,{newowner:WT(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/invite?resource=${s.encodedResource}`);await e.post(n,{usernames:HT(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:WT(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/apply_verify?resource=${s.encodedResource}`);await e.post(n,{applicant:WT(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(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 sC(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=VT(t),n=HT(r.userIds,"params.userIds"),i=ZT(s,`/chatgroups/${encodeURIComponent(WT(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 nC(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(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 iC(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/mute?resource=${s.encodedResource}`);await e.post(n,{usernames:HT(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=VT(t),n=HT(r.userIds,"params.userIds"),i=ZT(s,`/chatgroups/${encodeURIComponent(WT(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(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 oC(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/blocks/users?resource=${s.encodedResource}`);await e.post(n,{usernames:HT(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=VT(t),n=HT(r.userIds,"params.userIds"),i=ZT(s,`/chatgroups/${encodeURIComponent(WT(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 aC(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/white/users?resource=${s.encodedResource}`);await e.post(n,{usernames:HT(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=VT(t),n=HT(r.userIds,"params.userIds"),i=ZT(s,`/chatgroups/${encodeURIComponent(WT(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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),i=await e.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof i?i:yu(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=VT(t),n=ZT(s,`/sdk/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),i=await e.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof i?i:yu(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 cC(this.getRestClient(t),t,e)})}async updateGroupAnnouncement(e){return this.runOperation("updateGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const s=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(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 dC(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=uC(t,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),s=os({file:e.file}),n=Ph({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}`,[ou]:iu()},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=VT(t),n=ZT(s,`/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(WT(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}${uC(s,e)}`;t=Ph({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}:{},[ou]:iu()},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 lC(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return hC(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=VT(t),n=ZT(s,`/sdk/chatgroups/${encodeURIComponent(WT(r.groupId,"params.groupId"))}/nameCard/batch/get`),i=await e.post(n,{members:HT(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:pC(i),responseTimestamp:gC(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 Jy(e.restBaseUrl,{errorMap:QC,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 TC),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new yC(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 tC(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=Sl("number"==typeof s?s:Number(s));if("number"==typeof e)return e}}collectUpdateTimeCandidates(e,t,r){if(!yu(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(yu(s)){this.collectUpdateTimeCandidates(s,t,r);const e=s[t];yu(e)&&this.collectUpdateTimeCandidates(e,t,r)}const n=e.lastModified??e.last_modified;yu(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 Cu(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 Tu(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>Tu(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:Tu(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 tC(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=eT(e),s=await this.getRestClient(t).request(Y_(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return iT(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(bI(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),s=await RI({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 wI({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 JC(e)}};ZC.key="groupManager";let YC=ZC;const XC=Lv(kv,{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}}}}}),eS=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 Jy(e.restBaseUrl,{errorMap:XC,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}})}};eS.key="presenceManager";let tS=eS;const rS=["apns","fcm","huawei","xiaomi","meizu","vivo","oppo","honor"],sS=(e,t,r="invalid_format")=>new mt(t,{code:ot.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:r}]}}),nS=(e,t)=>{if(void 0!==e){if("string"!=typeof e||0===e.trim().length)throw sS(t,`${t} must be a non-empty string`);return e.trim()}},iS=e=>8===e?"normal":rS[e]??"normal",oS=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 aS{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 sS("options","options is required","required");const t=e.plugin;if(!t||"object"!=typeof t)throw sS("plugin","plugin is required","required");const r=t;if("function"!=typeof r.onRegister)throw sS("plugin.onRegister","plugin.onRegister must be a function");if("function"!=typeof r.unRegister)throw sS("plugin.unRegister","plugin.unRegister must be a function");const s=e.certificates;if(!s||"object"!=typeof s)throw sS("certificates","certificates is required","required");const n=s,i={apns:nS(n.apns,"certificates.apns"),fcm:nS(n.fcm,"certificates.fcm"),huawei:nS(n.huawei,"certificates.huawei"),xiaomi:nS(n.xiaomi,"certificates.xiaomi"),meizu:nS(n.meizu,"certificates.meizu"),vivo:nS(n.vivo,"certificates.vivo"),oppo:nS(n.oppo,"certificates.oppo"),honor:nS(n.honor,"certificates.honor")};if(!rS.some(e=>void 0!==i[e]))throw sS("certificates","at least one native push certificate is required");return{plugin:t,certificates:i,signature:rS.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(!oS(e)||200!==e.code||0===e.push_token.trim().length)return null;const r=iS(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=oS(s)?iS(s.push_type):void 0,r=oS(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 cS=Lv(kv,{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}}}}}),dS=["singleChat","groupChat"],uS=["ALL","AT","NONE","DEFAULT"],lS=["ALL","AT","NONE"],hS=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),pS=class{constructor(){this.client=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.eventContext=null,this.nativePushController=new aS({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=My({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 Jy(e.restBaseUrl,{errorMap:cS,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||!dS.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(!hS(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(!lS.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(!hS(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(!hS(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(hS(e.data)){const r=e.data[t];if(hS(r))return r}const r=e[t];return hS(r)?r:{}}resolveSilentModeRuleSource(e){if(!hS(e))return e;if(null!==this.parseRuleView(e))return e;const t=e.data;return hS(t)&&null!==this.parseRuleView(t)?t:e}normalizeRemindType(e){return"string"!=typeof e?null:"MENTION_ONLY"===e?"AT":uS.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(hS(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}})}};pS.key="pushManager";let mS=pS;const fS=e=>{const{orgName:t,appName:r}=fs(e.appKey);return`/${t}/${r}/user/${encodeURIComponent(e.userId)}/metadata/subscription`},gS=(e,t="params.userIds")=>Q_(e,t),yS=e=>{const t=gS(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}},vS=(e,t)=>{const r=(e=>gS(e))(t);return`${fS(e)}?usernames=${r.map(e=>encodeURIComponent(e)).join(",")}`},IS=(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}},bS=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],_S=Lv(kv,{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}}}}}),TS=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=IS(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=eT(Q_(e.userIds,"params.userIds")),n=Y_(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=Q_(e.userIds,"params.userIds"),i=Z_(e.attributes,"params.attributes"),{targets:Q_(n),properties:Z_(i).map(e=>J_(e,"params.attributes"))});var n,i;const o=Y_(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=>fS(e))(t),n=yS(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=vS(t,e.userIds);js("UserInfoManager unsubscribeUsersInfo",{userIds:Q_(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=>fS(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(oT(t,"nickname",e.nickname,"params.nickname"),oT(t,"avatarurl",e.avatarUrl,"params.avatarUrl"),oT(t,"mail",e.mail,"params.mail"),oT(t,"phone",e.phone,"params.phone"),oT(t,"gender",e.gender,"params.gender"),oT(t,"sign",e.sign,"params.sign"),oT(t,"birth",e.birth,"params.birth"),oT(t,"ext",e.ext,"params.ext"),0===t.length)throw z_("params must include at least one updatable field","params","required");return aT(t)})(e),n=X_(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=J_(e,"attribute"),s=W_(t,"value");if("gender"!==r&&"string"!=typeof s)throw z_("value must be a string","value","invalid_format");return aT([[r,String(s)]])})(e,t),i=X_(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 Jy(e.restBaseUrl,{errorMap:_S,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 nT(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=yu(e)?e:null,n=(s&&yu(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!!yu(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 bS)n in t&&(s[n]=t[n]);return r}getUpdatedFieldNames(e){return bS.filter(t=>t in e)}projectToSummary(e){const t=Date.now(),r=Sl(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)}};TS.key="userInfoManager";let CS=TS;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=qg,e.ChatClient=iI,e.ChatManager=Mb,e.ChatRoom=Yb,e.ChatRoomManager=lT,e.ChatThread=Ub,e.ChatThreadManager=Zb,e.ConnectionError=ht,e.ContactManager=$T,e.Group=jT,e.GroupManager=YC,e.ImageType={ORIGINAL:"original",LARGE:"large"},e.LogEventName=V,e.MessageReceiveError=gt,e.MessageSendError=ft,e.NetworkError=lt,e.PresenceManager=tS,e.PushEventName=Ge,e.PushManager=mS,e.RUNTIME_PLATFORMS=Js,e.RestBusinessError=It,e.RestTransportError=vt,e.SDKError=ut,e.StorageError=yt,e.StreamMessageStatus=nt,e.UploadError=bt,e.UserInfoManager=CS,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}({});