easemob-websdk 5.1.0 → 5.1.2

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 (100) hide show
  1. package/bundle/im-sdk-web.iife.js +1 -1
  2. package/chat-client.d.ts +42 -8
  3. package/chunks/{chat-manager-D_KF5qM1.cjs → chat-manager-BFd2Z4oY.cjs} +1 -1
  4. package/chunks/{chat-manager-DCqgMxLm.js → chat-manager-CId_M_e5.js} +1 -1
  5. package/chunks/common-BvlDAw4a.js +1 -0
  6. package/chunks/common-tHGz9VBk.cjs +1 -0
  7. package/chunks/event-system-B62vbKqG.js +1 -0
  8. package/chunks/{event-system-COBJFEIq.cjs → event-system-TYhmgy4K.cjs} +1 -1
  9. package/chunks/group-user-info-resolver-B-dyr__b.cjs +1 -0
  10. package/chunks/group-user-info-resolver-DMccCqez.js +1 -0
  11. package/chunks/index-BBFJYOM8.js +1 -0
  12. package/chunks/{index-Dvvh1nf6.cjs → index-DJPAjXAp.cjs} +1 -1
  13. package/chunks/index-DtWkVcfb.cjs +1 -0
  14. package/chunks/index-l_BUKi77.js +1 -0
  15. package/chunks/light-BcQg8h2W.cjs +1 -0
  16. package/chunks/light-DImBnNes.js +1 -0
  17. package/chunks/{reflection-proto-codec-CjRraw85.js → reflection-proto-codec-7r8Sei3y.js} +1 -1
  18. package/chunks/{reflection-proto-codec-BerStgkC.cjs → reflection-proto-codec-CwrIKT1L.cjs} +1 -1
  19. package/chunks/{session-list-query-rynxSxtv.js → session-list-query-Cvr6rlme.js} +1 -1
  20. package/chunks/{session-list-query-C4OQMvPf.cjs → session-list-query-Dslj2k3t.cjs} +1 -1
  21. package/chunks/{user-info-DfbCp80h.js → user-info-AlshAvdy.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-sync-controller.d.ts +5 -0
  30. package/index.cjs +1 -1
  31. package/index.d.ts +11 -9
  32. package/index.js +2 -2
  33. package/log.d.ts +27 -0
  34. package/managers/chat/index.cjs +1 -1
  35. package/managers/chat/index.js +1 -1
  36. package/managers/chat-thread/index.cjs +1 -1
  37. package/managers/chat-thread/index.js +1 -1
  38. package/managers/chatroom/chatroom.d.ts +1 -1
  39. package/managers/chatroom/index.cjs +1 -1
  40. package/managers/chatroom/index.js +1 -1
  41. package/managers/chatroom-manager.d.ts +6 -1
  42. package/managers/contact/index.cjs +1 -1
  43. package/managers/contact/index.js +1 -1
  44. package/managers/group/index.cjs +1 -1
  45. package/managers/group/index.js +1 -1
  46. package/managers/presence/index.cjs +1 -1
  47. package/managers/presence/index.js +1 -1
  48. package/managers/push/index.cjs +1 -1
  49. package/managers/push/index.d.ts +2 -0
  50. package/managers/push/index.js +1 -1
  51. package/managers/push/native-push-controller.d.ts +62 -0
  52. package/managers/push/native-push-normalizer.d.ts +15 -0
  53. package/managers/push-manager.d.ts +63 -4
  54. package/managers/user-info/index.cjs +1 -1
  55. package/managers/user-info/index.js +1 -1
  56. package/managers/user-info-manager.d.ts +3 -2
  57. package/message/combine-payload-codec.d.ts +2 -1
  58. package/package.json +1 -1
  59. package/platform/index.d.ts +1 -1
  60. package/platform/request/default-request-adapter.d.ts +7 -0
  61. package/platform/socket/default-socket-adapter.d.ts +6 -0
  62. package/platform/types.d.ts +22 -2
  63. package/platform/upload/legacy-multipart-upload.d.ts +14 -0
  64. package/platform/upload/legacy-simple-upload.d.ts +3 -0
  65. package/protocol/msync/codec.d.ts +5 -0
  66. package/rest/client.d.ts +0 -4
  67. package/rest/contact-management.d.ts +1 -0
  68. package/rest/dns-config.d.ts +6 -1
  69. package/rest/error-maps/chatroom.d.ts +6 -0
  70. package/rest/error-maps/common.d.ts +3 -0
  71. package/rest/error-maps/contact.d.ts +8 -3
  72. package/rest/error-maps/push.d.ts +13 -1
  73. package/rest/error-maps/user-info.d.ts +51 -3
  74. package/rest/service-url.d.ts +6 -0
  75. package/types/chat-client.d.ts +16 -9
  76. package/types/chatroom.d.ts +3 -34
  77. package/types/event-system.d.ts +52 -1
  78. package/types/index.d.ts +5 -7
  79. package/types/log.d.ts +19 -0
  80. package/types/manager.d.ts +31 -0
  81. package/types/push.d.ts +77 -0
  82. package/upload/attachment-uploader.d.ts +1 -5
  83. package/upload/multipart-upload.d.ts +4 -14
  84. package/upload/simple-upload.d.ts +4 -3
  85. package/upload/types.d.ts +2 -1
  86. package/utils/error-codes.generated.d.ts +1 -0
  87. package/utils/log-reporter.d.ts +1 -7
  88. package/utils/logger.d.ts +28 -2
  89. package/validators/chat-client.d.ts +22 -50
  90. package/validators/message-create.d.ts +18 -18
  91. package/chunks/common-BIpcR2uQ.cjs +0 -1
  92. package/chunks/common-D_DfwSd3.js +0 -1
  93. package/chunks/event-system-D6IJA0C4.js +0 -1
  94. package/chunks/group-user-info-resolver-Ds35Z1Uf.cjs +0 -1
  95. package/chunks/group-user-info-resolver-lEtRdWli.js +0 -1
  96. package/chunks/index-BmwQgZ3E.js +0 -1
  97. package/chunks/index-BsIqq7LU.cjs +0 -1
  98. package/chunks/index-CFMcR5a_.js +0 -1
  99. package/chunks/light-Dg9A1Xmd.js +0 -1
  100. package/chunks/light-dJjIln5b.cjs +0 -1
@@ -1 +0,0 @@
1
- const e={VALIDATION_REQUIRED:110,VALIDATION_INVALID_FORMAT:110,VALIDATION_UNKNOWN:110,AUTH_ALREADY_LOGIN:200,AUTH_NOT_LOGIN:201,AUTH_UNAUTHORIZED:202,AUTH_FORBIDDEN:210,AUTH_TOKEN_EXPIRED:108,AUTH_BIND_ANOTHER_DEVICE:213,AUTH_LOGIN_TOO_MANY_DEVICES:214,AUTH_USER_MUTED:215,CONNECTION_TIMEOUT:301,CONNECTION_WEBSOCKET_ERROR:300,CONNECTION_NOT_CREATED:1,CONNECTION_CLOSED_BEFORE_READY:300,CONNECTION_CANCELLED:1,CONNECTION_PROVISION_TIMEOUT:301,CONNECTION_PROVISION_REJECTED:202,CONNECTION_PROVISION_CLOSED:300,CONNECTION_DNSLIST_FAILED:304,STORAGE_OPERATION_FAILED:3,MESSAGE_NOT_CONNECTED:300,MESSAGE_ACK_TIMEOUT:301,MESSAGE_SEND_FAILED:303,MESSAGE_SENDER_DESTROYED:1,MESSAGE_ENCODE_FAILED:500,MESSAGE_DECODE_FAILED:500,MESSAGE_ACK_MISSING:301,MESSAGE_BLOCKED_BY_RECIPIENT:222,OPERATION_UNSUPPORTED:111,SERVER_BUSY:302,ATTACHMENT_NOT_FOUND:400,ATTACHMENT_INVALID:401,ATTACHMENT_EXPIRED:407,MESSAGE_INCLUDE_ILLEGAL_CONTENT:501,MESSAGE_SEND_TRAFFIC_LIMIT:502,MESSAGE_RECALL_TIME_LIMIT:504,SERVICE_NOT_ENABLED:505,MESSAGE_EXPIRED:506,MESSAGE_ILLEGAL_WHITELIST:507,MESSAGE_EXTERNAL_LOGIC_BLOCKED:508,MESSAGE_CURRENT_LIMITING:509,MESSAGE_SIZE_LIMIT:510,MESSAGE_EDIT_FAILED:511,INVALID_CONVERSATION:107,USER_LOGIN_ANOTHER_DEVICE:206,USER_REMOVED:207,USER_KICKED_BY_CHANGE_PASSWORD:216,USER_KICKED_BY_OTHER_DEVICE:217,USER_ALREADY_LOGIN_ANOTHER:218,USER_MUTED_BY_ADMIN:219,USER_DEVICE_CHANGED:220,USER_NOT_ON_ROSTER:221,SERVER_SERVING_DISABLED:305,FILE_DOWNLOAD_FAILED:403,FILE_TOO_LARGE:405,FILE_CONTENT_IMPROPER:406,THIRD_MODERATION_FAILED:1200,THIRD_DEFAULT_FAILED:1299,STREAM_SEND_NOT_SUPPORTED:303,STREAM_CHUNK_INVALID:500,STREAM_TIMEOUT_BY_SERVER:500,STREAM_STATE_CONFLICT:500,COMBINE_INVALID_INPUT:110,COMBINE_LEVEL_EXCEEDED:4,COMBINE_ITEM_LIMIT_EXCEEDED:4,COMBINE_ENCODE_FAILED:500,COMBINE_UPLOAD_FAILED:402,COMBINE_DOWNLOAD_FAILED:2,COMBINE_PARSE_FAILED:500,REST_NETWORK_ERROR:2,REST_TIMEOUT:301,REST_HTTP_ERROR:303,REST_BUSINESS_UNKNOWN:303,PUSH_TOKEN_UPLOAD_FAILED:1500,PUSH_SILENT_MODE_OPERATION_FAILED:1501,PUSH_LANGUAGE_OPERATION_FAILED:1502,USER_INFO_SUBSCRIPTION_LIMIT_EXCEEDED:1600,USER_INFO_SUBSCRIPTION_TARGET_LIMIT_EXCEEDED:1601,USERINFO_USERCOUNT_EXCEED:900,USERINFO_DATALENGTH_EXCEED:901,CONTACT_ADD_USER_NOT_FOUND:204,CONTACT_ADD_ALREADY_FRIEND:1e3,CONTACT_ADD_BLOCKED_BY_USER:210,CONTACT_SET_REMARK_NOT_FRIEND:223,CONTACT_REACH_LIMIT:1001,CONTACT_REACH_LIMIT_PEER:1002,CONTACT_BLOCKLIST_USER_NOT_FOUND:204,GROUP_INVALID_ID:600,GROUP_ALREADY_JOINED:601,GROUP_NOT_JOINED:602,GROUP_PERMISSION_DENIED:603,GROUP_MEMBERS_FULL:604,GROUP_SHARED_FILE_INVALID_ID:605,GROUP_NOT_EXIST:606,GROUP_DISABLED:607,GROUP_NAME_VIOLATION:608,GROUP_MEMBER_ATTRIBUTES_REACH_LIMIT:609,GROUP_MEMBER_ATTRIBUTES_UPDATE_FAILED:610,GROUP_MEMBER_ATTRIBUTES_KEY_REACH_LIMIT:611,GROUP_MEMBER_ATTRIBUTES_VALUE_REACH_LIMIT:612,GROUP_USER_IN_BLOCKLIST:613,CHATROOM_INVALID_ID:700,CHATROOM_NOT_JOINED:702,CHATROOM_PERMISSION_DENIED:703,CHATROOM_MEMBERS_FULL:704,CHATROOM_NOT_EXIST:705,CHATROOM_OWNER_NOT_ALLOW_LEAVE:706,CHATROOM_USER_IN_BLOCKLIST:707,CONTACT_SYNC_METADATA_FAILED:1700,CONTACT_SYNC_SOCKET_FAILED:1701,CONTACT_SYNC_CURSOR_INVALID:1702,CONTACT_SYNC_PROTO_DECODE_FAILED:1703,CONTACT_SYNC_CANCELLED:1704,SESSION_LIST_SOCKET_FAILED:300,SESSION_LIST_PROTO_DECODE_FAILED:500,SESSION_LIST_REQUEST_INVALID:110,SESSION_LIST_FETCH_FAILED:303,SESSION_LIST_SERVICE_DISABLED:305,SESSION_LIST_CANCELLED:1,PRESENCE_PARAM_LENGTH_EXCEED:1100,PRESENCE_CANNOT_SUBSCRIBE_YOURSELF:1101,TRANSLATE_PARAM_INVALID:1110,TRANSLATE_SERVICE_NOT_ENABLED:1111,TRANSLATE_USAGE_LIMIT:1112,TRANSLATE_FAILED:1113,VOICE_TO_TEXT_FILE_INVALID:407,VOICE_TO_TEXT_FILE_DURATION_TOO_LONG:408,VOICE_TO_TEXT_FAILED:409,VOICE_TO_TEXT_FILE_NOT_FOUND:410,VOICE_TO_TEXT_FILE_TOO_LARGE:411,REACTION_REACH_LIMIT:1300,REACTION_ALREADY_OPERATED:1301,REACTION_OPERATION_ILLEGAL:1302,UPLOAD_REQUIRED_FIELD_MISSING:110,UPLOAD_INVALID_APPKEY:100,UPLOAD_SIZE_EXCEEDED:405,UPLOAD_REQUEST_FAILED:402,UPLOAD_TIMEOUT:301,UPLOAD_ABORTED:1,SERVICE_LIMIT_EXCEEDED:4,UNKNOWN:1},t="[REDACTED]",o=e=>{if(!e)return"";const o=e.includes("?"),r=e.includes("#");try{return((e,o,r)=>(e.username&&(e.username=t),e.password&&(e.password=t),e.search=o?`?${t}`:"",e.hash=r?`#${t}`:"",e.toString()))(new URL(e),o,r)}catch{const o=[e.indexOf("?"),e.indexOf("#")].filter(e=>e>=0).sort((e,t)=>e-t)[0];return void 0===o?"[invalid-url]":`${e.slice(0,o)}?${t}`}},r=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>"url"===e.toLowerCase()&&"string"==typeof t?[e,o(t)]:[e,t]));class s extends Error{constructor(t,o=e.UNKNOWN,i){super(t),this.name="SDKError",this.code=o,this.details=i?.details?r(i.details):void 0,Error.captureStackTrace&&Error.captureStackTrace(this,s)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class i extends s{constructor(t,o){super(t,o?.code??e.REST_NETWORK_ERROR,o),this.name="NetworkError"}}class a extends s{constructor(t,o){super(t,o?.code??e.CONNECTION_WEBSOCKET_ERROR,o),this.name="ConnectionError"}}class n extends s{constructor(t,o){super(t,o?.code??e.AUTH_UNAUTHORIZED,o),this.name="AuthenticationError"}}class p extends s{constructor(t,o){super(t,o?.code??e.VALIDATION_UNKNOWN,o),this.name="ValidationError"}}class E extends s{constructor(t,o){super(t,o?.code??e.MESSAGE_SEND_FAILED,o),this.name="MessageSendError"}}class c extends s{constructor(t,o){super(t,o?.code??e.MESSAGE_DECODE_FAILED,o),this.name="MessageReceiveError"}}class u extends s{constructor(t,o){super(t,o?.code??e.STORAGE_OPERATION_FAILED,o),this.name="StorageError"}}class T extends s{constructor(t,o){super(t,o?.code??e.REST_NETWORK_ERROR,o),this.name="RestTransportError"}}class d extends s{constructor(t,o){super(t,o?.code??e.REST_BUSINESS_UNKNOWN,o),this.name="RestBusinessError"}}class l extends s{constructor(t,o){super(t,o?.code??e.UPLOAD_REQUEST_FAILED,o),this.name="UploadError"}}function _(e){if(e instanceof s)return!0;if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&"string"==typeof t.message&&"number"==typeof t.code&&"function"==typeof t.toJSON}const O=15e3,R=3e5,h=6e4,m=3e5,N=1e4,S=1e4,A=3e4,f=6e4,I=1e3,y=6e4,C=2,D=5e3,g=1e4,M=1e3,U=5e3,L=2,b=0,G=2e4,P=7e3,H=20,w=3,v=1,B=7e3,F=1e3,k=50,K=5,V={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",heic:"image/heic",heif:"image/heif",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",mp3:"audio/mpeg",m4a:"audio/mp4",wav:"audio/wav",aac:"audio/aac",amr:"audio/amr",pdf:"application/pdf",txt:"text/plain",json:"application/json"},q=e=>"undefined"!=typeof Blob&&e instanceof Blob,$=e=>{const t=e.replace(/[?#].*$/,"").split(/[\\/]/).filter(Boolean),o=t.length>0?t[t.length-1]:void 0;if(o)return o},x=e=>{if(!e)return;const t=e.lastIndexOf(".");if(t<0||t===e.length-1)return;const o=e.slice(t+1).toLowerCase();return V[o]},z=(e,t)=>{for(const o of t){const t=e[o];if("string"==typeof t&&t.length>0)return t}},j=e=>{const t=e.file,o=e.sourceMeta,r=t.name||(o?z(o,["name","fileName","filename"]):void 0),s=e.file.type||(o?z(o,["type","mimeType","filetype"]):void 0),i=e.file.size||(o?((e,t)=>{for(const o of t){const t=e[o];if("number"==typeof t&&Number.isFinite(t))return t}})(o,["size","fileSize","fileLength"]):void 0),a=W({fileName:r,fileType:s,fileSize:i,fallbackName:e.fallbackName,fallbackMimeType:e.fallbackMimeType,fallbackSize:e.fallbackSize});return{source:{sourceType:"web-file",file:e.file,name:a.fileName,mimeType:a.fileType,size:a.fileSize},fileName:a.fileName,fileType:a.fileType,fileSize:a.fileSize,webFile:e.file}},W=e=>({fileName:e.fileName??e.fallbackName??"file",fileType:e.fileType??e.fallbackMimeType??"application/octet-stream",fileSize:e.fileSize??e.fallbackSize??0}),Y=e=>{const{file:t,fallbackName:o,fallbackMimeType:r,fallbackSize:s}=e,i=(e=>{if(q(e))return e;if("object"!=typeof e||null===e)return;const t=e;for(const o of["file","originFileObj","raw","blob"]){const e=t[o];if(q(e))return e}})(t);if(i)return j({file:i,fallbackName:o,fallbackMimeType:r,fallbackSize:s,sourceMeta:"object"==typeof t&&null!==t?t:void 0});if((e=>"object"==typeof e&&null!==e&&"path"in e)(t)){const e=$(t.path),i=W({fileName:t.name??e,fileType:t.type??x(t.name??e),fileSize:t.size,fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"miniapp-path",path:t.path,name:i.fileName,mimeType:i.fileType,size:i.fileSize},fileName:i.fileName,fileType:i.fileType,fileSize:i.fileSize}}if((e=>"object"==typeof e&&null!==e&&"uri"in e)(t)){const e=$(t.uri),i=W({fileName:t.name??e,fileType:t.type??x(t.name??e),fileSize:t.size,fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"rn-uri",uri:t.uri,name:i.fileName,mimeType:i.fileType,size:i.fileSize},fileName:i.fileName,fileType:i.fileType,fileSize:i.fileSize}}const a=W({fallbackName:o,fallbackMimeType:r,fallbackSize:s});return{source:{sourceType:"web-file",name:a.fileName,mimeType:a.fileType,size:a.fileSize},fileName:a.fileName,fileType:a.fileType,fileSize:a.fileSize}},X=5242880,J=5242880,Q=4,Z="CHAT",ee="GROUP",te="ROOM",oe="original",re="large",se=e=>/^https?:\/\//i.test(e),ie=(e,t)=>!!t||(!e||!se(e)),ae=t=>{const o=t.split("#");if(2!==o.length||!o[0]||!o[1])throw new l("Invalid appKey for upload",{code:e.UPLOAD_INVALID_APPKEY,details:{appKey:t}});return{orgName:o[0],appName:o[1]}},ne=e=>"singleChat"===e?Z:"groupChat"===e?ee:te,pe=(e,t)=>ce(e,{size:t}),Ee=e=>{try{return decodeURIComponent(e)}catch{return e}},ce=(e,t)=>{const[o="",r]=e.split("#",2),[s,i=""]=o.split("?",2),a=i.split("&").filter(Boolean);return Object.entries(t).forEach(([e,t])=>{const o=encodeURIComponent(e),r=a.filter(t=>{const[r=""]=t.split("=",2);return r!==o&&Ee(r)!==e});a.length=0,a.push(...r),void 0!==t&&a.push(`${o}=${encodeURIComponent(String(t))}`)}),`${s}${a.length>0?`?${a.join("&")}`:""}${r?`#${r}`:""}`},ue=(e,t)=>{if(!e)return"";const o={};return e.includes("em-redirect")||(o["em-redirect"]="true"),t&&!e.includes("share-secret=")&&(o["share-secret"]=t),0===Object.keys(o).length?e:ce(e,o)},Te=e=>e.isGif?{resolvedImageType:oe,reason:"gif-force-origin"}:e.isOriginalImage?{resolvedImageType:oe,reason:"explicit-original"}:{resolvedImageType:re,reason:"default-large"},de=e=>{const t=(o=e.messageType,r=e.imageType,"image"!==o?"attachment":r===oe?"image-origin":"image-big");var o,r;const s=(e=>"image-origin"===e?204800:1048576)(t),i=e.fileSize>s;return{shouldPrecheck:i,thresholdType:t,thresholdBytes:s,actualBytes:e.fileSize,reason:i?"threshold-exceeded":"below-threshold"}},le=t=>{const o=t.entities?.[0],r=!0===o?.exists,s="string"==typeof o?.uuid&&o.uuid.length>0?o.uuid:void 0,i=o,a=i?.["exists-type"]??i?.existsType,n="origin"===a?oe:a===re||a===oe?a:void 0,p="string"==typeof o?.["share-secret"]?o["share-secret"]:void 0;if(r&&!s)throw new l("Upload precheck response missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t}});return{uuid:s,exists:r,existsType:n,shareSecret:p,hit:(E={exists:r,uuid:s},E.exists&&"string"==typeof E.uuid&&E.uuid.length>0)};var E},_e=(e,t)=>{if(!e)return{};if(!1===t?.deriveVariants)return{originalImageUrl:e};const o=(e=>{const[t="",o]=e.split("#",2),[r,s=""]=t.split("?",2),i=s.split("&").filter(Boolean).filter(e=>{const[t="",o=""]=e.split("=",2),r=Ee(t),s=Ee(o);return"size"!==r||!["big","large","thumbnail","small"].includes(s)}).join("&");return`${r}${i?`?${i}`:""}${o?`#${o}`:""}`})(e);return{originalImageUrl:o,bigImageUrl:pe(o,"large"),thumbnailUrl:pe(o,"small")}},Oe=e=>e===oe?"origin":"large",Re=e=>e===oe?1:2,he=e=>2===e?re:oe,me=t=>{const o=t.response.entities?.[0];if(!o?.uuid)throw new l("Upload response missing uuid",{code:e.UPLOAD_REQUEST_FAILED,details:{response:t.response}});const r=o["share-secret"],s=o["file-metadata"]??{},i="number"==typeof s["content-length"]?s["content-length"]:t.fallbackSize,a="string"==typeof s["content-type"]?s["content-type"]:t.fileType,n=`${t.restBaseUrl}/${t.orgName}/${t.appName}/chatfiles/${o.uuid}`;if("image"===t.messageType){const e=(t.imageType??re)===oe;return{..._e(n,{deriveVariants:!t.useCustomAttachmentUpload}),isOriginalImage:e,secret:r,fileLength:i,filetype:a,filename:t.fileName,width:t.width,height:t.height}}const p="video"===t.messageType?`${n}?vframe=true`:void 0;return{url:n,secret:r,fileLength:i,filetype:a,filename:t.fileName,thumbnailUrl:p}},Ne=(t,o)=>{if(!t)throw new l("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"file missing"}});const r=("number"==typeof o.fileLength?o.fileLength:void 0)??("fileSize"in o&&"number"==typeof o.fileSize?o.fileSize:void 0),s=Y({file:t,fallbackName:o.filename,fallbackMimeType:o.filetype,fallbackSize:r});if("web-file"===s.source.sourceType&&!s.webFile)throw new l("Attachment file is required",{code:e.UPLOAD_REQUIRED_FIELD_MISSING,details:{reason:"web file missing"}});return s},Se=e=>new Promise(t=>{setTimeout(t,e)});const Ae=new class{constructor(e){this.state="disabled",this.timerId=null,this.reporting=!1,this.context={},this.buffer=[],this.bufferBytes=0,this.reportIntervalMs=this.normalizeReportInterval(e?.reportIntervalMs),this.reportTimeoutMs=e?.reportTimeoutMs??15e3,this.chunkDelayMs=e?.chunkDelayMs??3e3,this.maxChunkBytes=e?.maxChunkBytes??2097152,this.maxBufferBytes=e?.maxBufferBytes??3145728}setEnabled(e){this.setState(e?"enabled":"disabled")}setState(e){this.state=e,"enabled"!==e?(this.stop(),this.clearBuffer()):this.start()}updateContext(e){this.context={...this.context,...e}}updateReportInterval(e){this.reportIntervalMs=this.normalizeReportInterval(e),"enabled"===this.state&&this.start()}append(e){if("disabled"===this.state)return;const t=this.formatEntry(e);this.pushBuffer(t)}async reportNow(){await this.reportLogs()}stop(){this.timerId&&(clearInterval(this.timerId),this.timerId=null)}clearBuffer(){this.buffer=[],this.bufferBytes=0}start(){this.stop(),this.timerId=setInterval(()=>{this.reportLogs()},this.reportIntervalMs)}normalizeReportInterval(e){const t=void 0!==e&&Number.isFinite(e)&&e>0?e:3e5;return Math.max(t,6e4)}canReport(){return Boolean(this.context.restBaseUrl&&this.context.appKey&&this.context.userId&&this.context.token&&this.context.requestAdapter)}formatEntry(e){const t=e.args.length>0?e.args.map(e=>(e=>{if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}})(e)).join(" "):"",o=t?`${e.message} ${t}`:e.message;return`${e.timestamp} [${e.level}] ${o}`}pushBuffer(e){const t=e.length;if(!(t>=this.maxBufferBytes)){for(;this.bufferBytes+t>this.maxBufferBytes&&this.buffer.length>0;){const e=this.buffer.shift();e&&(this.bufferBytes-=e.length)}this.buffer.push(e),this.bufferBytes+=t}}consumeBuffer(){if(0===this.buffer.length)return[];const e=`${this.buffer.join("\n")}\n`;this.clearBuffer();const t=[];let o=e;for(;o.length>this.maxChunkBytes;)t.push(o.slice(0,this.maxChunkBytes)),o=o.slice(this.maxChunkBytes);return o.length>0&&t.push(o),t}requeueChunk(e){this.pushBuffer(e)}async reportLogs(){if("enabled"===this.state&&!this.reporting&&0!==this.buffer.length){this.reporting=!0;try{const e=this.consumeBuffer();if(0===e.length)return;if(!this.canReport())return void e.forEach(e=>this.requeueChunk(e));for(const t of e){await this.reportChunk(t)||this.requeueChunk(t),await Se(this.chunkDelayMs)}}finally{this.reporting=!1}}}async reportChunk(e){if(!this.canReport())return!1;const{restBaseUrl:t,appKey:o,userId:r,token:s,resource:i,requestAdapter:a}=this.context;if(!(t&&o&&r&&s&&a))return!1;let n="",p="";try{const e=ae(o);n=e.orgName,p=e.appName}catch{return!1}const E=`${t}/${n}/${p}/sdk/users/${r}/client/logs`,c={resource:i??"webim",logContent:e};try{const e=await a.request({url:E,method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json"},body:c,responseType:"json",timeoutMs:this.reportTimeoutMs});if(e.status<200||e.status>=300)return!1;const t="string"==typeof e.data?(e=>{try{return JSON.parse(e)}catch{return}})(e.data):e.data;return!t||!t.status||"ok"===t.status}catch{return!1}}},fe="[MASKED]",Ie=new Set(["token","password","authorization","appkey","userid","deviceid","accesstoken","refreshtoken","secret","authtoken","sessionid","clientresource"]),ye=e=>!!e&&Ie.has((e=>e.toLowerCase())(e)),Ce=(e,t,o)=>{const r=o??/* @__PURE__ */new WeakSet;if("string"==typeof e)return((e,t)=>ye(t)?fe:e)(e,t);if("number"==typeof e||"boolean"==typeof e||null==e)return e;if("bigint"==typeof e||"symbol"==typeof e)return e.toString();if("function"==typeof e)return`[Function ${e.name||"anonymous"}]`;if(e instanceof Error)return{name:(s=e).name,message:s.message};var s;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>Ce(e,void 0,r));if("object"==typeof e){if(r.has(e))return"[Circular]";if(r.add(e),(e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Date||e instanceof Error))(e)){const t={};for(const[o,s]of Object.entries(e))ye(o)?t[o]=fe:t[o]=Ce(s,o,r);return t}return Object.prototype.toString.call(e)}return"[Unsupported]"},De="undefined"!=typeof document,ge={DEBUG:0,WARN:1,ERROR:2};class Me{constructor(e="WARN"){this.level=e}setLevel(e){this.level=e}shouldLog(e){return ge[e]>=ge[this.level]}emit(e,t,o){const r=(e=>{const t=/* @__PURE__ */new WeakSet;return e.map(e=>Ce(e,void 0,t))})(o),s=((e,t,o)=>({timestamp:/* @__PURE__ */(new Date).toISOString(),level:e,message:t,args:o}))(e,t,r);Ae.append(s);const i=/* @__PURE__ */new Date,a=`[Chat][${e}][${`${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}:${String(i.getSeconds()).padStart(2,"0")}.${String(i.getMilliseconds()).padStart(3,"0")}`}]`;De?console.log(`%c${a}`,"color: rgb(0, 157, 255); font-weight: bold",t,...r):console.log(a,t,...r)}debug(e,...t){this.shouldLog("DEBUG")&&this.emit("DEBUG",e,t)}warn(e,...t){this.shouldLog("WARN")&&this.emit("WARN",e,t)}error(e,...t){this.shouldLog("ERROR")&&this.emit("ERROR",e,t)}}let Ue=new Me;function Le(e){Ue instanceof Me&&Ue.setLevel(e)}function be(e){Ae.setState(e)}function Ge(e){Ae.updateContext(e)}function Pe(e){Ae.updateReportInterval(e)}async function He(){await Ae.reportNow()}function we(){Ae.stop()}const ve={debug:(e,...t)=>Ue.debug(e,...t),warn:(e,...t)=>Ue.warn(e,...t),error:(e,...t)=>Ue.error(e,...t)},Be=["__uniConfig","skipWaiting","registration","navigator","process","window","document","localStorage","fetch","WebSocket","XMLHttpRequest","FormData","TextEncoder","TextDecoder","crypto"],Fe=e=>{if(e)return e;return((e,t)=>{if(!e)return t;if(0===Object.keys(t).length)return e;const o={},r=e;for(const s of Be)try{const e=r[s];void 0!==e&&(o[s]=e)}catch{}for(const s of Object.keys(t))o[s]=t[s];return o})("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0,{..."undefined"!=typeof wx?{wx:wx}:{},..."undefined"!=typeof qq?{qq:qq}:{},..."undefined"!=typeof tt?{tt:tt}:{},..."undefined"!=typeof swan?{swan:swan}:{},..."undefined"!=typeof my?{my:my}:{},..."undefined"!=typeof dd?{dd:dd}:{},..."undefined"!=typeof jd?{jd:jd}:{},..."undefined"!=typeof ks?{ks:ks}:{},..."undefined"!=typeof uni?{uni:uni}:{}})},ke=()=>`${Date.now()}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`,Ke="X-Request-Id",Ve=1e3,qe="direct";class $e{constructor(e){this.events=[],this.enabled=!1,this.acceptedInWindow=0,this.capacityDiagnosticEmitted=!1,this.rateDiagnosticEmitted=!1,this.sendBatch=e.send,this.capacity=e.capacity??1e3,this.batchSize=e.batchSize??10,this.rateLimit=e.rateLimit??1e3,this.flushIntervalMs=e.flushIntervalMs??1e3,this.now=e.now??Date.now,this.onDrop=e.onDrop,this.windowStartedAt=this.now()}get size(){return this.events.length}enqueue(e){return this.refreshRateWindow(),this.acceptedInWindow>=this.rateLimit?(this.rateDiagnosticEmitted||(this.rateDiagnosticEmitted=!0,this.onDrop?.("rate-limit")),!1):this.events.length>=this.capacity?(this.capacityDiagnosticEmitted||(this.capacityDiagnosticEmitted=!0,this.onDrop?.("capacity")),!1):(this.events.push(e),this.acceptedInWindow+=1,this.schedule(),!0)}enable(){this.enabled=!0,this.schedule()}updateAppKey(e,t){for(let o=0;o<this.events.length;o+=1){const r=this.events[o];r&&r.appKey===e&&(this.events[o]={appKey:t,wire:{...r.wire,body:{...r.wire.body,appkey:t}}})}}pause(){this.enabled=!1,this.clearTimer()}clear(){this.pause(),this.events.splice(0,this.events.length),this.acceptedInWindow=0,this.windowStartedAt=this.now(),this.capacityDiagnosticEmitted=!1,this.rateDiagnosticEmitted=!1}refreshRateWindow(){const e=this.now();e-this.windowStartedAt<6e4||(this.windowStartedAt=e,this.acceptedInWindow=0,this.rateDiagnosticEmitted=!1)}schedule(){this.enabled&&0!==this.events.length&&!this.timer&&(this.timer=setTimeout(()=>{this.timer=void 0,this.consume()},this.flushIntervalMs))}async consume(){if(!this.enabled||0===this.events.length)return;const e=this.events[0];if(!e)return;const t=[];for(let o=0;o<this.events.length&&t.length<this.batchSize;){const r=this.events[o];r?.appKey===e.appKey?(t.push(r.wire),this.events.splice(o,1)):o+=1}this.events.length<this.capacity&&(this.capacityDiagnosticEmitted=!1);try{await this.sendBatch(e.appKey,t)}catch{}finally{this.schedule()}}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=void 0)}}class xe{constructor(e){this.requestAdapter=e.requestAdapter,this.debug=e.debug??!1,this.now=e.now??Date.now,this.onFailure=e.onFailure}async send(e,t){if(this.requestAdapter&&0!==t.length)try{const o=await this.requestAdapter.request({url:this.debug?"https://data-reporting.realtimemesh.com/report":"https://data-reporting.rtnsvc.com/report",method:"POST",headers:{"Content-Type":"application/json",token:"32f24ab2ddb74f508aa9286c356cec84",appid:e,sendts:String(Math.floor(this.now()/1e3)),biz:"im",debug:String(this.debug)},body:JSON.stringify(t),responseType:"text",timeoutMs:15e3});(o.status<200||o.status>=300)&&this.onFailure?.({reason:"non-success-response",status:o.status})}catch(o){this.onFailure?.({reason:"transport-error",message:o instanceof Error?o.message:String(o)})}else this.onFailure?.({reason:"request-adapter-unavailable",eventCount:t.length})}}const ze={none:0,disconnected:0,ethernet:1,lan:1,wifi:2,"slow-2g":7,"2g":7,"3g":7,"4g":7,"5g":7,cellular:7},je=()=>{const e=Fe(),t=e.crypto?.randomUUID;return("function"==typeof t?t.call(e.crypto):void 0)??`${Date.now()}_${Math.random().toString(36).slice(2)}`};class We{constructor(e){this.currentState="disabled",this.networkType=-1,this.now=e.now??Date.now,this.randomId=e.randomId??je;const t=new xe({requestAdapter:e.requestAdapter,debug:e.debug,now:this.now,onFailure:t=>{e.onDiagnostic?.("DataReport transport failed",t)}}),o=e.send??((e,o)=>t.send(e,o));this.queue=new $e({send:o,now:this.now,onDrop:t=>{e.onDiagnostic?.("DataReport event dropped",{reason:t})}})}get state(){return this.currentState}get queuedEventCount(){return this.queue.size}get serviceId(){return this.session?.serviceId}startSession(e){this.queue.clear(),this.currentState="unknown";const t=this.randomId();return this.session={...e,sessionId:`session_${t}`,serviceId:`sid_${t}`},this.enqueue(9674,{did:e.did??"",os:e.os??e.platform,sdkVersion:e.sdkVersion,deviceId:e.deviceId??""}),this.session.serviceId}updateSession(e){this.session&&(e.appKey&&e.appKey!==this.session.appKey&&this.queue.updateAppKey(this.session.appKey,e.appKey),this.session={...this.session,...e})}updateNetworkType(e){this.networkType=(e=>"number"==typeof e&&Number.isFinite(e)?e:"string"!=typeof e?-1:ze[e.trim().toLowerCase()]??-1)(e)}applyDnsSwitch(e){if(this.session){if("true"===e)return this.currentState="enabled",void this.queue.enable();this.currentState="disabled",this.queue.clear()}else this.currentState="disabled"}startOperation(e){const t=this.session?.sessionId;if(!t||"disabled"===this.currentState)return this.createNoopOperation();const o=`opr_${this.randomId()}`,r=this.now();let s=!1,i=!1,a=`req_${this.randomId()}`,n=0,p="";const E=()=>!s&&!i&&this.session?.sessionId===t,c=(t,r,s,i,a)=>{E()&&(n=a.success?0:a.code,p=a.success?"":a.description??"",this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:o,requestid:r,operationName:e.operationName,operationType:e.operationType,requestName:t.requestName??e.operationName,subrequestid:String(s),requestMethod:t.method??"",requestUrl:t.url??"",requestElapse:Math.max(0,this.now()-i),code:a.code,codeDesc:a.description??"",isLastApi:0,isSuccess:a.success?1:0,accessChannel:this.session?.accessChannel??qe,msgId:e.msgId,messageType:e.messageType,resultCount:a.resultCount}))},u=(e,t,o,r)=>{const s=this.now();let i=!1;return{retry:()=>(r.next+=1,u(e,t,r.next,r)),finish:r=>{i||(i=!0,c(e,t,o,s,r))}}};return{startRequest:(e={})=>(a=`req_${this.randomId()}`,u(e,a,1,{next:1})),finish:t=>{E()&&(s=!0,this.enqueue(9675,{uid:e.uid??this.session?.uid,operationId:o,requestid:a,operationName:e.operationName,operationType:e.operationType,requestName:"",subrequestid:"0",requestMethod:"",requestUrl:"",requestElapse:Math.max(0,this.now()-r),code:t.success?0:t.code??n,codeDesc:t.success?"":t.description??p,isLastApi:1,isSuccess:t.success?1:0,accessChannel:this.session?.accessChannel??qe,msgId:e.msgId,messageType:e.messageType,resultCount:t.resultCount}))},discard:()=>{i=!0}}}reset(){this.currentState="disabled",this.session=void 0,this.queue.clear()}enqueue(e,t){const o=this.session;if(!o||"disabled"===this.currentState)return;const r={lts:this.now(),net:this.networkType,appkey:o.appKey,sdkServiceId:o.serviceId,sdkProduct:0,uikitVersion:o.uikitVersion??"",...t},s={eventId:e,body:Object.fromEntries(Object.entries(r).filter(([,e])=>void 0!==e))};this.queue.enqueue({appKey:o.appKey,wire:s})}createNoopOperation(){const e={retry:()=>e,finish:()=>{}};return{startRequest:()=>e,finish:()=>{},discard:()=>{}}}}let Ye;const Xe=e=>(Ye?.reset(),Ye=new We(e),Ye),Je=e=>Ye?.startSession(e),Qe=e=>{Ye?.updateSession(e)},Ze=e=>{Ye?.applyDnsSwitch(e)},et=e=>{Ye?.updateNetworkType(e)},ot=e=>{if("disabled"!==Ye?.state)return Ye?.startOperation(e)},rt=()=>{Ye?.reset(),Ye=void 0},st=(e,t)=>{if(!e.matchField)return!1;const o=t[e.matchField];return void 0!==e.matchPattern?"string"==typeof o&&o.includes(e.matchPattern):void 0===e.matchValue?void 0!==o:o===e.matchValue||!("string"!=typeof o&&"number"!=typeof o||"string"!=typeof e.matchValue&&"number"!=typeof e.matchValue)&&String(o)===String(e.matchValue)};function it(t){const o=t.entry?.code??e.REST_BUSINESS_UNKNOWN,r=t.message??function(e){const t=e.apiName?`${e.apiName} failed`:"request failed";if(e.entry?.runtimeMessage)return`REST business error: ${e.entry.runtimeMessage}`;if(e.mapped??Boolean(e.entry)){if(e.reasonKey){const t=e.reasonKey.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split("_").join(" ").split("-").join(" ").toLowerCase();return`REST business error: ${t.charAt(0).toUpperCase()}${t.slice(1)}`}return`REST business error: ${t}`}return e.reasonKey?`REST business error: ${t} (${e.reasonKey})`:`REST business error: ${t}`}({apiName:t.apiName,entry:t.entry,mapped:t.mapped,reasonKey:t.reasonKey});return new d(r,{code:o,details:{api:t.apiName,serverCode:t.serverCode,serverMessage:t.serverMessage,httpStatus:t.httpStatus,mapped:t.mapped??Boolean(t.entry),reasonKey:t.reasonKey,matchedBy:t.matchedBy,retryable:t.entry?.retryable,canonicalCode:t.entry?.canonicalCode??t.entry?.code}})}const at={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"}},nt=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase(),pt=e=>{if(Array.isArray(e))return e.length;if(!e||"object"!=typeof e)return;const t=e;for(const o of["entities","data","items","messages","conversations","results"]){const e=t[o];if(Array.isArray(e))return e.length}};class Et{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.timeout=t?.timeout??15e3,this.errorMap=t?.errorMap,this.requestAdapter=t?.requestAdapter,this.includeRequestId=t?.includeRequestId??!1,this.defaultHeaders={Accept:"application/json",...t?.headers}}sanitizeUrl(e){try{const t=new URL(e),o=t.searchParams;for(const e of o.keys())o.set(e,"***");const r=o.toString(),s=r?`?${r}`:"";return`${t.origin}${t.pathname}${s}`}catch{return e.split("?")[0]??e}}setAuthToken(e){this.defaultHeaders.Authorization=`Bearer ${e}`}removeAuthToken(){delete this.defaultHeaders.Authorization}buildHttpStatusFallbackError(t,o,r,s){const i={...o.operation?{api:o.operation}:{},url:o.url,method:o.method,httpStatus:t,serverCode:r,serverMessage:s,mapped:!1};if(400===t)return new p("Invalid request parameters",{code:e.VALIDATION_UNKNOWN,details:{...i,canonicalCode:e.VALIDATION_UNKNOWN}});if(401===t){const t=[r,s].some(e=>"string"==typeof e&&/token[ _-]?(?:has[ _-]?)?expired/i.test(e)),o=t?e.AUTH_TOKEN_EXPIRED:e.AUTH_UNAUTHORIZED;return new n(t?"Authentication token expired":"Authentication failed",{code:o,details:{...i,reasonKey:t?"token_expired":"unauthorized",canonicalCode:o}})}return 403===t?new n("Access forbidden",{code:e.AUTH_FORBIDDEN,details:{...i,canonicalCode:e.AUTH_FORBIDDEN}}):429===t?new d("REST rate limit exceeded",{code:e.SERVICE_LIMIT_EXCEEDED,details:{...i,retryable:!0,reasonKey:"request_rate_limited",canonicalCode:e.SERVICE_LIMIT_EXCEEDED}}):t>=500?new d("REST business error: request failed",{code:e.REST_BUSINESS_UNKNOWN,details:{...i,retryable:!0,reasonKey:"server_unknown_error",canonicalCode:e.REST_BUSINESS_UNKNOWN}}):void 0}async request(t,o={}){const r=`${this.baseUrl}${t}`,i=o.method??"GET",a=Date.now(),n=this.sanitizeUrl(r);ve.debug("REST request",{method:i,url:n,operation:o.operation});const p=o.operation?(e=>{const t=at[e];if(t)return t;const o=(e=>{const t=e.toLowerCase();return t.includes("chatroom")||t.includes("chat_room")?"CHATROOM":t.includes("group")?"GROUP":t.includes("contact")||t.includes("blocklist")?"ROSTER":t.includes("userinfo")||t.includes("presence")?"USER":"REST"})(e);return{operationName:`REST_${nt(e)}`,operationType:o}})(o.operation):void 0,E=p?ot(p):void 0,c=E?.startRequest({requestName:p?.operationName,method:i,url:r});let u=0;const d={...this.defaultHeaders,...o.headers};this.includeRequestId&&(d[Ke]=ke());const l={method:i,headers:d};if(o.body&&"GET"!==i){const e=Object.keys(d).some(e=>"content-type"===e.toLowerCase());"string"==typeof o.body?(e||(d["Content-Type"]="application/x-www-form-urlencoded"),l.body=o.body):(e||(d["Content-Type"]="application/json"),l.body=JSON.stringify(o.body))}else if("GET"===i)for(const e of Object.keys(d))"content-type"===e.toLowerCase()&&delete d[e];try{if(this.requestAdapter){const e=await this.requestAdapter.request({url:r,method:i,headers:d,body:o.body,timeoutMs:o.timeout??this.timeout});u=e.status;const t=((e,t)=>{if("string"!=typeof e)return e;const o=Object.entries(t).find(([e])=>"content-type"===e.toLowerCase()),r=e.trim();if(!(o?.[1].includes("application/json")||r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]")))return e;try{return JSON.parse(r)}catch{return e}})(e.data,e.headers),s=Date.now()-a;(e.status<200||e.status>=300)&&(ve.warn("REST response error",{method:i,url:n,status:e.status,duration:s}),this.handleErrorPayload(e.status,"",t,{operation:o.operation,url:r,method:i})),ve.debug("REST response",{method:i,url:n,status:e.status,duration:s});const p=pt(t);return c?.finish({code:e.status,success:!0,resultCount:p}),E?.finish({code:0,success:!0,resultCount:p}),t}const e=new AbortController,t=setTimeout(()=>e.abort(),o.timeout??this.timeout),s=await fetch(r,{...l,signal:e.signal});u=s.status,clearTimeout(t);const p=Date.now()-a;s.ok||(ve.warn("REST response error",{method:i,url:n,status:s.status,duration:p}),await this.handleErrorResponse(s,{operation:o.operation,url:r,method:i})),ve.debug("REST response",{method:i,url:n,status:s.status,duration:p});const T=s.headers.get("content-type");if(T?.includes("application/json")){const e=await s.json(),t=pt(e);return c?.finish({code:s.status,success:!0,resultCount:t}),E?.finish({code:0,success:!0,resultCount:t}),e}const _=await s.text();return c?.finish({code:s.status,success:!0}),E?.finish({code:0,success:!0}),_}catch(_){const t=0!==u?u:_ instanceof s?_.code:-1,a=_ instanceof Error?_.message:String(_);if(c?.finish({code:t,success:!1,description:a}),E?.finish({code:t,success:!1,description:a}),_ instanceof s)throw _;if(_ instanceof Error&&"AbortError"===_.name)throw ve.warn("REST request timeout",{method:i,url:n,timeout:o.timeout??this.timeout}),new T(`Request timeout: ${r}`,{code:e.REST_TIMEOUT,details:{url:r,method:i,timeout:o.timeout??this.timeout}});throw ve.warn("REST request failed",{method:i,url:n}),new T(`Request failed: ${r}`,{code:e.REST_NETWORK_ERROR,details:{url:r,method:i}})}}async handleErrorResponse(e,t){let o;try{o=await e.json()}catch{o=await e.text()}this.handleErrorPayload(e.status,e.statusText,o,t)}handleErrorPayload(t,o,r,s){const i=r&&"object"==typeof r?r:{},a=((e,t)=>{if(!e.error||"object"!=typeof e.error||Array.isArray(e.error))return;const o=e.error,r=o.code;if("number"!=typeof r&&"string"!=typeof r)return;const s=String(r);return/^\d{7}$/.test(s)&&Number(s.slice(0,3))===t?o:void 0})(i,t),n=a?{...i,code:a.code,message:a.message}:r,p=function(e,t,o){if(!e)return;const r=o&&"object"==typeof o?o:{},s="string"==typeof r.error?r.error:void 0,i=(e=>"string"==typeof e.error_code||"number"==typeof e.error_code?e.error_code:"string"==typeof e.errorCode||"number"==typeof e.errorCode?e.errorCode:"string"==typeof e.error||"number"==typeof e.error?e.error:"string"==typeof e.code||"number"==typeof e.code?e.code:void 0)(r),a="string"==typeof r.error_description?r.error_description:"string"==typeof r.message?r.message:void 0,n=(e,t=!1)=>{const o=(e,o,r)=>({reasonKey:e,entry:o,matchedBy:t?"common":r});if(s&&e[s])return o(s,e[s],"key");for(const[s,i]of Object.entries(e))if(st(i,r))return o(s,i,"field");if(void 0!==i)for(const[r,s]of Object.entries(e)){if(s.code===i||s.canonicalCode===i)return o(r,s,"code");if(Array.isArray(s.aliases)&&s.aliases.includes(String(i)))return o(r,s,"alias")}if(a)for(const[r,s]of Object.entries(e))if(Array.isArray(s.aliases)&&s.aliases.includes(a))return o(r,s,"alias")},p=t?e.apis[t]:void 0,E=p?n(p.errors):void 0;if(E)return E;for(const c of Object.values(e.common)){const e=n(c.errors,!0);if(e)return e}}(this.errorMap,s.operation,n),E="string"==typeof i.error?i.error:void 0,c="number"==typeof i.error_code||"string"==typeof i.error_code?i.error_code:"number"==typeof i.errorCode||"string"==typeof i.errorCode?i.errorCode:"number"==typeof i.code||"string"==typeof i.code?i.code:"string"==typeof i.error?i.error:"number"==typeof a?.code||"string"==typeof a?.code?a.code:void 0,u="string"==typeof i.message?i.message:"string"==typeof i.error_description?i.error_description:"string"==typeof a?.message?a.message:void 0,d=!!(401!==t&&403!==t||void 0!==E&&"unauthorized"!==E&&"auth_failed"!==E&&"forbidden"!==E)&&(void 0!==E||"string"==typeof i.error_description||"string"==typeof i.message);if(s.operation&&p)throw it({apiName:s.operation,entry:p.entry,serverCode:c,serverMessage:u,httpStatus:t,mapped:!0,reasonKey:p.reasonKey,matchedBy:p.matchedBy});const l=this.buildHttpStatusFallbackError(t,s,c,u);if(l)throw l;if(s.operation&&d)throw it({apiName:s.operation,serverCode:c,serverMessage:u,httpStatus:t,mapped:!1,reasonKey:E});throw new T(`HTTP ${t}: ${o}`,{code:e.REST_HTTP_ERROR,details:{url:s.url,method:s.method,httpStatus:t}})}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,o){return this.request(e,{...o,method:"POST",body:t})}put(e,t,o){return this.request(e,{...o,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}patch(e,t,o){return this.request(e,{...o,method:"PATCH",body:t})}}const ct=(...e)=>{const t={},o={};for(const r of e)Object.assign(t,r.common),Object.assign(o,r.apis);return{common:t,apis:o}},ut={common:{validation:{range:"100-110",errors:{MISSING_REQUIRED:{code:110},INVALID_FORMAT:{code:110},UNKNOWN:{code:110}}},auth:{range:"108,200-215",errors:{ALREADY_LOGIN:{code:200},NOT_LOGIN:{code:201},UNAUTHORIZED:{code:202},FORBIDDEN:{code:210},TOKEN_EXPIRED:{code:108},BIND_ANOTHER_DEVICE:{code:213},LOGIN_TOO_MANY_DEVICES:{code:214},USER_MUTED:{code:215}}},connection:{range:"1,100,202,300-304",errors:{TIMEOUT:{code:301},WEBSOCKET_ERROR:{code:300},NOT_CREATED:{code:1},CLOSED_BEFORE_READY:{code:300},CANCELLED:{code:1},PROVISION_TIMEOUT:{code:301},PROVISION_REJECTED:{code:202},PROVISION_CLOSED:{code:300},DNSLIST_FAILED:{code:304},SERVER_BUSY:{code:302}}},storage:{range:"3",errors:{OPERATION_FAILED:{code:3}}},message:{range:"1,300-511",errors:{NOT_CONNECTED:{code:300},ACK_TIMEOUT:{code:301},SEND_FAILED:{code:303},SENDER_DESTROYED:{code:1},ENCODE_FAILED:{code:500},DECODE_FAILED:{code:500},ACK_MISSING:{code:301}}},transport:{range:"2,301,303",errors:{NETWORK_ERROR:{code:2},TIMEOUT:{code:301},HTTP_ERROR:{code:303},BUSINESS_UNKNOWN:{code:303}}},upload:{range:"1,100,110,301,402,405",errors:{REQUIRED_FIELD_MISSING:{code:110},INVALID_APPKEY:{code:100},SIZE_EXCEEDED:{code:405},REQUEST_FAILED:{code:402},TIMEOUT:{code:301},ABORTED:{code:1}}},unknown:{range:"1,4",errors:{UNKNOWN:{code:1},SERVICE_LIMIT_EXCEEDED:{code:4}}},push:{range:"1500,1501,1502",errors:{TOKEN_UPLOAD_FAILED:{code:1500},SILENT_MODE_OPERATION_FAILED:{code:1501},PUSH_LANGUAGE_OPERATION_FAILED:{code:1502}}},chatroom:{range:"700-707",errors:{CHATROOM_INVALID_ID:{code:700},CHATROOM_NOT_JOINED:{code:702},CHATROOM_PERMISSION_DENIED:{code:703},CHATROOM_MEMBERS_FULL:{code:704},CHATROOM_NOT_EXIST:{code:705},CHATROOM_OWNER_NOT_ALLOW_LEAVE:{code:706},CHATROOM_USER_IN_BLOCKLIST:{code:707}}}},apis:{}};export{D as $,n as A,ce as B,a as C,Ve as D,e as E,Oe as F,me as G,A as H,oe as I,R as J,J as K,ne as L,E as M,i as N,ie as O,S as P,se as Q,d as R,s as S,Ne as T,l as U,p as V,Te as W,de as X,le as Y,G as Z,u as _,ue as a,b as a0,g as a1,o as a2,U as a3,M as a4,L as a5,v as a6,w as a7,k as a8,F as a9,K as aa,B as ab,H as ac,P as ad,Xe as ae,Je as af,be as ag,Qe as ah,Ze as ai,Ge as aj,Pe as ak,rt as al,He as am,we as an,et as ao,_ as ap,Le as aq,m as ar,h as as,Ke as b,it as c,_e as d,ke as e,Et as f,Fe as g,T as h,ut as i,he as j,N as k,ve as l,ct as m,Y as n,C as o,ae as p,y as q,I as r,r as s,Re as t,f as u,ot as v,c as w,O as x,X as y,Q as z};
@@ -1 +0,0 @@
1
- const e={MESSAGE:"onMessage",STREAM_MESSAGE:"onStreamMessage",CONVERSATION_LIST_UPDATE:"onConversationListUpdate",MESSAGE_READ_RECEIPTS:"onMessageReadReceipts",MESSAGE_DELIVERED:"onMessageDelivered",MESSAGE_RECALLED:"onMessageRecalled",MESSAGE_UPDATED:"onMessageUpdated",REACTION_CHANGED:"onReactionChanged",PINNED_MESSAGE_CHANGED:"onPinnedMessageChanged",MULTI_DEVICE_CONTACT:"onMultiDeviceContact",MULTI_DEVICE_CONVERSATION:"onMultiDeviceConversation",SYNC_DATA_START:"onSyncDataStart",SYNC_DATA_FINISHED:"onSyncDataFinished"},E={STATUS_CHANGE:"onPresenceStatusChange"},o={INVITED:"onContactInvited",DELETED:"onContactDeleted",ADDED:"onContactAdded",REFUSE:"onContactRefuse",AGREED:"onContactAgreed",CONTACT_INFO_UPDATED:"onContactInfoUpdated"},_={INVITATION_RECEIVED:"onInvitationReceived",REQUEST_TO_JOIN_RECEIVED:"onRequestToJoinReceived",REQUEST_TO_JOIN_ACCEPTED:"onRequestToJoinAccepted",REQUEST_TO_JOIN_DECLINED:"onRequestToJoinDeclined",INVITATION_ACCEPTED:"onInvitationAccepted",INVITATION_DECLINED:"onInvitationDeclined",USER_REMOVED:"onUserRemoved",GROUP_DESTROYED:"onGroupDestroyed",AUTO_ACCEPT_INVITATION:"onAutoAcceptInvitationFromGroup",MUTE_LIST_ADDED:"onMuteListAdded",MUTE_LIST_REMOVED:"onMuteListRemoved",ALLOW_LIST_ADDED:"onAllowListAdded",ALLOW_LIST_REMOVED:"onAllowListRemoved",ALL_MEMBER_MUTE_STATE_CHANGED:"onAllMemberMuteStateChanged",ADMIN_ADDED:"onAdminAdded",ADMIN_REMOVED:"onAdminRemoved",OWNER_CHANGED:"onOwnerChanged",MEMBERS_JOINED:"onMembersJoined",MEMBERS_EXITED:"onMembersExited",ANNOUNCEMENT_CHANGED:"onAnnouncementChanged",SHARED_FILE_ADDED:"onSharedFileAdded",SHARED_FILE_DELETED:"onSharedFileDeleted",GROUP_INFO_CHANGED:"onGroupInfoChanged",GROUP_DISABLED_CHANGED:"onGroupDisabledChanged",GROUP_MEMBER_ATTRIBUTE_CHANGED:"onGroupMemberAttributeChanged",USER_GROUP_NAMECARD_UPDATED:"onUserGroupNamecardUpdated"},n={CHAT_ROOM_DESTROYED:"__chatroom:onChatRoomDestroyed",MEMBERS_JOINED:"__chatroom:onMembersJoined",MEMBERS_EXITED:"__chatroom:onMembersExited",REMOVED_FROM_CHAT_ROOM:"__chatroom:onRemovedFromChatRoom",MUTE_LIST_ADDED:"__chatroom:onMuteListAdded",MUTE_LIST_REMOVED:"__chatroom:onMuteListRemoved",ALLOW_LIST_ADDED:"__chatroom:onAllowListAdded",ALLOW_LIST_REMOVED:"__chatroom:onAllowListRemoved",ALL_MEMBER_MUTE_STATE_CHANGED:"__chatroom:onAllMemberMuteStateChanged",ADMIN_ADDED:"__chatroom:onAdminAdded",ADMIN_REMOVED:"__chatroom:onAdminRemoved",OWNER_CHANGED:"__chatroom:onOwnerChanged",ANNOUNCEMENT_CHANGED:"__chatroom:onAnnouncementChanged",CHAT_ROOM_INFO_CHANGED:"__chatroom:onChatRoomInfoChanged",ATTRIBUTES_UPDATE:"__chatroom:onAttributesUpdate",ATTRIBUTES_REMOVED:"__chatroom:onAttributesRemoved"};export{e as C,_ as G,E as P,o as a,n as b};
@@ -1 +0,0 @@
1
- "use strict";const e=require("./common-BIpcR2uQ.cjs"),r={INIT:"init",REQUEST:"request",UPLOAD:"upload",SOCKET:"socket",PROTO:"proto",RUNTIME:"runtime",STORAGE:"storage"},s={INIT_FAILED:"PLATFORM_INIT_FAILED",MISSING_CAPABILITY:"PLATFORM_MISSING_CAPABILITY",REQUEST_FAILED:"PLATFORM_REQUEST_FAILED",UPLOAD_FAILED:"PLATFORM_UPLOAD_FAILED",SOCKET_FAILED:"PLATFORM_SOCKET_FAILED",PROTO_FAILED:"PLATFORM_PROTO_FAILED"},t=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],o=(e,r)=>`${e}\0${r}`,n=(e,r,s)=>{const o={userId:e};for(const n of t){const e=s?.[n]??r?.[n];void 0!==e&&(o[n]=e)}return o},a=e=>n(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),i=(e,r,s)=>{const t=new Map;if(!e?.getGroupNamecard||!s)return t;for(const n of r){const r=e.getGroupNamecard(n.groupId,n.user.userId,!1);r&&t.set(o(n.groupId,n.user.userId),r.namecard)}return t},I=async(r,s)=>{if(0===r.length||!s)return[];try{return await s({userIds:r})}catch(t){return e.logger.warn("Group user info hydration failed",{userIds:r,error:t}),[]}},d=async(r,s)=>{s&&0!==r.size&&await Promise.all([...r.entries()].map(async([r,t])=>{try{await s(r,t)}catch(o){e.logger.warn("Group namecard hydration failed",{groupId:r,userIds:t,error:o})}}))},u=async e=>{const r=(e=>{const r=[],s=new Set;for(const t of e){const e=t.groupId.trim(),n=t.user.userId.trim();if(!e||!n)continue;const a=o(e,n);s.has(a)||(s.add(a),r.push({groupId:e,user:{...t.user,userId:n}}))}return r})(e.contexts),s=(e=>{const r=[],s=new Set;for(const t of e)s.has(t.user.userId)||(s.add(t.user.userId),r.push(t.user.userId));return r})(r),t=((e,r)=>{const s=new Map;if(!e)return s;for(const o of r){const r=e.getRuntimeUserInfo?.(o,!1)??null;r&&s.set(o,r)}const t=r.filter(e=>!s.has(e));for(const o of e.getUserInfoSummaries?.(t,!1)??[])s.set(o.userId,a(o));return s})(e.cacheManager,s),u=s.filter(e=>!t.has(e)),c=new Set(u),p=i(e.cacheManager,r,e.includeNameCard),E=e.includeNameCard?((e,r,s)=>{const t=new Map;for(const n of e){const e=n.user.userId,a=o(n.groupId,e);if(!r.has(e)||s.has(a))continue;const i=t.get(n.groupId)??[];i.includes(e)||i.push(e),t.set(n.groupId,i)}return t})(r,c,p):new Map,[l]=await Promise.all([I(u,e.fetchUserInfos),d(E,e.hydrateGroupNamecards)]),A=new Map(l.map(e=>[e.userId,e])),f=i(e.cacheManager,r,e.includeNameCard),R=new Map;for(const a of r){const e=a.user.userId,r=o(a.groupId,e),s=n(e,a.user,A.get(e)??t.get(e)),i=f.get(r)??p.get(r);R.set(r,void 0!==i?{...s,nameCard:i}:s)}return{usersByContextKey:R,fetchedUserInfos:l,missingUserIds:u.filter(e=>!A.has(e))}};exports.PLATFORM_ERROR_CODE=s,exports.PLATFORM_ERROR_STAGE=r,exports.RUNTIME_PLATFORMS={WEB:"web",WECHAT_MINIAPP:"wechat-miniapp",QQ_MINIAPP:"qq-miniapp",TOUTIAO_MINIAPP:"toutiao-miniapp",BAIDU_MINIAPP:"baidu-miniapp",ALIPAY_MINIAPP:"alipay-miniapp",DINGTALK_MINIAPP:"dingtalk-miniapp",LARK_MINIAPP:"lark-miniapp",KUAISHOU_MINIAPP:"kuaishou-miniapp",JD_MINIAPP:"jd-miniapp",MINIAPP_360:"360-miniapp",HARMONY_MINIAPP:"harmony-miniapp",QUICKAPP:"quickapp",UNIAPP:"uniapp",REACT_NATIVE:"react-native",ELECTRON_RENDERER:"electron-renderer",ELECTRON_MAIN:"electron-main",UNKNOWN:"unknown"},exports.SOCKET_READY_STATE={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},exports.createPlatformError=(r,s)=>{const t=new Error(r);return t.name="PlatformAdapterError",t.code=s.code,t.stage=s.stage,t.retryable=s.retryable,s.details&&(t.details=e.sanitizeErrorDetails(s.details)),t},exports.getGroupUserInfoContextKey=o,exports.mapUploadAdapterError=t=>{if(t instanceof e.UploadError)return t;if((e=>"object"==typeof e&&null!==e)(t)){const o=t.details;if(t.code===s.MISSING_CAPABILITY){const s=o?.capability;if(t.stage===r.RUNTIME&&"string"==typeof s&&s.includes("FileSystem")){const r=t instanceof Error?t.message:"Upload failed";return new e.UploadError(r,{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:o})}return new e.UploadError("Upload capability is missing for current platform",{code:e.ERROR_CODES.UPLOAD_REQUIRED_FIELD_MISSING,details:o})}if(t.stage===r.UPLOAD)return(e=>{const r=e?.reason;return!("string"!=typeof r||!r.toLowerCase().includes("abort"))})(o)?new e.UploadError("Upload canceled",{code:e.ERROR_CODES.UPLOAD_ABORTED,details:o}):(e=>{const r=e?.reason;return!("string"!=typeof r||!r.toLowerCase().includes("timeout"))})(o)?new e.UploadError("Upload timeout",{code:e.ERROR_CODES.UPLOAD_TIMEOUT,details:o}):new e.UploadError("Upload failed",{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:o})}const o=t instanceof Error?t.message:"Upload failed";return new e.UploadError(o,{code:e.ERROR_CODES.UPLOAD_REQUEST_FAILED,details:{cause:t}})},exports.resolveGroupUserInfoContexts=u,exports.resolveGroupUserInfoMap=async e=>{const r=await u({...e,contexts:e.users.map(r=>({groupId:e.groupId,user:r}))}),s=new Map;for(const t of e.users){const n=t.userId.trim();if(!n||s.has(n))continue;const a=r.usersByContextKey.get(o(e.groupId.trim(),n));a&&s.set(n,a)}return{usersById:s,fetchedUserInfos:r.fetchedUserInfos,missingUserIds:r.missingUserIds}};
@@ -1 +0,0 @@
1
- import{s as e,U as r,E as s,l as t}from"./common-D_DfwSd3.js";const a={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"},n={INIT:"init",REQUEST:"request",UPLOAD:"upload",SOCKET:"socket",PROTO:"proto",RUNTIME:"runtime",STORAGE:"storage"},o={INIT_FAILED:"PLATFORM_INIT_FAILED",MISSING_CAPABILITY:"PLATFORM_MISSING_CAPABILITY",REQUEST_FAILED:"PLATFORM_REQUEST_FAILED",UPLOAD_FAILED:"PLATFORM_UPLOAD_FAILED",SOCKET_FAILED:"PLATFORM_SOCKET_FAILED",PROTO_FAILED:"PLATFORM_PROTO_FAILED"},i=(r,s)=>{const t=new Error(r);return t.name="PlatformAdapterError",t.code=s.code,t.stage=s.stage,t.retryable=s.retryable,s.details&&(t.details=e(s.details)),t},I={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},u=e=>{if(e instanceof r)return e;if((e=>"object"==typeof e&&null!==e)(e)){const t=e.details;if(e.code===o.MISSING_CAPABILITY){const a=t?.capability;if(e.stage===n.RUNTIME&&"string"==typeof a&&a.includes("FileSystem")){const a=e instanceof Error?e.message:"Upload failed";return new r(a,{code:s.UPLOAD_REQUEST_FAILED,details:t})}return new r("Upload capability is missing for current platform",{code:s.UPLOAD_REQUIRED_FIELD_MISSING,details:t})}if(e.stage===n.UPLOAD)return(e=>{const r=e?.reason;return!("string"!=typeof r||!r.toLowerCase().includes("abort"))})(t)?new r("Upload canceled",{code:s.UPLOAD_ABORTED,details:t}):(e=>{const r=e?.reason;return!("string"!=typeof r||!r.toLowerCase().includes("timeout"))})(t)?new r("Upload timeout",{code:s.UPLOAD_TIMEOUT,details:t}):new r("Upload failed",{code:s.UPLOAD_REQUEST_FAILED,details:t})}const t=e instanceof Error?e.message:"Upload failed";return new r(t,{code:s.UPLOAD_REQUEST_FAILED,details:{cause:e}})},c=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],d=(e,r)=>`${e}\0${r}`,p=(e,r,s)=>{const t={userId:e};for(const a of c){const e=s?.[a]??r?.[a];void 0!==e&&(t[a]=e)}return t},A=e=>p(e.userId,void 0,{userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),f=(e,r,s)=>{const t=/* @__PURE__ */new Map;if(!e?.getGroupNamecard||!s)return t;for(const a of r){const r=e.getGroupNamecard(a.groupId,a.user.userId,!1);r&&t.set(d(a.groupId,a.user.userId),r.namecard)}return t},l=async(e,r)=>{if(0===e.length||!r)return[];try{return await r({userIds:e})}catch(s){return t.warn("Group user info hydration failed",{userIds:e,error:s}),[]}},m=async(e,r)=>{r&&0!==e.size&&await Promise.all([...e.entries()].map(async([e,s])=>{try{await r(e,s)}catch(a){t.warn("Group namecard hydration failed",{groupId:e,userIds:s,error:a})}}))},E=async e=>{const r=(e=>{const r=[],s=/* @__PURE__ */new Set;for(const t of e){const e=t.groupId.trim(),a=t.user.userId.trim();if(!e||!a)continue;const n=d(e,a);s.has(n)||(s.add(n),r.push({groupId:e,user:{...t.user,userId:a}}))}return r})(e.contexts),s=(e=>{const r=[],s=/* @__PURE__ */new Set;for(const t of e)s.has(t.user.userId)||(s.add(t.user.userId),r.push(t.user.userId));return r})(r),t=((e,r)=>{const s=/* @__PURE__ */new Map;if(!e)return s;for(const a of r){const r=e.getRuntimeUserInfo?.(a,!1)??null;r&&s.set(a,r)}const t=r.filter(e=>!s.has(e));for(const a of e.getUserInfoSummaries?.(t,!1)??[])s.set(a.userId,A(a));return s})(e.cacheManager,s),a=s.filter(e=>!t.has(e)),n=new Set(a),o=f(e.cacheManager,r,e.includeNameCard),i=e.includeNameCard?((e,r,s)=>{const t=/* @__PURE__ */new Map;for(const a of e){const e=a.user.userId,n=d(a.groupId,e);if(!r.has(e)||s.has(n))continue;const o=t.get(a.groupId)??[];o.includes(e)||o.push(e),t.set(a.groupId,o)}return t})(r,n,o):/* @__PURE__ */new Map,[I]=await Promise.all([l(a,e.fetchUserInfos),m(i,e.hydrateGroupNamecards)]),u=new Map(I.map(e=>[e.userId,e])),c=f(e.cacheManager,r,e.includeNameCard),E=/* @__PURE__ */new Map;for(const A of r){const e=A.user.userId,r=d(A.groupId,e),s=p(e,A.user,u.get(e)??t.get(e)),a=c.get(r)??o.get(r);E.set(r,void 0!==a?{...s,nameCard:a}:s)}return{usersByContextKey:E,fetchedUserInfos:I,missingUserIds:a.filter(e=>!u.has(e))}},P=async e=>{const r=await E({...e,contexts:e.users.map(r=>({groupId:e.groupId,user:r}))}),s=/* @__PURE__ */new Map;for(const t of e.users){const a=t.userId.trim();if(!a||s.has(a))continue;const n=r.usersByContextKey.get(d(e.groupId.trim(),a));n&&s.set(a,n)}return{usersById:s,fetchedUserInfos:r.fetchedUserInfos,missingUserIds:r.missingUserIds}};export{o as P,a as R,I as S,n as a,E as b,i as c,d as g,u as m,P as r};
@@ -1 +0,0 @@
1
- import{V as e,E as t,p as s,S as r,A as a,l as n,f as o,m as i,i as c}from"./common-D_DfwSd3.js";import{i as d}from"./cache-utils-B99glc0H.js";import{b as l,a as u,n as h}from"./user-info-DfbCp80h.js";import{a as p,b as g,L as m}from"./reflection-proto-codec-CjRraw85.js";import{l as y}from"./light-Dg9A1Xmd.js";const I=e=>({userId:e}),f=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),C=e=>e,S=async(e,t)=>{const s=(e=>{const t=[],s=/* @__PURE__ */new Set;for(const r of e){const e=r.trim();e&&!s.has(e)&&(s.add(e),t.push(e))}return t})(e),r=/* @__PURE__ */new Map;if(0===s.length)return r;const a=t.cacheManager?.getUserInfoSummaries(s,!1)??[];for(const o of a)r.set(o.userId,f(o));const n=s.filter(e=>!r.has(e));if(n.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:n});for(const t of e)r.set(t.userId,C(t))}for(const o of s)r.has(o)||r.set(o,I(o));return r},R=async(e,t)=>((e,t,s)=>({userId:s,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 S([e],t)).get(e),e),v={UNSPECIFIED:0,PING:1,PONG:2,REQUEST:3,RESPONSE:4,ERROR:5},E=0,T=0,_=1,U=1001,w=1002,b=1003,k=1004,N=1005,A=1101,O=e=>{const{orgName:t,appName:r}=s(e.appKey);return{orgName:t,appName:r,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},M=e=>d(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):[],q=(s,r)=>{if(!Array.isArray(s.userIds)||0===s.userIds.length)throw new e(`${r} is required`,{code:t.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}});const a=s.userIds.map((s,a)=>{if("string"!=typeof s)throw new e(`${r}[${a}] must be a string`,{code:t.VALIDATION_INVALID_FORMAT,details:{fields:[{path:`${r}[${a}]`,message:"userId must be a string",rule:"invalid_format"}]}});return s.trim()}),n=(e=>{const t=[],s=/* @__PURE__ */new Set;for(const r of e)r&&!s.has(r)&&(s.add(r),t.push(r));return t})(a);if(0===n.length)throw new e(`${r} is required`,{code:t.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}});return n.length!==a.length&&d(s),n},D=async(e,t)=>{const s=O(t),r=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/blocks/users`,a=await e.get(r,{operation:"getBlocklist"});return M(a).map(e=>({userId:e}))},$=async(e,t,s)=>{const r=O(t),a=`/${r.orgName}/${r.appName}/sdk/user/${r.encodedUserId}/blocks?resource=${r.encodedResource}`,n=await e.post(a,{usernames:s},{operation:"addUsersToBlocklist"});return{succeeded:M(n).map(e=>({userId:e})),failed:[]}},P={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 B=!1,F=null;const x=()=>F||(B||(y.util.Long=m,y.configure(),B=!0),p(),F=y.Root.fromJSON(P),g(F),F),L=e=>"number"==typeof e?e:m.isLong(e)?e.toNumber():0,V=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:L(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:L(t.protocolVersion)}};class G{encodeRequest(e){const t=x().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=E){const t=x().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:v.PONG,status:e})).finish()}decode(e){const t=x(),s=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(s.type){case v.PING:return{type:v.PING};case v.PONG:{const s=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:v.PONG,status:L(s.status)}}case v.RESPONSE:{const s=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:v.RESPONSE,header:V(s.header),data:Array.isArray(s.data)?s.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:L(t.createdAt),updatedAt:L(t.updatedAt),metadataUpdatedAt:L(t.metadataUpdatedAt)}})(e)):[],cursor:L(s.cursor),version:"string"==typeof s.version?s.version:"",responseType:L(s.responseType)||T}}case v.ERROR:{const s=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:v.ERROR,header:V(s.header),code:"string"==typeof s.code?s.code:"",message:"string"==typeof s.message?s.message:"Unknown roster error"}}default:return{type:"number"==typeof s.type?s.type:v.UNSPECIFIED}}}}class Y{constructor(e){this.pages=[],this.responseType=null,this.version="",this.nextCursor=0,this.pageCount=0,this.completed=!1,this.requestId=e}push(e){const s=e.header?.requestId;if(s&&s!==this.requestId)throw new r("Roster response requestId mismatched",t.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",expectedRequestId:this.requestId,receivedRequestId:s}});if(this.completed)throw new r("Roster response received after completion",t.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:e.cursor}});if(null!==this.responseType&&this.responseType!==e.responseType)throw new r("Roster response type changed in same session",t.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 r("Roster cursor duplicated",t.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===_?"incremental":"full",version:this.version,pages:this.pages}}}const H=e=>e.type===v.RESPONSE,K=e=>"message"in e&&"code"in e;class W{constructor(e){this.codec=new G,this.sharedSession=e}async sync(e){const t=new Y(e.request.header.requestId);return await this.syncWithSharedSession(e.request,t)}cancel(){this.sharedSession.cancel("contact-sync-cancelled")}async syncWithSharedSession(e,s){return await this.sharedSession.request({dataType:"contact",label:"Roster sync",requestId:e.header.requestId,encode:()=>{const t=this.buildAttemptRequest(e,s.getNextCursor());return this.codec.encodeRequest(t)},decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:H(t)||K(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(e,n)=>{try{if(e.type===v.PING)return void(await n.send(this.codec.encodePong()));if(H(e)){if(!s.push(e).done)return;return{done:!0,result:s.buildResult()}}if(K(e))throw(e=>{const s=e.header?.requestId,n=t=>({stage:"sync_page",serverCode:e.code,requestId:s,retryable:t});switch(Number.parseInt(e.code,10)){case w:return new a(e.message,{code:t.AUTH_UNAUTHORIZED,details:n(!1)});case b:return new r(e.message,t.SERVICE_LIMIT_EXCEEDED,{details:n(!0)});case U:return new r(e.message,t.VALIDATION_REQUIRED,{details:n(!1)});case k:return new r(e.message,t.VALIDATION_INVALID_FORMAT,{details:n(!1)});case N:return new r(e.message,t.REST_BUSINESS_UNKNOWN,{details:n(!0)});case A:return new r(e.message,t.CONTACT_SYNC_SOCKET_FAILED,{details:n(!1)});default:return new r(e.message,t.CONTACT_SYNC_SOCKET_FAILED,{details:n(!0)})}})(e);return}catch(o){throw o instanceof r?o:new r("Roster frame decode failed",t.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:o instanceof Error?o.message:String(o)}})}}})}buildAttemptRequest(e,t){return{...e,cursor:t,header:{...e.header,timestamp:Date.now(),requestId:e.header.requestId}}}}const j=e=>e.versionState.version?"incremental":"full",Q=e=>{const{metadata:t,metadataFailed:s,state:r}=e,a=r.versionState.version;return s||!t?{decision:"complete"===r.cacheMeta.cacheIntegrity?j(r):"full",version:a}:t.requiresSync||"complete"!==r.cacheMeta.cacheIntegrity?t.requiresSync&&"complete"===r.cacheMeta.cacheIntegrity&&a?{decision:"incremental",version:t.version||a}:{decision:"full",version:t.version||a}:{decision:"skip",version:t.version||a}},z=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{}}},J=e=>{const t=(e=>{if(!(e instanceof r&&e.details))return null;const t=e.details.httpStatus;return"number"==typeof t?t:null})(e);return 401===t||403===t||404===t},X=(e,t,s,r)=>({code:t,stage:e,message:`${e}: ${s}`,retryable:r}),Z=e=>{n.warn("Contact sync duration",e)};class ee{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(),s=Date.now();let a;this.dependencies.onStart();try{const t=await this.dependencies.queryMetadata(e.versionState.version);if(a=Q({metadata:t,state:e}),"skip"===a.decision)return this.dependencies.onFinish(),void Z({outcome:"skip",decision:a.decision,durationMs:Date.now()-s,version:a.version,hasUsableSnapshot:e.cachedSnapshot.complete})}catch(n){if(J(n)){const a=Q({metadataFailed:!0,state:e}),o=n instanceof r?n:new r("Contact metadata request failed",t.CONTACT_SYNC_METADATA_FAILED,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:X("metadata",o.code,o.message,!1)}),void Z({outcome:"fail",decision:a.decision,durationMs:Date.now()-s,version:e.versionState.version,stage:"metadata",hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}if(a=Q({metadataFailed:!0,state:e}),e.cachedSnapshot.complete)return this.dependencies.onFinish({error:X("metadata",t.CONTACT_SYNC_METADATA_FAILED,n instanceof Error?n.message:String(n),!0)}),void Z({outcome:"fail",decision:a.decision,durationMs:Date.now()-s,version:a.version,stage:"metadata",hasUsableSnapshot:!0,source:e.cachedSnapshot.source})}try{const t=await this.dependencies.getSyncUrls(),r=this.dependencies.buildRosterRequest({decision:a.decision,version:e.versionState.version}),n=await new W(this.dependencies.getSharedSyncSession()).sync({urls:t,request:r}),o=(e=>{const t=[];for(const s of e)for(const e of s.data){const s=z(e.metadata);t.push({relation:{userId:e.contact,remark:e.remark,sign:s.sign??"",addTs:e.createdAt,updatedAt:e.updatedAt,metadataUpdatedAt:e.metadataUpdatedAt},userInfo:{userId:e.contact,nickname:s.nickname,avatarUrl:s.avatarUrl,sign:s.sign,ext:s.ext}})}return t})(n.pages),i=this.dependencies.applySyncResult({mode:n.mode,relations:o.map(e=>e.relation),userInfos:o.map(e=>e.userInfo),version:n.version,lastSyncTs:Date.now()});this.dependencies.onFinish(),Z({outcome:"finish",decision:a.decision,durationMs:Date.now()-s,version:n.version,source:"sync",changed:i.changed,hasUsableSnapshot:i.snapshot.complete})}catch(n){const o=n instanceof r?n:new r("Contact sync failed",t.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"sync_page",cause:n instanceof Error?n.message:String(n)}}),i=o.details??{},c="string"==typeof i.stage?i.stage:"sync_page";this.dependencies.onFinish({error:X(c,o.code,o.message,!0)}),Z({outcome:"fail",decision:a.decision,durationMs:Date.now()-s,version:a.version,stage:c,hasUsableSnapshot:e.cachedSnapshot.complete,source:e.cachedSnapshot.complete?e.cachedSnapshot.source:void 0})}}}const te={items:[],loaded:!1,source:"server"},se=i(c,{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:{}}}}),re=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=te,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=te,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"),s=this.validateOptionalString(e.message,"params.message"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);n.debug("ContactManager addContact",{userId:t,hasMessage:"string"==typeof s&&s.length>0}),await(async(e,t,s)=>{const r=O(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/apply?resource=${r.encodedResource}`;await e.post(a,{usernames:[s.userId],reason:s.message??""},{operation:"addContact"})})(a,r,{userId:t,message:s})})}async deleteContact(e){return this.runOperation("deleteContact",async()=>{const t=this.validateUserId(e.userId,"params.userId"),s=this.getRestContextOrThrow(),r=this.getRestClient(s);n.debug("ContactManager deleteContact",{userId:t}),await(async(e,t,s)=>{const r=O(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.delete(a,{operation:"deleteContact"})})(r,s,{userId:t});const a=this.client?.getCacheManager()?.removeContact(t);n.debug("ContactManager deleteContact patched cache",{userId:t,changed:a?.changed??!1})})}async acceptContactInvite(e){return this.runOperation("acceptContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),s=this.getRestContextOrThrow(),r=this.getRestClient(s);n.debug("ContactManager acceptContactInvite",{userId:t}),await(async(e,t,s)=>{const r=O(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/accept/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.post(a,void 0,{operation:"acceptContactInvite"})})(r,s,{userId:t}),await this.requireClient().refreshContactSnapshot()})}async declineContactInvite(e){return this.runOperation("declineContactInvite",async()=>{const t=this.validateUserId(e.userId,"params.userId"),s=this.getRestContextOrThrow(),r=this.getRestClient(s);n.debug("ContactManager declineContactInvite",{userId:t}),await(async(e,t,s)=>{const r=O(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/decline/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.post(a,void 0,{operation:"declineContactInvite"})})(r,s,{userId:t})})}async setContactRemark(e){return this.runOperation("setContactRemark",async()=>{const t=this.validateUserId(e.userId,"params.userId"),s=this.validateRemark(e.remark,"params.remark"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);n.debug("ContactManager setContactRemark",{userId:t,remarkLength:s.length}),await(async(e,t,s)=>{const r=O(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.put(a,{remark:s.remark},{operation:"setContactRemark"})})(a,r,{userId:t,remark:s});const o=this.client?.getCacheManager()?.updateContactRemark(t,s);this.client?.refreshConversationDisplayFromUserInfos([{userId:t}],"profile"),n.debug("ContactManager setContactRemark patched cache",{userId:t,changed:o?.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 s=await this.enrichBlocklistUsers(await D(t,e));return this.blocklistSnapshot={items:s,loaded:!0,source:"server"},n.debug("ContactManager getBlocklist",{count:s.length}),s})}async addUsersToBlocklist(e){return this.runOperation("addUsersToBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const s=q(e,"params.userIds"),r=this.getRestClient(t);n.debug("ContactManager addUsersToBlocklist",{userIds:s,inputCount:e.userIds.length,normalizedCount:s.length});const a=await $(r,t,s),o=await this.enrichBlocklistUsers(a.succeeded);return this.blocklistSnapshot=this.patchBlocklistSnapshotWithAdditions(o),{succeeded:o,failed:await this.enrichBlocklistUsers(a.failed)}})}async removeUserFromBlocklist(e){return this.runOperation("removeUserFromBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const s=q(e,"params.userIds"),r=this.getRestClient(t);n.debug("ContactManager removeUserFromBlocklist",{userIds:s,inputCount:e.userIds.length,normalizedCount:s.length}),await(async(e,t,s)=>{const r=O(t),a=`/${r.orgName}/${r.appName}/sdk/user/${r.encodedUserId}/blocks?resource=${r.encodedResource}`;await e.request(a,{method:"DELETE",body:{usernames:s},operation:"removeUserFromBlocklist"})})(r,t,s),this.blocklistSnapshot=this.patchBlocklistSnapshotWithRemovals(s)})}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async runOperation(e,t){try{return await t()}catch(s){const t=this.normalizeSdkError(e,s);throw n.warn(`ContactManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,s){return s instanceof r?s:s instanceof Error?new r(`ContactManager ${e} failed: ${s.message}`,t.UNKNOWN):new r(`ContactManager ${e} failed`,t.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 o(e.restBaseUrl,{errorMap:se,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=te)}patchBlocklistSnapshotWithAdditions(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const s of e)t.set(s.userId,s);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 s of e)t.delete(s);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 s=e.trim();if(!s)throw this.buildValidationError("userId is required",[{path:t,message:"userId is required",rule:"required"}]);return s}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(s,r){const a=r.some(e=>"invalid_format"===e.rule)?t.VALIDATION_INVALID_FORMAT:t.VALIDATION_REQUIRED;return new e(s,{code:a,details:{fields:r}})}async enrichBlocklistUsers(e){if(0===e.length||!this.requireClient().isUserInfoSyncEnabled())return e;const t=await S(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 n.warn("ContactManager user info fetch failed",{userIds:e,error:t}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),s=l(e),r=await this.getRestClient(t).request(u(t),{method:"POST",body:s,operation:"getUserInfoByUserId"});return h(r,s.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 ee(e)}};re.key="contactManager";let ae=re;export{ae as C,v as R,R as r};
@@ -1 +0,0 @@
1
- "use strict";const e=require("./common-BIpcR2uQ.cjs"),t=require("./cache-utils-gowrxNr8.cjs"),s=require("./user-info-DsDDTJrw.cjs"),r=require("./reflection-proto-codec-BerStgkC.cjs"),a=require("./light-dJjIln5b.cjs"),n=e=>({userId:e}),o=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),i=e=>e,c=async(e,t)=>{const s=(e=>{const t=[],s=new Set;for(const r of e){const e=r.trim();e&&!s.has(e)&&(s.add(e),t.push(e))}return t})(e),r=new Map;if(0===s.length)return r;const a=t.cacheManager?.getUserInfoSummaries(s,!1)??[];for(const n of a)r.set(n.userId,o(n));const c=s.filter(e=>!r.has(e));if(c.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:c});for(const t of e)r.set(t.userId,i(t))}for(const o of s)r.has(o)||r.set(o,n(o));return r},d={UNSPECIFIED:0,PING:1,PONG:2,REQUEST:3,RESPONSE:4,ERROR:5},l=0,u=0,h=1,p=1001,g=1002,m=1003,y=1004,R=1005,I=1101,E=t=>{const{orgName:s,appName:r}=e.parseAppKey(t.appKey);return{orgName:s,appName:r,encodedUserId:encodeURIComponent(t.userId),encodedResource:encodeURIComponent(t.clientResource)}},C=e=>t.isRecord(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):[],S=(s,r)=>{if(!Array.isArray(s.userIds)||0===s.userIds.length)throw new e.ValidationError(`${r} is required`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}});const a=s.userIds.map((t,s)=>{if("string"!=typeof t)throw new e.ValidationError(`${r}[${s}] must be a string`,{code:e.ERROR_CODES.VALIDATION_INVALID_FORMAT,details:{fields:[{path:`${r}[${s}]`,message:"userId must be a string",rule:"invalid_format"}]}});return t.trim()}),n=(e=>{const t=[],s=new Set;for(const r of e)r&&!s.has(r)&&(s.add(r),t.push(r));return t})(a);if(0===n.length)throw new e.ValidationError(`${r} is required`,{code:e.ERROR_CODES.VALIDATION_REQUIRED,details:{fields:[{path:r,message:`${r} is required`,rule:"required"}]}});return n.length!==a.length&&t.isRecord(s),n},f=async(e,t)=>{const s=E(t),r=`/${s.orgName}/${s.appName}/users/${s.encodedUserId}/blocks/users`,a=await e.get(r,{operation:"getBlocklist"});return C(a).map(e=>({userId:e}))},v=async(e,t,s)=>{const r=E(t),a=`/${r.orgName}/${r.appName}/sdk/user/${r.encodedUserId}/blocks?resource=${r.encodedResource}`,n=await e.post(a,{usernames:s},{operation:"addUsersToBlocklist"});return{succeeded:C(n).map(e=>({userId:e})),failed:[]}},_={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 O=!1,T=null;const U=()=>T||(O||(a.lightExports.util.Long=r.Long,a.lightExports.configure(),O=!0),r.installReflectionRuntime(),T=a.lightExports.Root.fromJSON(_),r.installReflectionCodecInNamespace(T),T),w=e=>"number"==typeof e?e:r.Long.isLong(e)?e.toNumber():0,b=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:w(t.timestamp),requestId:"string"==typeof t.requestId?t.requestId:"",protocolVersion:w(t.protocolVersion)}};class N{encodeRequest(e){const t=U().lookupType("easemob.imfusion.gateway.v1.GetRosterRequest");return t.encode(t.create(e)).finish()}encodePong(e=l){const t=U().lookupType("easemob.imfusion.gateway.v1.PongResponse");return t.encode(t.create({type:d.PONG,status:e})).finish()}decode(e){const t=U(),s=t.lookupType("easemob.imfusion.gateway.v1.BaseMessage").decode(e);switch(s.type){case d.PING:return{type:d.PING};case d.PONG:{const s=t.lookupType("easemob.imfusion.gateway.v1.PongResponse").decode(e);return{type:d.PONG,status:w(s.status)}}case d.RESPONSE:{const s=t.lookupType("easemob.imfusion.gateway.v1.GetRosterResponse").decode(e);return{type:d.RESPONSE,header:b(s.header),data:Array.isArray(s.data)?s.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:w(t.createdAt),updatedAt:w(t.updatedAt),metadataUpdatedAt:w(t.metadataUpdatedAt)}})(e)):[],cursor:w(s.cursor),version:"string"==typeof s.version?s.version:"",responseType:w(s.responseType)||u}}case d.ERROR:{const s=t.lookupType("easemob.imfusion.gateway.v1.ErrorDetail").decode(e);return{type:d.ERROR,header:b(s.header),code:"string"==typeof s.code?s.code:"",message:"string"==typeof s.message?s.message:"Unknown roster error"}}default:return{type:"number"==typeof s.type?s.type:d.UNSPECIFIED}}}}class k{constructor(e){this.pages=[],this.responseType=null,this.version="",this.nextCursor=0,this.pageCount=0,this.completed=!1,this.requestId=e}push(t){const s=t.header?.requestId;if(s&&s!==this.requestId)throw new e.SDKError("Roster response requestId mismatched",e.ERROR_CODES.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",expectedRequestId:this.requestId,receivedRequestId:s}});if(this.completed)throw new e.SDKError("Roster response received after completion",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:t.cursor}});if(null!==this.responseType&&this.responseType!==t.responseType)throw new e.SDKError("Roster response type changed in same session",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{expected:this.responseType,received:t.responseType}});if(this.pages.length>0&&0!==t.cursor&&t.cursor===this.pages[this.pages.length-1]?.cursor)throw new e.SDKError("Roster cursor duplicated",e.ERROR_CODES.CONTACT_SYNC_CURSOR_INVALID,{details:{cursor:t.cursor}});return this.responseType=t.responseType,this.version=t.version||this.version,this.pages.push(t),this.nextCursor=t.cursor,this.pageCount+=1,this.completed=0===t.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===h?"incremental":"full",version:this.version,pages:this.pages}}}const A=e=>e.type===d.RESPONSE,D=e=>"message"in e&&"code"in e;class M{constructor(e){this.codec=new N,this.sharedSession=e}async sync(e){const t=new k(e.request.header.requestId);return await this.syncWithSharedSession(e.request,t)}cancel(){this.sharedSession.cancel("contact-sync-cancelled")}async syncWithSharedSession(t,s){return await this.sharedSession.request({dataType:"contact",label:"Roster sync",requestId:t.header.requestId,encode:()=>{const e=this.buildAttemptRequest(t,s.getNextCursor());return this.codec.encodeRequest(e)},decode:e=>{const t=this.codec.decode(e);return{type:t.type,requestId:A(t)||D(t)?t.header?.requestId:void 0,frame:t}},onFrame:async(t,r)=>{try{if(t.type===d.PING)return void(await r.send(this.codec.encodePong()));if(A(t)){if(!s.push(t).done)return;return{done:!0,result:s.buildResult()}}if(D(t))throw(t=>{const s=t.header?.requestId,r=e=>({stage:"sync_page",serverCode:t.code,requestId:s,retryable:e});switch(Number.parseInt(t.code,10)){case g:return new e.AuthenticationError(t.message,{code:e.ERROR_CODES.AUTH_UNAUTHORIZED,details:r(!1)});case m:return new e.SDKError(t.message,e.ERROR_CODES.SERVICE_LIMIT_EXCEEDED,{details:r(!0)});case p:return new e.SDKError(t.message,e.ERROR_CODES.VALIDATION_REQUIRED,{details:r(!1)});case y:return new e.SDKError(t.message,e.ERROR_CODES.VALIDATION_INVALID_FORMAT,{details:r(!1)});case R:return new e.SDKError(t.message,e.ERROR_CODES.REST_BUSINESS_UNKNOWN,{details:r(!0)});case I:return new e.SDKError(t.message,e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:r(!1)});default:return new e.SDKError(t.message,e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:r(!0)})}})(t);return}catch(a){throw a instanceof e.SDKError?a:new e.SDKError("Roster frame decode failed",e.ERROR_CODES.CONTACT_SYNC_PROTO_DECODE_FAILED,{details:{stage:"response_decode",cause:a instanceof Error?a.message:String(a)}})}}})}buildAttemptRequest(e,t){return{...e,cursor:t,header:{...e.header,timestamp:Date.now(),requestId:e.header.requestId}}}}const q=e=>e.versionState.version?"incremental":"full",P=e=>{const{metadata:t,metadataFailed:s,state:r}=e,a=r.versionState.version;return s||!t?{decision:"complete"===r.cacheMeta.cacheIntegrity?q(r):"full",version:a}:t.requiresSync||"complete"!==r.cacheMeta.cacheIntegrity?t.requiresSync&&"complete"===r.cacheMeta.cacheIntegrity&&a?{decision:"incremental",version:t.version||a}:{decision:"full",version:t.version||a}:{decision:"skip",version:t.version||a}},$=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{}}},B=t=>{const s=(t=>{if(!(t instanceof e.SDKError&&t.details))return null;const s=t.details.httpStatus;return"number"==typeof s?s:null})(t);return 401===s||403===s||404===s},F=(e,t,s,r)=>({code:t,stage:e,message:`${e}: ${s}`,retryable:r}),x=t=>{e.logger.warn("Contact sync duration",t)};class L{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 t=this.dependencies.getContextState(),s=Date.now();let r;this.dependencies.onStart();try{const e=await this.dependencies.queryMetadata(t.versionState.version);if(r=P({metadata:e,state:t}),"skip"===r.decision)return this.dependencies.onFinish(),void x({outcome:"skip",decision:r.decision,durationMs:Date.now()-s,version:r.version,hasUsableSnapshot:t.cachedSnapshot.complete})}catch(a){if(B(a)){const r=P({metadataFailed:!0,state:t}),n=a instanceof e.SDKError?a:new e.SDKError("Contact metadata request failed",e.ERROR_CODES.CONTACT_SYNC_METADATA_FAILED,{details:{stage:"metadata"}});return this.dependencies.onFinish({error:F("metadata",n.code,n.message,!1)}),void x({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:t.versionState.version,stage:"metadata",hasUsableSnapshot:t.cachedSnapshot.complete,source:t.cachedSnapshot.complete?t.cachedSnapshot.source:void 0})}if(r=P({metadataFailed:!0,state:t}),t.cachedSnapshot.complete)return this.dependencies.onFinish({error:F("metadata",e.ERROR_CODES.CONTACT_SYNC_METADATA_FAILED,a instanceof Error?a.message:String(a),!0)}),void x({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:r.version,stage:"metadata",hasUsableSnapshot:!0,source:t.cachedSnapshot.source})}try{const e=await this.dependencies.getSyncUrls(),a=this.dependencies.buildRosterRequest({decision:r.decision,version:t.versionState.version}),n=await new M(this.dependencies.getSharedSyncSession()).sync({urls:e,request:a}),o=(e=>{const t=[];for(const s of e)for(const e of s.data){const s=$(e.metadata);t.push({relation:{userId:e.contact,remark:e.remark,sign:s.sign??"",addTs:e.createdAt,updatedAt:e.updatedAt,metadataUpdatedAt:e.metadataUpdatedAt},userInfo:{userId:e.contact,nickname:s.nickname,avatarUrl:s.avatarUrl,sign:s.sign,ext:s.ext}})}return t})(n.pages),i=this.dependencies.applySyncResult({mode:n.mode,relations:o.map(e=>e.relation),userInfos:o.map(e=>e.userInfo),version:n.version,lastSyncTs:Date.now()});this.dependencies.onFinish(),x({outcome:"finish",decision:r.decision,durationMs:Date.now()-s,version:n.version,source:"sync",changed:i.changed,hasUsableSnapshot:i.snapshot.complete})}catch(a){const n=a instanceof e.SDKError?a:new e.SDKError("Contact sync failed",e.ERROR_CODES.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"sync_page",cause:a instanceof Error?a.message:String(a)}}),o=n.details??{},i="string"==typeof o.stage?o.stage:"sync_page";this.dependencies.onFinish({error:F(i,n.code,n.message,!0)}),x({outcome:"fail",decision:r.decision,durationMs:Date.now()-s,version:r.version,stage:i,hasUsableSnapshot:t.cachedSnapshot.complete,source:t.cachedSnapshot.complete?t.cachedSnapshot.source:void 0})}}}const K={items:[],loaded:!1,source:"server"},V=e.mergeRuntimeErrorMaps(e.COMMON_ERROR_MAP,{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:{}}}}),G=class{constructor(){this.client=null,this.eventContext=null,this.restClient=null,this.restBaseUrl=null,this.restToken=null,this.blocklistSnapshot=K,this.blocklistSessionKey=null}bind(e,t){this.client=e,this.eventContext=t??null,this.blocklistSnapshot=K,this.blocklistSessionKey=null}getContacts(){return this.client?.getContactSnapshot()?.items??[]}async addContact(t){return this.runOperation("addContact",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.validateOptionalString(t.message,"params.message"),a=this.getRestContextOrThrow(),n=this.getRestClient(a);e.logger.debug("ContactManager addContact",{userId:s,hasMessage:"string"==typeof r&&r.length>0}),await(async(e,t,s)=>{const r=E(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/apply?resource=${r.encodedResource}`;await e.post(a,{usernames:[s.userId],reason:s.message??""},{operation:"addContact"})})(n,a,{userId:s,message:r})})}async deleteContact(t){return this.runOperation("deleteContact",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);e.logger.debug("ContactManager deleteContact",{userId:s}),await(async(e,t,s)=>{const r=E(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.delete(a,{operation:"deleteContact"})})(a,r,{userId:s});const n=this.client?.getCacheManager()?.removeContact(s);e.logger.debug("ContactManager deleteContact patched cache",{userId:s,changed:n?.changed??!1})})}async acceptContactInvite(t){return this.runOperation("acceptContactInvite",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);e.logger.debug("ContactManager acceptContactInvite",{userId:s}),await(async(e,t,s)=>{const r=E(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/accept/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.post(a,void 0,{operation:"acceptContactInvite"})})(a,r,{userId:s}),await this.requireClient().refreshContactSnapshot()})}async declineContactInvite(t){return this.runOperation("declineContactInvite",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.getRestContextOrThrow(),a=this.getRestClient(r);e.logger.debug("ContactManager declineContactInvite",{userId:s}),await(async(e,t,s)=>{const r=E(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/decline/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.post(a,void 0,{operation:"declineContactInvite"})})(a,r,{userId:s})})}async setContactRemark(t){return this.runOperation("setContactRemark",async()=>{const s=this.validateUserId(t.userId,"params.userId"),r=this.validateRemark(t.remark,"params.remark"),a=this.getRestContextOrThrow(),n=this.getRestClient(a);e.logger.debug("ContactManager setContactRemark",{userId:s,remarkLength:r.length}),await(async(e,t,s)=>{const r=E(t),a=`/${r.orgName}/${r.appName}/users/${r.encodedUserId}/contacts/users/${encodeURIComponent(s.userId)}?resource=${r.encodedResource}`;await e.put(a,{remark:s.remark},{operation:"setContactRemark"})})(n,a,{userId:s,remark:r});const o=this.client?.getCacheManager()?.updateContactRemark(s,r);this.client?.refreshConversationDisplayFromUserInfos([{userId:s}],"profile"),e.logger.debug("ContactManager setContactRemark patched cache",{userId:s,changed:o?.changed??!1})})}async getBlocklist(){return this.runOperation("getBlocklist",async()=>{const t=this.getRestContextOrThrow();this.ensureBlocklistSession(t);const s=this.getRestClient(t);if(this.blocklistSnapshot.loaded)return this.blocklistSnapshot.items;const r=await this.enrichBlocklistUsers(await f(s,t));return this.blocklistSnapshot={items:r,loaded:!0,source:"server"},e.logger.debug("ContactManager getBlocklist",{count:r.length}),r})}async addUsersToBlocklist(t){return this.runOperation("addUsersToBlocklist",async()=>{const s=this.getRestContextOrThrow();this.ensureBlocklistSession(s);const r=S(t,"params.userIds"),a=this.getRestClient(s);e.logger.debug("ContactManager addUsersToBlocklist",{userIds:r,inputCount:t.userIds.length,normalizedCount:r.length});const n=await v(a,s,r),o=await this.enrichBlocklistUsers(n.succeeded);return this.blocklistSnapshot=this.patchBlocklistSnapshotWithAdditions(o),{succeeded:o,failed:await this.enrichBlocklistUsers(n.failed)}})}async removeUserFromBlocklist(t){return this.runOperation("removeUserFromBlocklist",async()=>{const s=this.getRestContextOrThrow();this.ensureBlocklistSession(s);const r=S(t,"params.userIds"),a=this.getRestClient(s);e.logger.debug("ContactManager removeUserFromBlocklist",{userIds:r,inputCount:t.userIds.length,normalizedCount:r.length}),await(async(e,t,s)=>{const r=E(t),a=`/${r.orgName}/${r.appName}/sdk/user/${r.encodedUserId}/blocks?resource=${r.encodedResource}`;await e.request(a,{method:"DELETE",body:{usernames:s},operation:"removeUserFromBlocklist"})})(a,s,r),this.blocklistSnapshot=this.patchBlocklistSnapshotWithRemovals(r)})}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async runOperation(t,s){try{return await s()}catch(r){const s=this.normalizeSdkError(t,r);throw e.logger.warn(`ContactManager ${t} failed`,{code:s.code,message:s.message,details:s.details}),s}}normalizeSdkError(t,s){return s instanceof e.SDKError?s:s instanceof Error?new e.SDKError(`ContactManager ${t} failed: ${s.message}`,e.ERROR_CODES.UNKNOWN):new e.SDKError(`ContactManager ${t} failed`,e.ERROR_CODES.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(t){return this.restClient&&this.restBaseUrl===t.restBaseUrl&&this.restToken===t.token||(this.restClient=new e.RestClient(t.restBaseUrl,{errorMap:V,requestAdapter:this.requireClient().getRequestAdapter?.(),includeRequestId:!0}),this.restClient.setAuthToken(t.token),this.restBaseUrl=t.restBaseUrl,this.restToken=t.token),this.restClient}ensureBlocklistSession(e){const t=`${e.restBaseUrl}:${e.userId}:${e.token}`;this.blocklistSessionKey!==t&&(this.blocklistSessionKey=t,this.blocklistSnapshot=K)}patchBlocklistSnapshotWithAdditions(e){const t=new Map(this.blocklistSnapshot.items.map(e=>[e.userId,e]));for(const s of e)t.set(s.userId,s);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 s of e)t.delete(s);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 s=e.trim();if(!s)throw this.buildValidationError("userId is required",[{path:t,message:"userId is required",rule:"required"}]);return s}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(t,s){const r=s.some(e=>"invalid_format"===e.rule)?e.ERROR_CODES.VALIDATION_INVALID_FORMAT:e.ERROR_CODES.VALIDATION_REQUIRED;return new e.ValidationError(t,{code:r,details:{fields:s}})}async enrichBlocklistUsers(e){if(0===e.length||!this.requireClient().isUserInfoSyncEnabled())return e;const t=await c(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(t){if(0===t.length)return[];try{const e=this.getUserInfoManager();return e?await e.getUserInfoByUserId({userIds:t}):await this.fetchUserInfosFromRest(t)}catch(s){return e.logger.warn("ContactManager user info fetch failed",{userIds:t,error:s}),[]}}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=s.buildFetchUserInfoByUserIdRequest(e),a=await this.getRestClient(t).request(s.buildUserInfoFetchEndpoint(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return s.normalizeFetchedUserInfos(a,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 L(e)}};G.key="contactManager";let Y=G;exports.ContactManager=Y,exports.RosterMessageType=d,exports.resolveSingleContactUserInfo=async(e,t)=>((e,t,s)=>({userId:s,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 c([e],t)).get(e),e);
@@ -1 +0,0 @@
1
- import{i as e}from"./cache-utils-B99glc0H.js";import{p as t,V as r,E as o,S as s,A as n,_ as a,l as i,n as u,v as p,ar as d,b as c,e as m,as as l,f as h,m as g,i as I}from"./common-D_DfwSd3.js";import{a as y}from"./profile-version-DLMz8lqW.js";import{m as f,g as _,r as w,b as G}from"./group-user-info-resolver-lEtRdWli.js";import{G as b}from"./event-system-D6IJA0C4.js";import{c as v}from"./query-params-Bu3Xq4b6.js";import{b as R,a as S,n as A}from"./user-info-DfbCp80h.js";import{l as U}from"./light-Dg9A1Xmd.js";import{L as E,a as C,b as O}from"./reflection-proto-codec-CjRraw85.js";const T=["nickname","avatarUrl","mail","phone","gender","sign","birth","ext"],M=e=>({userId:e.userId,nickname:e.nickname,avatarUrl:e.avatarUrl,sign:e.sign,ext:e.ext}),D=e=>({userId:e}),N=(e,t,r)=>{const o={userId:r};for(const s of T){const r=t?.[s]??e?.[s];void 0!==r&&(o[s]=r)}return o},L=async(e,t)=>{const r=(e=>{const t=[],r=/* @__PURE__ */new Set;for(const o of e){const e=o.trim();e&&!r.has(e)&&(r.add(e),t.push(e))}return t})(e),o=/* @__PURE__ */new Map;if(0===r.length)return o;const s=t.cacheManager?.getUserInfoSummaries(r,!1)??[];for(const a of s)o.set(a.userId,M(a));const n=r.filter(e=>!o.has(e));if(n.length>0&&t.fetchUserInfos){const e=await t.fetchUserInfos({userIds:n});for(const t of e)o.set(t.userId,t)}for(const a of r)o.has(a)||o.set(a,D(a));return o},F=t=>e(t)?t:null,P=e=>{if("string"==typeof e)return e},$=e=>{const t=P(e)?.trim();return t||void 0},j=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}},x=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){if("true"===e)return!0;if("false"===e)return!1}},k=e=>{const t=F(e);return t&&Array.isArray(t.data)?t.data:t&&Array.isArray(t.entities)?t.entities:Array.isArray(e)?e:[]},J=e=>{const t=F(e);return t?F(t.data)?t.data:t:null},q=(e,t)=>{const r=F(e),o=r&&F(r.params),s=o?.[t];if(Array.isArray(s)&&0!==s.length)return j(s[0])},B=(e,t)=>{const r=(e=>{const t=F(e);return t?j(t.count):void 0})(e);if(void 0!==r&&void 0!==t)return r>=t},H=e=>$(e.groupId)??$(e.groupid)??$(e.id)??"",V=e=>P(e.name)??P(e.groupname)??P(e.groupName)??"",K=e=>{const t=k(e),r=F(t[0])??J(e)??{},o=(e=>{const t=F(e);if(!t)return null;const r=H(t);return r?{groupId:r,name:V(t),description:P(t.description),memberCount:j(t.memberCount)??j(t.affiliations_count),public:x(t.public),joinApprovalRequired:x(t.joinApprovalRequired)??x(t.approval)??x(t.membersonly)??x(t.members_only),allowInvites:x(t.allowInvites)??x(t.allowinvites)??x(t.allow_user_invites),maxMembers:j(t.maxMembers)??j(t.maxusers),role:$(t.role)??$(t.permission),disabled:x(t.disabled)}:null})(r)??{groupId:H(r),name:V(r)},s=$(r.owner)??$(r.admin)??$(r.member),n=(Array.isArray(r.affiliations)?r.affiliations:[]).map(e=>F(e)).filter(e=>null!==e).map(e=>j(e.joined_time)).find(e=>void 0!==e);return{...o,owner:s?D(s):void 0,inviteNeedConfirm:x(r.inviteNeedConfirm)??x(r.invite_need_confirm),muteAllMembers:x(r.mute),ext:P(r.ext)??P(r.custom),createdAt:j(r.createdAt)??j(r.created),joinedAt:n,avatarUrl:P(r.avatar),messageBlocked:x(r.messageBlocked)??x(r.isMessageBlocked)??x(r.shieldgroup)}},z=e=>D(e),W=e=>k(e).map(e=>$(e)).filter(e=>Boolean(e)).map(e=>z(e)),Q=e=>{const t=F(e);if(!t)return null;const r=$(t.fileId)??$(t.file_id);if(!r)return null;const o=P(t.fileName)??P(t.file_name)??r,s=$(t.fileOwner)??$(t.file_owner);return{fileId:r,fileName:o,fileOwner:s?z(s):void 0,fileSize:j(t.fileSize)??j(t.file_size),createdAt:j(t.createdAt)??j(t.created)}},Y=100,X=3e3,Z=e=>({...e}),ee=e=>"object"==typeof e&&null!==e,te=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 re{constructor(){this.items=[],this.meta={integrity:"unknown",limited:!1,storageLimit:Y,serverLimit:X,source:"localPreview"}}load(e){if(!e)return this.items=[],void(this.meta={integrity:"unknown",limited:!1,storageLimit:Y,serverLimit:X,source:"localPreview"});const t=Array.isArray(e.items)?e.items.map(e=>{return ee(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:te(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,Y),this.meta=(e=>{const t=ee(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:Y,serverLimit:"number"==typeof t.serverLimit?t.serverLimit:X,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=>Z(e)).slice(0,Y),this.meta={...e.meta,source:"localPreview",storageLimit:Y,serverLimit:X,integrity:e.meta.limited?"limited":e.meta.integrity}}getSnapshot(){return{items:this.items.map(e=>Z(e)),meta:{...this.meta,source:"localPreview"}}}exportRecord(){return{items:this.items.map(e=>Z(e)),meta:{...this.meta,source:"localPreview"}}}}class oe{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 se=e=>{const{orgName:r,appName:o}=t(e.appKey);return{orgName:r,appName:o,encodedUserId:encodeURIComponent(e.userId),encodedResource:encodeURIComponent(e.clientResource)}},ne=e=>new r(`${e} is required`,{code:o.VALIDATION_REQUIRED,details:{fields:[{path:e,message:`${e} is required`,rule:"required"}]}}),ae=(e,t)=>new r(t,{code:o.VALIDATION_INVALID_FORMAT,details:{fields:[{path:e,message:t,rule:"invalid_format"}]}}),ie=(e,t)=>{if(!Array.isArray(e)||0===e.length)throw ne(t);const r=[],o=/* @__PURE__ */new Set;if(e.forEach((e,s)=>{if("string"!=typeof e)throw ae(`${t}[${s}]`,`${t}[${s}] must be a string`);const n=e.trim();n&&!o.has(n)&&(o.add(n),r.push(n))}),0===r.length)throw ne(t);return r},ue=(e,t)=>{if("string"!=typeof e||0===e.trim().length)throw ne(t);return e.trim()},pe=(e,t)=>{if(void 0!==e){if("string"!=typeof e)throw ae(t,`${t} must be a string`);return e}},de=(e,t)=>{if(void 0!==e){if("boolean"!=typeof e)throw ae(t,`${t} must be a boolean`);return e}},ce=(e,t)=>`/${e.orgName}/${e.appName}${t}`,me=/* @__PURE__ */new Set(["groupNamecard","group_namecard","group_name_card","namecard","nameCard"]),le=e=>{const t=v();"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}`:""},he=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups?resource=${o.encodedResource}`);return(e=>{const t=k(e),r=F(t[0]),o=J(e)??r;return{groupId:o&&H(o)||r&&H(r)||""}})(await e.post(s,{owner:t.userId,groupname:r.name,desc:r.description,members:r.memberIds?ie(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"}))},ge=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=ce(o,`/chatgroups/${encodeURIComponent(s)}?joined_time=true&version=v3`),a=await e.get(n,{operation:"getGroupInfo"});return K(a)},Ie=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n={},a=pe(r.name,"params.name"),i=pe(r.description,"params.description"),u=pe(r.avatar,"params.avatar"),p=pe(r.ext,"params.ext"),d=de(r.public,"params.public"),c=de(r.joinApprovalRequired,"params.joinApprovalRequired"),m=de(r.allowInvites,"params.allowInvites"),l=de(r.inviteNeedConfirm,"params.inviteNeedConfirm"),h=((e,t)=>{if(void 0!==e){if("number"!=typeof e||Number.isNaN(e))throw ae(t,`${t} must be a number`);return e}})(r.maxMembers,"params.maxMembers");if(void 0!==a&&(n.groupname=a),void 0!==i&&(n.description=i),void 0!==u&&(n.avatar=u),void 0!==p&&(n.custom=p),void 0!==d&&(n.public=d),void 0!==c&&(n.membersonly=c),void 0!==m&&(n.allowinvites=m),void 0!==l&&(n.invite_need_confirm=l),void 0!==h&&(n.maxusers=h),0===Object.keys(n).length)throw ne("params");const g=ce(o,`/chatgroups/${encodeURIComponent(s)}?resource=${o.encodedResource}&version=v3`);await e.put(g,n,{operation:"updateGroupInfo"})},ye=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/users${(e=>{const t=v();return"number"==typeof e?.pageSize&&t.set("pagesize",String(e.pageSize)),"string"==typeof e?.cursor&&e.cursor.length>0&&t.set("cursor",e.cursor),t.set("version","v3"),`?${t.toString()}`})(r)}`);return(e=>{const t=[];for(const n of k(e)){const e=F(n);if(!e)continue;const r=$(e.owner),o=$(e.admin),s=$(e.member),a=r??o??s;if(!a)continue;const i=j(e.joinedAt)??j(e.joined_time);t.push({user:z(a),role:r?"owner":o?"admin":"member",...void 0===i?{}:{joinedAt:i}})}const r=q(e,"pagenum"),o=q(e,"pagesize"),s=B(e,o);return{items:t,pageNum:r,pageSize:o,...void 0===s?{}:{hasMore:s}}})(await e.get(s,{operation:"getGroupMemberList"}))},fe=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/admin`),n=await e.get(s,{operation:"getGroupAdminList"});return W(n)},_e=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=le(r),a=n?"&":"",i=ce(o,`/chatgroups/${encodeURIComponent(s)}/mute?version=v3${a}${n.replace("?","")}`);return(e=>{const t=[];for(const r of k(e)){const e=$(r);if(e){t.push({user:z(e)});continue}const o=F(r);if(!o)continue;const s=$(o.user);if(!s)continue;const n=j(o.expire);t.push({user:z(s),...void 0===n?{}:{muteExpire:n}})}return t})(await e.get(i,{operation:"getGroupMuteList"}))},we=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=le(r),a=n?"&":"",i=ce(o,`/chatgroups/${encodeURIComponent(s)}/blocks/users?version=v3${a}${n.replace("?","")}`),u=await e.get(i,{operation:"getGroupBlocklist"});return W(u).map(e=>({user:e}))},Ge=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/white/users`),n=await e.get(s,{operation:"getGroupAllowlist"});return W(n).map(e=>({user:e}))},be=async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/announcement`);return(e=>{const t=J(e)??{};return{announcement:P(t.announcement)??""}})(await e.get(s,{operation:"getGroupAnnouncement"}))},ve=async(e,t,r)=>{const o=se(t),s=v();s.set("pagenum",String(r.pageNum??1)),s.set("pagesize",String(r.pageSize??20));const n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/share_files?${s.toString()}`);return(e=>{const t=q(e,"pagenum"),r=q(e,"pagesize"),o=B(e,r);return{items:k(e).map(e=>Q(e)).filter(e=>null!==e),pageNum:t,pageSize:r,...void 0===o?{}:{hasMore:o}}})(await e.get(n,{operation:"getGroupSharedFileList"}))},Re=(e,t)=>{const r=se(e);return ce(r,`/chatgroups/${encodeURIComponent(ue(t.groupId,"params.groupId"))}/share_files/${encodeURIComponent(ue(t.fileId,"params.fileId"))}`)},Se=async(e,t,r)=>{const o=se(t),s=ue(r.groupId,"params.groupId"),n=ue(r.userId,"params.userId"),a=((e,t,r)=>{if(t!==e.userId)return null;const o=Object.entries(r);if(0===o.length)return null;let s;for(const[n,a]of o){if(!me.has(n)||"string"!=typeof a)return null;if(void 0!==s){if(s!==a)return null}else s=a}return void 0===s?null:{nameCard:s}})(t,n,r.memberAttributes);if(a){const t=ce(o,`/sdk/chatgroups/${encodeURIComponent(s)}/nameCard`);return await e.put(t,a,{operation:"setGroupMemberAttributes"})}const i=ce(o,`/sdk/metadata/chatgroup/${encodeURIComponent(s)}/user/${encodeURIComponent(n)}?resource=${o.encodedResource}`);return await e.put(i,{metaData:r.memberAttributes},{operation:"setGroupMemberAttributes"})},Ae=async(e,t,r)=>{const o=se(t),s=ce(o,`/sdk/metadata/chatgroup/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/get`);return(e=>{const t=J(e)??{},r=F(t.data)??t,o={};for(const[s,n]of Object.entries(r)){const e=F(n);e&&(o[s]=Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1])))}return{items:o}})(await e.post(s,{targets:ie(r.userIds,"params.userIds"),properties:r.keys??[]},{operation:"getGroupMembersAttributes"}))},Ue=t=>{const r=e(t)?t:{},o=r.data,s=e(o)?o.data:void 0,n=Array.isArray(o)?o:Array.isArray(s)?s:null;if(Array.isArray(n))return Ee(n);const a=e(o)?o:r,i=e(a.namecards)?a.namecards:a,u={};for(const[p,d]of Object.entries(i)){if("string"==typeof d){u[p]={namecard:d};continue}if(!e(d))continue;const t=d.namecard??d.nameCard??d.groupNamecard??d.group_namecard??d.group_name_card;"string"==typeof t&&(u[p]={namecard:t,namecardUpdateTime:Ce(d)})}return u},Ee=t=>{const r={};return t.forEach(t=>{if(!e(t))return;const o=t.username??t.userId??t.userid??t.user_id,s=t.name_card??t.namecard??t.nameCard??t.groupNamecard??t.group_namecard??t.group_name_card;"string"==typeof o&&o.trim()&&"string"==typeof s&&(r[o.trim()]={namecard:s,namecardUpdateTime:Ce(t)})}),r},Ce=e=>y("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),Oe=t=>{if(e(t))return y("number"==typeof t.timestamp?t.timestamp:"number"==typeof t.update_timestamp?t.update_timestamp:"number"==typeof t.updateTimestamp?t.updateTimestamp:"number"==typeof t.lastModified?t.lastModified:"number"==typeof t.last_modified?t.last_modified:void 0)};class Te{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 Me=e=>({...e}),De=e=>({...e,owner:e.owner?{...e.owner}:void 0});class Ne{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=Me({...this.summarySnapshot??{},...e,groupId:this.groupId}),this.loadedSummary=!0,this.lastPatchedAt=Date.now())}mergeDetail(e){e.groupId===this.groupId&&(this.detailSnapshot=De({...this.detailSnapshot??this.summarySnapshot??{groupId:this.groupId,name:""},...e,groupId:this.groupId}),this.summarySnapshot=Me(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?Me(this.summarySnapshot):this.detailSnapshot?Me(this.toSummaryFromDetail(this.detailSnapshot)):null}getDetailSnapshot(){return this.detailSnapshot?De(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 Le{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 Fe{constructor(){this.groups=/* @__PURE__ */new Map,this.joinedGroupById=/* @__PURE__ */new Map,this.removedJoinedGroupIds=/* @__PURE__ */new Set,this.snapshotMapper=new Le,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 Ne(e);return this.groups.set(e,r),r}mergeSummary(e){return this.getOrCreate(e.groupId).mergeSummary(e),this.getSummarySnapshot(e.groupId)??{...e}}mergeSummaries(e){return e.map(e=>this.mergeSummary(e))}applyJoinedGroupSnapshot(e){const t=e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId));this.joinedGroupSnapshot={items:t.map(e=>({...e})),meta:{...e.meta}},this.joinedGroupById.clear();for(const r of t){const e={...r};this.joinedGroupById.set(e.groupId,e),this.mergeSummary(this.toGroupSummary(e))}}getJoinedGroupSnapshot(e){return this.joinedGroupSnapshot?{items:this.joinedGroupSnapshot.items.map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}}:e?{items:e.items.filter(e=>!this.removedJoinedGroupIds.has(e.groupId)).map(e=>({...e})),meta:{...e.meta}}:{items:[],meta:{integrity:"unknown",limited:!1,storageLimit:100,serverLimit:3e3,source:"sync"}}}getJoinedGroupSummarySnapshot(e,t){const r=this.joinedGroupById.get(e);if(r)return{...r};if(this.removedJoinedGroupIds.has(e))return null;const o=t?.items.find(t=>t.groupId===e);return o?{...o}:null}addJoinedGroupIfAbsent(e,t){const r=this.getJoinedGroupSnapshot(t);return r.items.some(t=>t.groupId===e.groupId)?null:(this.removedJoinedGroupIds.delete(e.groupId),this.applyJoinedGroupSnapshot({items:[{...e},...r.items],meta:{...r.meta}}),this.getJoinedGroupSnapshot())}mergeJoinedGroupSummary(e,t){const r=this.joinedGroupById.get(e);if(!r||!this.joinedGroupSnapshot)return null;const o={...r,...t,groupId:e};return this.joinedGroupById.set(e,o),this.mergeSummary(this.toGroupSummary(o)),this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.map(t=>t.groupId===e?{...o}:{...t}),meta:{...this.joinedGroupSnapshot.meta}},this.getJoinedGroupSnapshot()}mergeDetail(e){const t=this.mergeJoinedGroupFieldsIntoDetail(e);return this.getOrCreate(t.groupId).mergeDetail(t),this.getDetailSnapshot(t.groupId)??{...t}}mergeDetails(e){return e.map(e=>this.mergeDetail(e))}getSummarySnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toSummary(t):null}getDetailSnapshot(e){const t=this.groups.get(e);return t?this.snapshotMapper.toDetail(t):null}hasFreshDetail(e){const t=this.groups.get(e);return Boolean(t&&t.hasLoadedDetail()&&!t.isStale())}markStale(e){this.getOrCreate(e).markStale()}delete(e){this.groups.delete(e),this.joinedGroupById.delete(e),this.joinedGroupSnapshot&&(this.joinedGroupSnapshot={items:this.joinedGroupSnapshot.items.filter(t=>t.groupId!==e).map(e=>({...e})),meta:{...this.joinedGroupSnapshot.meta}})}markJoinedGroupRemoved(e){this.removedJoinedGroupIds.add(e),this.delete(e)}clear(){this.groups.clear(),this.joinedGroupById.clear(),this.removedJoinedGroupIds.clear(),this.joinedGroupSnapshot=null}mergeJoinedGroupFieldsIntoDetail(e){const t=this.joinedGroupById.get(e.groupId);return t&&void 0===e.joinedAt&&void 0!==t.joinedAt?{...e,joinedAt:t.joinedAt}:e}toGroupSummary(e){return{groupId:e.groupId,name:e.name,description:e.description,memberCount:e.memberCount,role:e.role,disabled:e.disabled}}}const Pe=0,$e=5,je=12,xe=13,ke=0,Je=1,qe=2,Be=0,He=1,Ve=2,Ke=3,ze=e=>{const t=e.group_id?.trim();return t?{groupId:t,name:e.group_name??"",description:e.description,memberCount:e.members_count,role:(o=e.role,o===ke?"owner":o===Je?"admin":o===qe?"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===Be?"DEFAULT":r===He?"ALL":r===Ve?"AT":r===Ke?"NONE":void 0),createdAt:e.create_at,updatedAt:e.update_at,joinedAt:e.joined_timestamp}:null;var r,o},We=e=>e.updatedAt??0,Qe=(e,t)=>{if(!e)return!0;return We(t)>=We(e)},Ye={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 Xe=null,Ze=!1;const et=()=>Xe||(Ze||(U.util.Long=E,U.configure(),Ze=!0),C(),Xe=U.Root.fromJSON(Ye),O(Xe),Xe),tt=e=>et().lookupType(e),rt=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(E.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}},ot=e=>{if(!e||"object"!=typeof e)return;const t=e;return{resource:"string"==typeof t.resource?t.resource:"",timestamp:rt(t.timestamp)??0,requestId:"string"==typeof t.request_id?t.request_id:"string"==typeof t.requestId?t.requestId:"",protocolVersion:rt(t.protocol_version)??rt(t.protocolVersion)??0}};class st{constructor(){this.requestType=tt("easemob.joinedgroups.GetJoinedGroupsRequest"),this.responseType=tt("easemob.joinedgroups.GetJoinedGroupsResponse"),this.errorType=tt("easemob.joinedgroups.ErrorDetail")}encodeRequest(e){const t=this.requestType.create({type:e.type,header:e.header?{resource:e.header.resource,timestamp:e.header.timestamp,request_id:e.header.requestId,protocol_version:e.header.protocolVersion}:void 0,org:e.org,app:e.app,username:e.username,last_sync_time:e.lastSyncTime??0,cursor:e.cursor});return this.requestType.encode(t).finish()}decode(e){const t=this.tryDecodeError(e);if(t)return t;const r=this.tryDecodeResponse(e);if(r)return r;const o=this.tryDecodeRequest(e);return o||{type:Pe}}tryDecodeRequest(e){try{const t=this.requestType.toObject(this.requestType.decode(e),{longs:String,bytes:Uint8Array}),r=rt(t.type);return r!==je?null:{type:r,header:ot(t.header),org:"string"==typeof t.org?t.org:"",app:"string"==typeof t.app?t.app:"",username:"string"==typeof t.username?t.username:"",lastSyncTime:rt(t.last_sync_time)??rt(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=rt(t.type);return r!==xe?null:{type:r,header:ot(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:rt(t.members_count)??rt(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:rt(t.role),mute_expiration:rt(t.mute_expiration)??rt(t.muteExpiration),remind_type:rt(t.remind_type)??rt(t.remindType),create_at:rt(t.create_at)??rt(t.createAt),update_at:rt(t.update_at)??rt(t.updateAt),joined_timestamp:rt(t.joined_timestamp)??rt(t.joinedTimestamp)}})(e)):[],isLastBatch:!0===t.is_last_batch||!0===t.isLastBatch,lastSyncFinishedTs:rt(t.last_sync_finished_ts)??rt(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=rt(t.type);return r!==$e?null:{type:r,header:ot(t.header),code:rt(t.code)??0,message:"string"==typeof t.message?t.message:"Unknown joined groups sync error"}}catch{return null}}}class nt{constructor(e){this.batches=[],this.done=!1,this.requestId=e}getResumeCursor(){return this.latestCursor}push(e){if(e.type!==xe)return{done:!1};const t=e.header?.requestId;if(t!==this.requestId)return{done:!1};if(this.done)throw new s("Joined groups response received after completion",o.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 s("Joined groups final batch missing lastSyncFinishedTs",o.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 at=e=>e.type===xe,it=e=>e.type===$e;class ut{constructor(e){this.codec=new st,this.sharedSession=e}async sync(e){const t=e.request.header?.requestId??`group-sync-${Date.now()}`,r=new nt(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:at(t)||it(t)?t.header?.requestId:void 0,frame:t}},onFrame:e=>{try{if(at(e)){if(!r.push(e).done)return;return{done:!0,result:r.buildResult()}}if(it(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 s(e.message,o.VALIDATION_REQUIRED,{details:t("request_send",!1)});case 1602:return new s(e.message,o.REST_BUSINESS_UNKNOWN,{details:t("batch_merge",!0)});case 1002:return new n(e.message,{code:o.AUTH_UNAUTHORIZED,details:t("auth",!1)});case 1003:return new s(e.message,o.SERVICE_LIMIT_EXCEEDED,{details:t("server_limit",!0)});default:return new s(e.message,o.REST_BUSINESS_UNKNOWN,{details:t("response_decode",!0)})}})(e);return}catch(t){throw t instanceof s?t:new s("Joined groups frame decode failed",o.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 pt{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 s("Group sync websocket urls are unavailable",o.CONTACT_SYNC_SOCKET_FAILED,{details:{stage:"socket_connect",retryable:!0}});const n=this.buildRequest(),u=await new ut(this.dependencies.getSharedSyncSession()).sync({urls:r,request:n}),p=u.batches.flatMap(e=>(e=>{const t=[];for(const r of e){const e=ze(r);e&&t.push(e)}return t})(e.groups)),d=this.dependencies.getRuntimeSnapshot(),c=(e=>{const t=new Map(e.existingItems.map(e=>[e.groupId,e])),r=/* @__PURE__ */new Map;for(const s of e.incomingItems){const e=r.get(s.groupId)??t.get(s.groupId);Qe(e,s)?r.set(s.groupId,{...e??{},...s,groupId:s.groupId}):e&&r.set(s.groupId,{...e})}const o=r.size>=X;return{items:Array.from(o?e.existingItems.map(e=>({...e})):r.values()).sort((e,t)=>{const r=(t.joinedAt??0)-(e.joinedAt??0);return 0!==r?r:e.groupId.localeCompare(t.groupId)}),meta:{integrity:o?"limited":"synced",limited:o,storageLimit:Y,serverLimit:X,source:"sync",lastSyncFinishedTs:e.lastSyncFinishedTs,lastSuccessfulAt:Date.now()}}})({existingItems:d?.items??[],incomingItems:p,lastSyncFinishedTs:u.lastSyncFinishedTs}),m=this.dependencies.getCacheManager();this.dependencies.applyRuntimeSnapshot(c);const l=this.dependencies.getRuntimeSnapshot()??c;try{await m.commitJoinedGroupPreviewSnapshot(l);const e=this.dependencies.getRuntimeSnapshot();e&&!this.hasSameMembership(l,e)&&await m.commitJoinedGroupPreviewSnapshot(e)}catch(t){throw d&&this.dependencies.applyRuntimeSnapshot(d),new a("Joined-group preview persistence failed",{details:{stage:"preview_persist",cause:t instanceof Error?t.message:String(t)}})}i.warn("Group sync finished",{durationMs:Date.now()-e,itemCount:c.items.length,limited:c.meta.limited}),this.dependencies.onFinish({status:"success"})}catch(t){const r=(e=>{const t=e instanceof s?e:new s("Group sync failed",o.REST_BUSINESS_UNKNOWN,{details:{stage:"socket_connect",cause:e instanceof Error?e.message:String(e)}}),r=t.details??{},n=r.serverCode;return{dataType:"group",code:t.code,stage:(a=r.stage,"config"===a||"socket_connect"===a||"request_send"===a||"response_decode"===a||"batch_merge"===a||"preview_persist"===a||"completion_meta"===a||"auth"===a||"server_limit"===a||"cancelled"===a?a:"socket_connect"),message:t.message,retryable:!0===r.retryable,serverCode:"number"==typeof n||"string"==typeof n?n:void 0};var a})(t);i.warn("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:r,appName:o}=t(e.appKey);return{type:je,header:{resource:e.clientResource,timestamp:Date.now(),requestId:`group-sync-${Date.now()}`,protocolVersion:1},org:r,app:o,username:e.userId,lastSyncTime:0}}}const dt=g(I,{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:{}}}}),ct=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=/* @__PURE__ */new Map,this.groupRepository=null,this.groupEventSync=null}bind(e,t){this.client=e,this.eventContext=t??null,this.groupRegistry.clear(),this.groupRepository=new Fe,this.groupEventSync=new Te(this.groupRepository),this.ensureRepositorySession()}addEventHandler(e,t){this.eventContext?.addEventHandler(e,t)}removeEventHandler(e){this.eventContext?.removeEventHandler(e)}async handleRawNotify(e){if("group"!==e.type)return;const t=e.payload,r=t.eventName,o=await this.buildIncomingEventPayload(r,t);if(!o)return;if(this.eventContext?.dispatch?.(r,o),r!==b.GROUP_MEMBER_ATTRIBUTE_CHANGED)return;if(!("attribute"in o)||!("user"in o))return;const s=this.extractGroupNamecard(o.attribute);if(void 0===s||!o.user?.userId)return;const n=this.client?.getCurrentUserId();o.user.userId!==n&&(this.getCacheManager()?.setGroupNamecards([{groupId:o.groupId,userId:o.user.userId,namecard:s,lastAccess:Date.now(),lastUpdate:Date.now()}]),this.eventContext?.dispatch?.(b.USER_GROUP_NAMECARD_UPDATED,{groupId:o.groupId,userId:o.user.userId,namecard:s}))}async createGroup(e){return this.runOperation("createGroup",async()=>{const t=this.getRestContextOrThrow(),r=await he(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 r("groupId is required",{code:o.VALIDATION_REQUIRED,details:{fields:[{path:"groupId",message:"groupId is required",rule:"required"}]}});const s=this.groupRegistry.get(t);if(s)return s;this.getGroupSummaryForHandle(t),this.getGroupRepository().getOrCreate(t);const n=new oe(t,this);return this.groupRegistry.set(t,n),n}async getGroupInfo(e){return this.runOperation("getGroupInfo",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow(),r=await ge(this.getRestClient(t),t,e),o=await this.hydrateGroupDetailUsers(r);return this.getGroupRepository().mergeDetail(o)})}async getGroupInfoList(t){return this.runOperation("getGroupInfoList",async()=>{this.ensureRepositorySession();const r=this.getRestContextOrThrow(),o=await(async(t,r,o)=>{const s=se(r),n=ie(o.groupIds,"params.groupIds"),a=ce(s,`/chatgroups/${n.map(e=>encodeURIComponent(e)).join(",")}?joined_time=true&version=v3`),i=await t.get(a,{operation:"getGroupInfoList"});return(e(i)&&Array.isArray(i.data)?i.data:[]).map(e=>K({data:[e]}))})(this.getRestClient(r),r,t),s=await this.hydrateGroupDetailsUsers(o);return this.getGroupRepository().mergeDetails(s)})}async getGroupDetailForHandle(e){this.ensureRepositorySession();const t=this.getGroupRepository();if(t.getOrCreate(e),t.hasFreshDetail(e)){const r=t.getDetailSnapshot(e);if(r)return r}return this.getGroupInfo({groupId:e})}async refreshGroupDetailForHandle(e){return this.ensureRepositorySession(),this.getGroupRepository().getOrCreate(e),this.getGroupInfo({groupId:e})}resetSessionRuntime(){this.groupRegistry.clear(),this.getGroupRepository().ensureSession(null)}async buildIncomingEventPayload(e,t){this.ensureRepositorySession();const r=t.payload,o=e===b.GROUP_DESTROYED?this.resolveLocalGroupName(r.groupId):void 0,s=await this.resolveUserInfoMap(this.collectEventUserIds(t));switch(await this.syncRuntimeForEvent(e,r,s),e){case b.INVITATION_RECEIVED:return{groupId:r.groupId,groupName:r.groupName,inviter:this.pickEventUser(r.inviterId,s),reason:r.reason};case b.REQUEST_TO_JOIN_RECEIVED:return{groupId:r.groupId,groupName:r.groupName,applicant:this.pickEventUser(r.applicantId,s),reason:r.reason};case b.REQUEST_TO_JOIN_ACCEPTED:return{groupId:r.groupId,groupName:r.groupName,accepter:this.pickEventUser(r.accepterId,s)};case b.REQUEST_TO_JOIN_DECLINED:return{groupId:r.groupId,groupName:r.groupName,decliner:this.pickEventUser(r.declinerId,s),applicant:this.pickEventUser(r.applicantId,s),reason:r.reason};case b.INVITATION_ACCEPTED:case b.INVITATION_DECLINED:return{groupId:r.groupId,invitee:this.pickEventUser(r.inviteeId,s),reason:r.reason};case b.USER_REMOVED:return{groupId:r.groupId,groupName:r.groupName};case b.GROUP_DESTROYED:return{groupId:r.groupId,groupName:r.groupName??o};case b.AUTO_ACCEPT_INVITATION:return{groupId:r.groupId,inviter:this.pickEventUser(r.inviterId,s),inviteMessage:r.reason};case b.MUTE_LIST_ADDED:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,s),muteExpire:r.muteExpire};case b.MUTE_LIST_REMOVED:return{groupId:r.groupId,mutes:this.pickEventUsers(r.userIds,s)};case b.ALLOW_LIST_ADDED:case b.ALLOW_LIST_REMOVED:return{groupId:r.groupId,allowlist:this.pickEventUsers(r.userIds,s)};case b.ALL_MEMBER_MUTE_STATE_CHANGED:return{groupId:r.groupId,isMuted:Boolean(r.isMuted)};case b.ADMIN_ADDED:case b.ADMIN_REMOVED:return{groupId:r.groupId,administrator:this.pickEventUser(r.administratorId,s)};case b.OWNER_CHANGED:return{groupId:r.groupId,newOwner:this.pickEventUser(r.newOwnerId,s),oldOwner:this.pickEventUser(r.oldOwnerId,s)};case b.MEMBERS_JOINED:return{groupId:r.groupId,groupName:await this.resolveMembersJoinedGroupName(r),members:this.pickEventUsers(r.memberIds,s)};case b.MEMBERS_EXITED:return{groupId:r.groupId,members:this.pickEventUsers(r.memberIds,s)};case b.ANNOUNCEMENT_CHANGED:return{groupId:r.groupId,announcement:r.announcement??""};case b.SHARED_FILE_ADDED:return{groupId:r.groupId,sharedFile:this.hydrateEventSharedFile(r.sharedFile,s)};case b.SHARED_FILE_DELETED:return{groupId:r.groupId,fileId:r.fileId??""};case b.GROUP_INFO_CHANGED:return{groupId:r.groupId,groupInfo:await this.resolveGroupDetailForEvent(r)};case b.GROUP_DISABLED_CHANGED:{const e=await this.resolveGroupDetailForEvent(r),t=void 0===r.isDisabled?Boolean(e.disabled):Boolean(r.isDisabled);return{groupId:r.groupId,groupInfo:e,disabled:t}}case b.GROUP_MEMBER_ATTRIBUTE_CHANGED:return{groupId:r.groupId,user:this.pickEventUser(r.userId,s),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(s){i.warn("GroupManager resolveGroupDetailForEvent fallback to snapshot",{groupId:e.groupId,error:s})}if(r)return r;const o=this.getGroupRepository().getDetailSnapshot(e.groupId);return o||{groupId:e.groupId,name:t?.name??e.groupName??"",...t??{}}}async updateGroupInfo(e){return this.runOperation("updateGroupInfo",async()=>{const t=this.getRestContextOrThrow();await Ie(this.getRestClient(t),t,e)})}async changeGroupOwner(e){return this.runOperation("changeGroupOwner",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}?resource=${o.encodedResource}`);await e.put(s,{newowner:ue(r.newOwner,"params.newOwner")},{operation:"changeGroupOwner"})})(this.getRestClient(t),t,e)})}async destroyGroup(e){return this.runOperation("destroyGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}?version=v3&resource=${o.encodedResource}`);await e.delete(s,{operation:"destroyGroup"})})(this.getRestClient(t),t,e),await this.requireClient().handleGroupDestroyedConversation(e.groupId),await this.removeJoinedGroupLocal(e.groupId)})}async leaveGroup(e){return this.runOperation("leaveGroup",async()=>{this.ensureRepositorySession();const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/quit?resource=${o.encodedResource}`);await e.delete(s,{operation:"leaveGroup"})})(this.getRestClient(t),t,e),await this.removeJoinedGroupLocal(e.groupId)})}async joinGroup(e){return this.runOperation("joinGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/apply?resource=${o.encodedResource}`);await e.post(s,{message:r.message??""},{operation:"joinGroup"})})(this.getRestClient(t),t,e)})}async inviteUsersToGroup(e){return this.runOperation("inviteUsersToGroup",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/invite?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds")},{operation:"inviteUsersToGroup"})})(this.getRestClient(t),t,e)})}async acceptGroupJoinRequest(e){return this.runOperation("acceptGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/apply_verify?resource=${o.encodedResource}`);await e.post(s,{applicant:ue(r.userId,"params.userId"),verifyResult:!0},{operation:"acceptGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async rejectGroupJoinRequest(e){return this.runOperation("rejectGroupJoinRequest",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/apply_verify?resource=${o.encodedResource}`);await e.post(s,{applicant:ue(r.userId,"params.userId"),verifyResult:!1,reason:r.reason},{operation:"rejectGroupJoinRequest"})})(this.getRestClient(t),t,e)})}async acceptInvitation(e){return this.runOperation("acceptInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/invite_verify?resource=${o.encodedResource}`);await e.post(s,{invitee:t.userId,verifyResult:!0},{operation:"acceptInvitation"})})(this.getRestClient(t),t,e)})}async rejectInvitation(e){return this.runOperation("rejectInvitation",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/invite_verify?resource=${o.encodedResource}`);await e.post(s,{invitee:t.userId,verifyResult:!1},{operation:"rejectInvitation"})})(this.getRestClient(t),t,e)})}async getGroupMemberList(e){return this.runOperation("getGroupMemberList",async()=>{const t=this.getRestContextOrThrow(),r=await ye(this.getRestClient(t),t,e);return{...r,items:await this.hydrateEntriesWithUsers(e.groupId,r.items)}})}async removeGroupMembers(e){return this.runOperation("removeGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAdminList(e){return this.runOperation("getGroupAdminList",async()=>{const t=this.getRestContextOrThrow(),r=await fe(this.getRestClient(t),t,e);return this.hydrateUserInfos(e.groupId,r)})}async addGroupAdmin(e){return this.runOperation("addGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/admin?resource=${o.encodedResource}`);await e.post(s,{newadmin:r.userId},{operation:"addGroupAdmin"})})(this.getRestClient(t),t,e)})}async removeGroupAdmin(e){return this.runOperation("removeGroupAdmin",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/admin/${encodeURIComponent(r.userId)}?resource=${o.encodedResource}`);await e.delete(s,{operation:"removeGroupAdmin"})})(this.getRestClient(t),t,e)})}async getGroupMuteList(e){return this.runOperation("getGroupMuteList",async()=>{const t=this.getRestContextOrThrow(),r=await _e(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async muteGroupMembers(e){return this.runOperation("muteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/mute?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds"),mute_duration:r.muteDuration},{operation:"muteGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteGroupMembers(e){return this.runOperation("unmuteGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/mute/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unmuteGroupMembers"})})(this.getRestClient(t),t,e)})}async muteAllGroupMembers(e){return this.runOperation("muteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/ban?resource=${o.encodedResource}`);await e.post(s,void 0,{operation:"muteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async unmuteAllGroupMembers(e){return this.runOperation("unmuteAllGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/ban?resource=${o.encodedResource}`);await e.delete(s,{operation:"unmuteAllGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupBlocklist(e){return this.runOperation("getGroupBlocklist",async()=>{const t=this.getRestContextOrThrow(),r=await we(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async blockGroupMembers(e){return this.runOperation("blockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/blocks/users?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds")},{operation:"blockGroupMembers"})})(this.getRestClient(t),t,e)})}async unblockGroupMembers(e){return this.runOperation("unblockGroupMembers",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/blocks/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"unblockGroupMembers"})})(this.getRestClient(t),t,e)})}async getGroupAllowlist(e){return this.runOperation("getGroupAllowlist",async()=>{const t=this.getRestContextOrThrow(),r=await Ge(this.getRestClient(t),t,e);return this.hydrateEntriesWithUsers(e.groupId,r)})}async addUsersToGroupAllowlist(e){return this.runOperation("addUsersToGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/white/users?resource=${o.encodedResource}`);await e.post(s,{usernames:ie(r.userIds,"params.userIds")},{operation:"addUsersToGroupAllowlist"})})(this.getRestClient(t),t,e)})}async removeUsersFromGroupAllowlist(e){return this.runOperation("removeUsersFromGroupAllowlist",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ie(r.userIds,"params.userIds"),n=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/white/users/${s.map(e=>encodeURIComponent(e)).join(",")}?resource=${o.encodedResource}`);await e.delete(n,{operation:"removeUsersFromGroupAllowlist"})})(this.getRestClient(t),t,e)})}async checkIfInGroupAllowList(t){return this.runOperation("checkIfInGroupAllowList",async()=>{const r=this.getRestContextOrThrow();return(async(t,r,o)=>{const s=se(r),n=ce(s,`/chatgroups/${encodeURIComponent(ue(o.groupId,"params.groupId"))}/white/users/${s.encodedUserId}?version=v3`),a=await t.get(n,{operation:"checkIfInGroupAllowList"});return"boolean"==typeof a?a:e(a)&&"boolean"==typeof a.data?a.data:Boolean(a)})(this.getRestClient(r),r,t)})}async checkIfInGroupMuteList(t){return this.runOperation("checkIfInGroupMuteList",async()=>{const r=this.getRestContextOrThrow();return(async(t,r,o)=>{const s=se(r),n=ce(s,`/sdk/chatgroups/${encodeURIComponent(ue(o.groupId,"params.groupId"))}/mute/${s.encodedUserId}?version=v3`),a=await t.get(n,{operation:"checkIfInGroupMuteList"});return"boolean"==typeof a?a:e(a)&&"boolean"==typeof a.data?a.data:Boolean(a)})(this.getRestClient(r),r,t)})}async getGroupAnnouncement(e){return this.runOperation("getGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();return be(this.getRestClient(t),t,e)})}async updateGroupAnnouncement(e){return this.runOperation("updateGroupAnnouncement",async()=>{const t=this.getRestContextOrThrow();await(async(e,t,r)=>{const o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/announcement?resource=${o.encodedResource}`);await e.post(s,{announcement:r.announcement},{operation:"updateGroupAnnouncement"})})(this.getRestClient(t),t,e)})}async getGroupSharedFileList(e){return this.runOperation("getGroupSharedFileList",async()=>{const t=this.getRestContextOrThrow(),r=await ve(this.getRestClient(t),t,e),o=await this.resolveGroupContextUserInfoMap(e.groupId,r.items.map(e=>e.fileOwner).filter(e=>void 0!==e));return{...r,items:r.items.map(e=>({...e,fileOwner:e.fileOwner?.userId?o.get(e.fileOwner.userId)??e.fileOwner:e.fileOwner}))}})}async uploadGroupSharedFile(e){return this.runOperation("uploadGroupSharedFile",async()=>{const t=this.getRestContextOrThrow(),r=Re(t,{groupId:e.groupId,fileId:"__upload__"}).replace(/\/share_files\/__upload__$/,"/share_files"),n=u({file:e.file}),a=p({operationName:"GROUP_UPLOAD_SHAREDFILE",operationType:"GROUP"}),i=a?.startRequest({requestName:"GROUP_UPLOAD_SHAREDFILE",method:"POST",url:`${t.restBaseUrl}${r}`});try{const u=await(this.requireClient().getUploadAdapter()?.upload({url:`${t.restBaseUrl}${r}?resource=${encodeURIComponent(t.clientResource)}`,headers:{Authorization:`Bearer ${t.token}`,[c]:m()},source:n.source,timeoutMs:d,onProgress:e.onFileUploadProgress}));if(!u)throw new Error("platform upload adapter is unavailable");if(u.status<200||u.status>=300)throw new s("uploadGroupSharedFile failed",o.REST_HTTP_ERROR,{details:{status:u.status}});i?.finish({code:u.status,success:!0}),a?.finish({code:0,success:!0}),e.onFileUploadComplete?.(u.body)}catch(l){const t=f(l);throw i?.finish({code:t.code,success:!1,description:t.message}),a?.finish({code:t.code,success:!1,description:t.message}),t.code===o.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 o=se(t),s=ce(o,`/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/share_files/${encodeURIComponent(ue(r.fileId,"params.fileId"))}?resource=${o.encodedResource}`);await e.delete(s,{operation:"deleteGroupSharedFile"})})(this.getRestClient(t),t,e)})}async downloadGroupSharedFile(e){return this.runOperation("downloadGroupSharedFile",async()=>{let t,r;try{const n=this.getRestContextOrThrow(),a=`${n.restBaseUrl}${Re(n,e)}`;t=p({operationName:"GROUP_DOWNLOAD_SHAREDFILE",operationType:"GROUP"}),r=t?.startRequest({requestName:"GROUP_DOWNLOAD_SHAREDFILE",method:"GET",url:a});const i=this.requireClient().getRequestAdapter();if(!i)throw new s("downloadGroupSharedFile request adapter is unavailable",o.REST_NETWORK_ERROR);const u=await i.request({url:a,method:"GET",headers:{Authorization:`Bearer ${n.token}`,...e.secret?{"Share-Secret":e.secret}:{},[c]:m()},responseType:"arraybuffer",timeoutMs:l});if(u.status<200||u.status>=300)throw r?.finish({code:u.status,success:!1,description:"downloadGroupSharedFile failed"}),t?.finish({code:u.status,success:!1,description:"downloadGroupSharedFile failed"}),new s("downloadGroupSharedFile failed",o.REST_HTTP_ERROR);r?.finish({code:u.status,success:!0}),t?.finish({code:0,success:!0});const d="undefined"!=typeof Blob?new Blob([u.data]):u.data;e.onFileDownloadComplete?.(d)}catch(n){const a=n instanceof s?n.code:o.REST_NETWORK_ERROR,i=n instanceof Error?n.message:String(n);throw r?.finish({code:a,success:!1,description:i}),t?.finish({code:a,success:!1,description:i}),e.onFileDownloadError?.(n),n}})}async setGroupMemberAttributes(e){return this.runOperation("setGroupMemberAttributes",async()=>{const t=this.getRestContextOrThrow(),r=await Se(this.getRestClient(t),t,e);this.writeSelfGroupNamecardCache(t.userId,e,r)})}async getGroupMembersAttributes(e){return this.runOperation("getGroupMembersAttributes",async()=>{const t=this.getRestContextOrThrow();return Ae(this.getRestClient(t),t,e)})}async hydrateMessageProfileGroupNamecards(e,t){0!==t.length&&await this.runOperation("hydrateMessageProfileGroupNamecards",async()=>{const r=this.getRestContextOrThrow(),o=t.map(e=>e.userId),s=await(async(e,t,r)=>{const o=se(t),s=ce(o,`/sdk/chatgroups/${encodeURIComponent(ue(r.groupId,"params.groupId"))}/nameCard/batch/get`),n=await e.post(s,{members:ie(r.userIds,"params.userIds")},{operation:"getGroupNamecards"});return{items:Ue(n),responseTimestamp:Oe(n)}})(this.getRestClient(r),r,{groupId:e,userIds:o}),n=new Map(t.map(e=>[e.userId,e.namecardUpdateTime])),a=[],u=/* @__PURE__ */new Set;for(const[t,i]of Object.entries(s.items))u.add(t),a.push({groupId:e,userId:t,namecard:i.namecard,namecardUpdateTime:n.get(t)??i.namecardUpdateTime,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()});const p=o.filter(e=>!u.has(e));p.length>0&&"number"==typeof s.responseTimestamp&&a.push(...p.map(t=>({groupId:e,userId:t,namecard:"",namecardUpdateTime:s.responseTimestamp,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}))),this.getCacheManager()?.setGroupNamecards(a);for(const e of a)e.userId!==r.userId&&""!==e.namecard&&this.eventContext?.dispatch?.(b.USER_GROUP_NAMECARD_UPDATED,{groupId:e.groupId,userId:e.userId,namecard:e.namecard});p.length>0&&"number"!=typeof s.responseTimestamp&&i.warn("Group namecard hydration returned partial result",{groupId:e,requestedUserIds:o,missingUserIds:p})})}async runOperation(e,t){try{return await t()}catch(r){const t=this.normalizeSdkError(e,r);throw i.warn(`GroupManager ${e} failed`,{code:t.code,message:t.message,details:t.details}),t}}normalizeSdkError(e,t){return t instanceof s?t:t instanceof Error?new s(`GroupManager ${e} failed: ${t.message}`,o.UNKNOWN):new s(`GroupManager ${e} failed`,o.UNKNOWN)}getRestContextOrThrow(){return this.requireClient().getRestContext()}getRestClient(e){return this.restClient&&this.restBaseUrl===e.restBaseUrl&&this.restToken===e.token||(this.restClient=new h(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 s("GroupManager is not bound to client",o.VALIDATION_REQUIRED);return this.client}getGroupRepository(){return this.groupRepository||(this.groupRepository=new Fe),this.groupRepository}getGroupEventSync(){return this.groupEventSync||(this.groupEventSync=new Te(this.getGroupRepository())),this.groupEventSync}ensureRepositorySession(){this.getGroupRepository().ensureSession(this.resolveRepositorySessionKey())&&this.groupRegistry.clear()}resolveRepositorySessionKey(){if(!this.client)return null;const e=this.client.getCurrentUserId();if(!e)return null;try{const e=this.client.getRestContext();return`${e.restBaseUrl}:${e.userId}:${e.token}:${e.clientResource}`}catch{return`pending:${e}`}}getCacheManager(){return this.client?.getCacheManager()??null}loadJoinedGroupPreviewSnapshot(){const e=this.getCacheManager();if(e&&"function"==typeof e.loadJoinedGroupPreviewSnapshot)return e.loadJoinedGroupPreviewSnapshot()}resolveLocalGroupName(e){const t=this.getGroupRepository(),r=t.getSummarySnapshot(e)?.name;if(r)return r;const o=t.getJoinedGroupSummarySnapshot(e,this.loadJoinedGroupPreviewSnapshot())?.name;return o||void 0}async resolveMembersJoinedGroupName(e){const 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 o=this.getGroupRepository().getSessionKey();try{const t=this.getRestContextOrThrow(),r=await ge(this.getRestClient(t),t,{groupId:e.groupId}),s=this.getGroupRepository();if(s.getSessionKey()!==o)return;return s.mergeDetail(r),this.resolveUsableGroupName(r.name,e.groupId)}catch(s){return void i.warn("Members joined group detail enrichment failed",{groupId:e.groupId,error:s})}}resolveUsableGroupName(e,t){const r=e?.trim();return r&&r!==t?r:void 0}writeSelfGroupNamecardCache(e,t,r){if(t.userId!==e)return;const o=this.extractGroupNamecard(t.memberAttributes);if("string"!=typeof o)return;const s=this.resolveGroupMemberAttributesUpdateTime(r,t.userId);"number"!=typeof s&&i.warn("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:o,namecardUpdateTime:s,lastSyncAt:Date.now(),lastAccess:Date.now(),lastUpdate:Date.now()}])}resolveGroupMemberAttributesUpdateTime(e,t){const r=[];this.collectUpdateTimeCandidates(e,t,r);for(const o of r){const e=y("number"==typeof o?o:Number(o));if("number"==typeof e)return e}}collectUpdateTimeCandidates(t,r,o){if(!e(t))return;o.push(t.lastModified,t.last_modified,t.timestamp,t.updateTime,t.update_time,t.updatedAt,t.updated_at);const s=t.data;if(e(s)){this.collectUpdateTimeCandidates(s,r,o);const t=s[r];e(t)&&this.collectUpdateTimeCandidates(t,r,o)}const n=t.lastModified??t.last_modified;e(n)&&o.push(n[r])}getUserInfoManager(){const e=this.requireClient();if(!this.hasUserInfoCapabilityProvider(e))return null;const t=e.getManagerByCapability("userInfo:read");return t&&this.hasUserInfoReadCapability(t)?t:null}hasUserInfoCapabilityProvider(e){return"function"==typeof e.getManagerByCapability}hasUserInfoReadCapability(e){return"function"==typeof e.getUserInfoByUserId}async resolveUserInfoMap(e){return L(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 i.warn("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??[]],o=[],s=/* @__PURE__ */new Set;for(const n of r){if("string"!=typeof n)continue;const e=n.trim();e&&!s.has(e)&&(s.add(e),o.push(e))}return o}pickEventUser(e,t){if(e)return N(void 0,t.get(e),e)}pickEventUsers(e,t){return(e??[]).map(e=>N(void 0,t.get(e),e))}hydrateEventSharedFile(e,t){return e?.fileOwner?.userId?{...e,fileOwner:N(e.fileOwner,t.get(e.fileOwner.userId),e.fileOwner.userId)}:e}async syncRuntimeForEvent(e,t,r){switch(e){case b.ALL_MEMBER_MUTE_STATE_CHANGED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{muteAllMembers:Boolean(t.isMuted)}});case b.OWNER_CHANGED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,groupPatch:{owner:this.pickEventUser(t.newOwnerId,r)}});case b.REQUEST_TO_JOIN_ACCEPTED:case b.AUTO_ACCEPT_INVITATION:return void this.addCurrentUserJoinedGroupFromEvent(t);case b.MEMBERS_JOINED:{let r=!1;if(t.memberIds?.includes(this.requireClient().getCurrentUserId()??"")&&(r=await this.addCurrentUserJoinedGroupFromEvent(t)),r)return;if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0})}case b.MEMBERS_EXITED:if(this.applyMemberCountDeltaPatch(t.groupId,t.groupName,-this.getMemberEventDeltaCount(e,t)))return;return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});case b.USER_REMOVED:case b.GROUP_DESTROYED:return void(await this.removeJoinedGroupLocal(t.groupId));case b.MUTE_LIST_ADDED:case b.MUTE_LIST_REMOVED:case b.ALLOW_LIST_ADDED:case b.ALLOW_LIST_REMOVED:case b.ADMIN_ADDED:case b.ADMIN_REMOVED:return void this.getGroupEventSync().applyPatch({groupId:t.groupId,groupName:t.groupName,shouldMarkStale:!0});default:return}}getMemberEventDeltaCount(e,t){switch(e){case b.MEMBERS_JOINED:case b.MEMBERS_EXITED:return t.memberIds?.length??0;default:return 0}}applyMemberCountDeltaPatch(e,t,r){if(0===r)return!1;const o=this.getGroupRepository().getDetailSnapshot(e);return!(!o||"number"!=typeof o.memberCount)&&(this.getGroupEventSync().applyPatch({groupId:e,groupName:t,groupPatch:{memberCount:Math.max(0,o.memberCount+r)}}),!0)}async removeJoinedGroupLocal(e){this.getGroupRepository().markJoinedGroupRemoved(e);const t=this.getCacheManager();t&&"function"==typeof t.removeJoinedGroupPreview&&await t.removeJoinedGroupPreview(e)}async addCurrentUserJoinedGroupFromEvent(e){if(!this.addJoinedGroupIfAbsent({groupId:e.groupId,name:e.groupName??"",role:"member"}))return!1;const t=this.getGroupRepository().getSessionKey();let r;try{r=this.getRestContextOrThrow()}catch(o){return i.warn("Joined group detail enrichment skipped",{groupId:e.groupId,error:o}),!1}try{return await this.enrichJoinedGroupFromDetail(e.groupId,t,r)}catch(o){return i.warn("Joined group detail enrichment failed",{groupId:e.groupId,error:o}),!1}}addJoinedGroupIfAbsent(e){const t=this.getGroupRepository().addJoinedGroupIfAbsent(e,this.loadJoinedGroupPreviewSnapshot());return!!t&&(this.persistJoinedGroupSnapshot(t),!0)}async enrichJoinedGroupFromDetail(e,t,r){const o=await ge(this.getRestClient(r),r,{groupId:e}),s=this.getGroupRepository();if(s.getSessionKey()!==t)return!1;s.mergeDetail(o);const n=s.getJoinedGroupSummarySnapshot(e);if(!n)return!1;const a=s.mergeJoinedGroupSummary(e,{...n.name||!o.name?{}:{name:o.name},...void 0!==n.description||void 0===o.description?{}:{description:o.description},...void 0!==n.memberCount||void 0===o.memberCount?{}:{memberCount:o.memberCount},...void 0!==n.role||void 0===o.role?{}:{role:o.role},...void 0!==n.disabled||void 0===o.disabled?{}:{disabled:o.disabled},...n.ownerId||!o.owner?.userId?{}:{ownerId:o.owner.userId},...void 0!==n.avatarUrl||void 0===o.avatarUrl?{}:{avatarUrl:o.avatarUrl},...void 0!==n.muteAllMembers||void 0===o.muteAllMembers?{}:{muteAllMembers:o.muteAllMembers},...void 0!==n.createdAt||void 0===o.createdAt?{}:{createdAt:o.createdAt},...void 0!==n.joinedAt||void 0===o.joinedAt?{}:{joinedAt:o.joinedAt}});if(a){this.persistJoinedGroupSnapshot(a);const t=s.getJoinedGroupSummarySnapshot(e);t&&this.requireClient().refreshConversationDisplayFromJoinedGroups([{...t,name:o.name||t.name,avatarUrl:o.avatarUrl??t.avatarUrl}],"profile",{onlyWhenNameMissing:!0})}return!0}persistJoinedGroupSnapshot(e){const t=this.getCacheManager();if(t&&"function"==typeof t.applyJoinedGroupPreviewSnapshot){try{t.applyJoinedGroupPreviewSnapshot(e)}catch(r){return void i.warn("Joined group preview persistence failed",{error:r})}"function"==typeof t.flushPending&&t.flushPending().catch(e=>{i.warn("Joined group preview flush failed",{error:e})})}}async hydrateUserInfos(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t);return t.map(e=>r.get(e.userId)??e)}async fetchUserInfosFromRest(e){const t=this.getRestContextOrThrow(),r=R(e),o=await this.getRestClient(t).request(S(t),{method:"POST",body:r,operation:"getUserInfoByUserId"});return A(o,r.targets)}async hydrateEntriesWithUsers(e,t){const r=await this.resolveGroupContextUserInfoMap(e,t.map(e=>e.user));return t.map(e=>({...e,user:r.get(e.user.userId)??e.user}))}extractGroupNamecard(e){return e.groupNamecard??e.group_namecard??e.group_name_card??e.namecard}async hydrateGroupDetailUsers(e){if(!e.owner?.userId)return e;const t=await this.resolveGroupContextUserInfoMap(e.groupId,[e.owner]);return{...e,owner:t.get(e.owner.userId)??e.owner}}async hydrateGroupDetailsUsers(e){const t=e.filter(e=>Boolean(e.owner?.userId)).map(e=>({groupId:e.groupId,user:e.owner}));if(0===t.length)return e;const r=await this.resolveGroupUserInfoContexts(t);return e.map(e=>e.owner?.userId?{...e,owner:r.get(_(e.groupId,e.owner.userId))??e.owner}:e)}async resolveGroupContextUserInfoMap(e,t){const r=this.isGroupNamecardEnhancementEnabled(),o=await w({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(o.fetchedUserInfos),o.usersById}async resolveGroupUserInfoContexts(e){const t=this.isGroupNamecardEnhancementEnabled(),r=await G({contexts:e,includeNameCard:t,cacheManager:this.getCacheManager(),fetchUserInfos:async({userIds:e})=>await this.fetchGroupUserInfos(e),hydrateGroupNamecards:async(e,t)=>await this.hydrateMessageProfileGroupNamecards(e,t.map(e=>({userId:e})))});return t&&this.dispatchFetchedUserInfoUpdates(r.fetchedUserInfos),r.usersByContextKey}async fetchGroupUserInfos(e){if(0===e.length)return[];const t=this.getUserInfoManager();return t?await t.getUserInfoByUserId({userIds:e}):await this.fetchUserInfosFromRest(e)}isGroupNamecardEnhancementEnabled(){const e=this.requireClient(),t=e.isUserInfoSyncEnabled;return"function"==typeof t&&t.call(e)}dispatchFetchedUserInfoUpdates(e){if(0===e.length)return;const t=this.requireClient(),r=t.getCurrentUserId(),o=e.find(e=>e.userId===r),s=e.filter(e=>e.userId!==r);o&&t.dispatchOwnInfoUpdated?.(o),t.dispatchUserInfoUpdated?.(s),t.refreshConversationDisplayFromUserInfos?.(e.map(e=>({userId:e.userId})),"profile")}createSyncController(e){return new pt(e)}};ct.key="groupManager";let mt=ct;export{oe as G,re as J,mt as a,Q as n};