@amityco/ts-sdk-react-native 7.27.2-60f0571.0 → 7.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/dist/@types/core/events.d.ts +5 -0
  2. package/dist/@types/core/events.d.ts.map +1 -1
  3. package/dist/@types/core/payload.d.ts +26 -0
  4. package/dist/@types/core/payload.d.ts.map +1 -1
  5. package/dist/@types/core/permissions.d.ts +10 -4
  6. package/dist/@types/core/permissions.d.ts.map +1 -1
  7. package/dist/@types/domains/analytics.d.ts +3 -1
  8. package/dist/@types/domains/analytics.d.ts.map +1 -1
  9. package/dist/@types/domains/channel.d.ts +5 -0
  10. package/dist/@types/domains/channel.d.ts.map +1 -1
  11. package/dist/@types/domains/client.d.ts +18 -0
  12. package/dist/@types/domains/client.d.ts.map +1 -1
  13. package/dist/@types/domains/comment.d.ts +27 -0
  14. package/dist/@types/domains/comment.d.ts.map +1 -1
  15. package/dist/@types/domains/community.d.ts +1 -0
  16. package/dist/@types/domains/community.d.ts.map +1 -1
  17. package/dist/@types/domains/curatedContent.d.ts +25 -0
  18. package/dist/@types/domains/curatedContent.d.ts.map +1 -0
  19. package/dist/@types/domains/pinnedMessage.d.ts +43 -0
  20. package/dist/@types/domains/pinnedMessage.d.ts.map +1 -0
  21. package/dist/@types/domains/post.d.ts +11 -0
  22. package/dist/@types/domains/post.d.ts.map +1 -1
  23. package/dist/@types/index.d.ts +3 -1
  24. package/dist/@types/index.d.ts.map +1 -1
  25. package/dist/analytic/service/analytic/AnalyticsEngine.d.ts +3 -0
  26. package/dist/analytic/service/analytic/AnalyticsEngine.d.ts.map +1 -1
  27. package/dist/analytic/service/analytic/AnalyticsEventCapturer.d.ts +3 -0
  28. package/dist/analytic/service/analytic/AnalyticsEventCapturer.d.ts.map +1 -1
  29. package/dist/channelRepository/api/createChannel.d.ts.map +1 -1
  30. package/dist/channelRepository/events/index.d.ts +2 -0
  31. package/dist/channelRepository/events/index.d.ts.map +1 -1
  32. package/dist/channelRepository/events/onChannelMemberRoleAdded.d.ts +22 -0
  33. package/dist/channelRepository/events/onChannelMemberRoleAdded.d.ts.map +1 -1
  34. package/dist/channelRepository/events/onChannelMemberRoleRemoved.d.ts +22 -0
  35. package/dist/channelRepository/events/onChannelMemberRoleRemoved.d.ts.map +1 -1
  36. package/dist/channelRepository/events/onChannelMessagePinned.d.ts +24 -0
  37. package/dist/channelRepository/events/onChannelMessagePinned.d.ts.map +1 -0
  38. package/dist/channelRepository/events/onChannelMessageUnpinned.d.ts +21 -0
  39. package/dist/channelRepository/events/onChannelMessageUnpinned.d.ts.map +1 -0
  40. package/dist/channelRepository/events/onChannelPinnedMessageDeleted.d.ts +12 -0
  41. package/dist/channelRepository/events/onChannelPinnedMessageDeleted.d.ts.map +1 -0
  42. package/dist/channelRepository/events/tests/onChannelMemberRoleAdded.test.d.ts +2 -0
  43. package/dist/channelRepository/events/tests/onChannelMemberRoleAdded.test.d.ts.map +1 -0
  44. package/dist/channelRepository/events/tests/onChannelMemberRoleRemoved.test.d.ts +2 -0
  45. package/dist/channelRepository/events/tests/onChannelMemberRoleRemoved.test.d.ts.map +1 -0
  46. package/dist/channelRepository/events/tests/onChannelMessagePinned.test.d.ts +2 -0
  47. package/dist/channelRepository/events/tests/onChannelMessagePinned.test.d.ts.map +1 -0
  48. package/dist/channelRepository/observers/getChannel.d.ts.map +1 -1
  49. package/dist/channelRepository/observers/getChannels/ChannelLiveCollectionController.d.ts.map +1 -1
  50. package/dist/channelRepository/observers/getMyMembership.d.ts.map +1 -1
  51. package/dist/channelRepository/observers/searchChannels/SearchChannelLiveCollectionController.d.ts.map +1 -1
  52. package/dist/channelRepository/utils/applyChannelRolePayload.d.ts +21 -0
  53. package/dist/channelRepository/utils/applyChannelRolePayload.d.ts.map +1 -0
  54. package/dist/channelRepository/utils/index.d.ts +2 -0
  55. package/dist/channelRepository/utils/index.d.ts.map +1 -1
  56. package/dist/channelRepository/utils/tests/pinnedMessage.test.d.ts +2 -0
  57. package/dist/channelRepository/utils/tests/pinnedMessage.test.d.ts.map +1 -0
  58. package/dist/channelRepository/utils/updatePinnedMessageCache.d.ts +24 -0
  59. package/dist/channelRepository/utils/updatePinnedMessageCache.d.ts.map +1 -0
  60. package/dist/client/api/createClient.d.ts +5 -1
  61. package/dist/client/api/createClient.d.ts.map +1 -1
  62. package/dist/client/api/getSocialSettings.d.ts.map +1 -1
  63. package/dist/client/api/setupLoginSubscriptions.d.ts.map +1 -1
  64. package/dist/client/api/tests/getSocialSettings.test.d.ts +2 -0
  65. package/dist/client/api/tests/getSocialSettings.test.d.ts.map +1 -0
  66. package/dist/commentRepository/api/approveComment.d.ts +17 -0
  67. package/dist/commentRepository/api/approveComment.d.ts.map +1 -0
  68. package/dist/commentRepository/api/createComment.d.ts +12 -1
  69. package/dist/commentRepository/api/createComment.d.ts.map +1 -1
  70. package/dist/commentRepository/api/declineComment.d.ts +18 -0
  71. package/dist/commentRepository/api/declineComment.d.ts.map +1 -0
  72. package/dist/commentRepository/api/deleteComment.d.ts.map +1 -1
  73. package/dist/commentRepository/api/index.d.ts +2 -0
  74. package/dist/commentRepository/api/index.d.ts.map +1 -1
  75. package/dist/commentRepository/api/tests/approveComment.test.d.ts +2 -0
  76. package/dist/commentRepository/api/tests/approveComment.test.d.ts.map +1 -0
  77. package/dist/commentRepository/api/tests/createComment.optimistic.test.d.ts +2 -0
  78. package/dist/commentRepository/api/tests/createComment.optimistic.test.d.ts.map +1 -0
  79. package/dist/commentRepository/api/tests/declineComment.test.d.ts +2 -0
  80. package/dist/commentRepository/api/tests/declineComment.test.d.ts.map +1 -0
  81. package/dist/commentRepository/api/updateComment.d.ts.map +1 -1
  82. package/dist/commentRepository/events/index.d.ts +1 -0
  83. package/dist/commentRepository/events/index.d.ts.map +1 -1
  84. package/dist/commentRepository/events/onCommentApproved.d.ts +17 -0
  85. package/dist/commentRepository/events/onCommentApproved.d.ts.map +1 -0
  86. package/dist/commentRepository/events/tests/onCommentApproved.test.d.ts +2 -0
  87. package/dist/commentRepository/events/tests/onCommentApproved.test.d.ts.map +1 -0
  88. package/dist/commentRepository/events/tests/onCommentCreated.count.test.d.ts +2 -0
  89. package/dist/commentRepository/events/tests/onCommentCreated.count.test.d.ts.map +1 -0
  90. package/dist/commentRepository/events/utils.d.ts.map +1 -1
  91. package/dist/commentRepository/internalApi/getComment.d.ts.map +1 -1
  92. package/dist/commentRepository/observers/getComment.d.ts.map +1 -1
  93. package/dist/commentRepository/observers/getCommentReviewQueue/LiveCollectionController.d.ts +13 -0
  94. package/dist/commentRepository/observers/getCommentReviewQueue/LiveCollectionController.d.ts.map +1 -0
  95. package/dist/commentRepository/observers/getCommentReviewQueue/PaginationController.d.ts +5 -0
  96. package/dist/commentRepository/observers/getCommentReviewQueue/PaginationController.d.ts.map +1 -0
  97. package/dist/commentRepository/observers/getCommentReviewQueue/QueryStreamController.d.ts +15 -0
  98. package/dist/commentRepository/observers/getCommentReviewQueue/QueryStreamController.d.ts.map +1 -0
  99. package/dist/commentRepository/observers/getCommentReviewQueue.d.ts +22 -0
  100. package/dist/commentRepository/observers/getCommentReviewQueue.d.ts.map +1 -0
  101. package/dist/commentRepository/observers/getComments/CommentLiveCollectionController.d.ts +1 -1
  102. package/dist/commentRepository/observers/getComments/CommentLiveCollectionController.d.ts.map +1 -1
  103. package/dist/commentRepository/observers/getComments/CommentQueryStreamController.d.ts.map +1 -1
  104. package/dist/commentRepository/observers/getComments/enums.d.ts +1 -0
  105. package/dist/commentRepository/observers/getComments/enums.d.ts.map +1 -1
  106. package/dist/commentRepository/observers/index.d.ts +1 -0
  107. package/dist/commentRepository/observers/index.d.ts.map +1 -1
  108. package/dist/commentRepository/observers/tests/integrations/getCommentReviewQueue.integration.test.d.ts +2 -0
  109. package/dist/commentRepository/observers/tests/integrations/getCommentReviewQueue.integration.test.d.ts.map +1 -0
  110. package/dist/commentRepository/utils/approval.d.ts +49 -0
  111. package/dist/commentRepository/utils/approval.d.ts.map +1 -0
  112. package/dist/commentRepository/utils/payload.d.ts +6 -0
  113. package/dist/commentRepository/utils/payload.d.ts.map +1 -1
  114. package/dist/commentRepository/utils/tests/approval.test.d.ts +2 -0
  115. package/dist/commentRepository/utils/tests/approval.test.d.ts.map +1 -0
  116. package/dist/commentRepository/utils/tests/payload.test.d.ts +2 -0
  117. package/dist/commentRepository/utils/tests/payload.test.d.ts.map +1 -0
  118. package/dist/communityRepository/api/createCommunity.d.ts +1 -1
  119. package/dist/communityRepository/api/createCommunity.d.ts.map +1 -1
  120. package/dist/communityRepository/api/updateCommunity.d.ts +1 -1
  121. package/dist/communityRepository/api/updateCommunity.d.ts.map +1 -1
  122. package/dist/core/device.d.ts +1 -1
  123. package/dist/core/device.d.ts.map +1 -1
  124. package/dist/core/events.d.ts +3 -3
  125. package/dist/core/events.d.ts.map +1 -1
  126. package/dist/core/tests/device.test.d.ts +2 -0
  127. package/dist/core/tests/device.test.d.ts.map +1 -0
  128. package/dist/core/transports/http.d.ts.map +1 -1
  129. package/dist/core/transports/utils.d.ts +8 -0
  130. package/dist/core/transports/utils.d.ts.map +1 -1
  131. package/dist/curatedContentRepository/api/getPool.d.ts +2 -0
  132. package/dist/curatedContentRepository/api/getPool.d.ts.map +1 -0
  133. package/dist/curatedContentRepository/api/index.d.ts +2 -0
  134. package/dist/curatedContentRepository/api/index.d.ts.map +1 -0
  135. package/dist/curatedContentRepository/api/tests/getPool.test.d.ts +2 -0
  136. package/dist/curatedContentRepository/api/tests/getPool.test.d.ts.map +1 -0
  137. package/dist/curatedContentRepository/api/tests/integration/getPool.integration.test.d.ts +2 -0
  138. package/dist/curatedContentRepository/api/tests/integration/getPool.integration.test.d.ts.map +1 -0
  139. package/dist/curatedContentRepository/index.d.ts +2 -0
  140. package/dist/curatedContentRepository/index.d.ts.map +1 -0
  141. package/dist/index.cjs.js +1744 -479
  142. package/dist/index.d.ts +1 -0
  143. package/dist/index.d.ts.map +1 -1
  144. package/dist/index.esm.js +1719 -455
  145. package/dist/index.umd.js +1 -1
  146. package/dist/messagePreview/utils/getChannelMessagePreviewWithUser.d.ts +1 -0
  147. package/dist/messagePreview/utils/getChannelMessagePreviewWithUser.d.ts.map +1 -1
  148. package/dist/messageRepository/api/index.d.ts +2 -0
  149. package/dist/messageRepository/api/index.d.ts.map +1 -1
  150. package/dist/messageRepository/api/pinMessage.d.ts +29 -0
  151. package/dist/messageRepository/api/pinMessage.d.ts.map +1 -0
  152. package/dist/messageRepository/api/tests/pinMessage.test.d.ts +2 -0
  153. package/dist/messageRepository/api/tests/pinMessage.test.d.ts.map +1 -0
  154. package/dist/messageRepository/api/tests/unpinMessage.test.d.ts +2 -0
  155. package/dist/messageRepository/api/tests/unpinMessage.test.d.ts.map +1 -0
  156. package/dist/messageRepository/api/unpinMessage.d.ts +28 -0
  157. package/dist/messageRepository/api/unpinMessage.d.ts.map +1 -0
  158. package/dist/messageRepository/utils/refreshChannelPermissionsForMessage.d.ts +13 -0
  159. package/dist/messageRepository/utils/refreshChannelPermissionsForMessage.d.ts.map +1 -0
  160. package/dist/postRepository/utils/PostCommentCountEngine/ApproveTask.d.ts +16 -0
  161. package/dist/postRepository/utils/PostCommentCountEngine/ApproveTask.d.ts.map +1 -0
  162. package/dist/postRepository/utils/PostCommentCountEngine/PostCommentCountEngine.d.ts +25 -1
  163. package/dist/postRepository/utils/PostCommentCountEngine/PostCommentCountEngine.d.ts.map +1 -1
  164. package/dist/postRepository/utils/PostCommentCountEngine/postCommentCountEngineOnLoginHandler.d.ts +9 -0
  165. package/dist/postRepository/utils/PostCommentCountEngine/postCommentCountEngineOnLoginHandler.d.ts.map +1 -0
  166. package/dist/postRepository/utils/PostCommentCountEngine/tests/getLocalCommentCount.test.d.ts +2 -0
  167. package/dist/postRepository/utils/PostCommentCountEngine/tests/getLocalCommentCount.test.d.ts.map +1 -0
  168. package/dist/postRepository/utils/PostCommentCountEngine/tests/pendingAuthoredComments.test.d.ts +2 -0
  169. package/dist/postRepository/utils/PostCommentCountEngine/tests/pendingAuthoredComments.test.d.ts.map +1 -0
  170. package/dist/postRepository/utils/latestComments.d.ts +10 -0
  171. package/dist/postRepository/utils/latestComments.d.ts.map +1 -0
  172. package/dist/postRepository/utils/payload.d.ts.map +1 -1
  173. package/dist/postRepository/utils/tests/latestComments.test.d.ts +2 -0
  174. package/dist/postRepository/utils/tests/latestComments.test.d.ts.map +1 -0
  175. package/dist/postRepository/utils/tests/payload.test.d.ts +2 -0
  176. package/dist/postRepository/utils/tests/payload.test.d.ts.map +1 -0
  177. package/dist/utils/constants.d.ts +4 -0
  178. package/dist/utils/constants.d.ts.map +1 -1
  179. package/dist/utils/linkedObject/commentLinkedObject.d.ts.map +1 -1
  180. package/dist/utils/linkedObject/curatedContentTopicLinkedObject.d.ts +2 -0
  181. package/dist/utils/linkedObject/curatedContentTopicLinkedObject.d.ts.map +1 -0
  182. package/dist/utils/linkedObject/index.d.ts +1 -0
  183. package/dist/utils/linkedObject/index.d.ts.map +1 -1
  184. package/dist/utils/linkedObject/messageLinkedObject.d.ts.map +1 -1
  185. package/dist/utils/linkedObject/postLinkedObject.d.ts.map +1 -1
  186. package/dist/utils/linkedObject/tests/postLinkedObject.test.d.ts +2 -0
  187. package/dist/utils/linkedObject/tests/postLinkedObject.test.d.ts.map +1 -0
  188. package/dist/utils/tests/dummy/comment.d.ts +1 -0
  189. package/dist/utils/tests/dummy/comment.d.ts.map +1 -1
  190. package/dist/utils/tests/dummy/index.d.ts +1 -0
  191. package/dist/utils/tests/dummy/index.d.ts.map +1 -1
  192. package/dist/utils/tests/dummy/pinnedMessage.d.ts +2 -0
  193. package/dist/utils/tests/dummy/pinnedMessage.d.ts.map +1 -0
  194. package/dist/utils/tests/dummy/post.d.ts.map +1 -1
  195. package/package.json +3 -2
package/dist/index.umd.js CHANGED
@@ -1 +1 @@
1
- var Amity=function(e,t,n,a,s,o,i,r,c,d,l,u,h){"use strict";function m(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var g,p,y,v,f,b=m(n),I=m(a),C=m(s),w=m(o),S=m(i),O=m(r),T=m(c),A=m(d),R=m(u),P=m(h);e.MembershipAcceptanceTypeEnum=void 0,(g=e.MembershipAcceptanceTypeEnum||(e.MembershipAcceptanceTypeEnum={})).AUTOMATIC="automatic",g.INVITATION="invitation",e.AmityAutoSubscription=void 0,(p=e.AmityAutoSubscription||(e.AmityAutoSubscription={})).CHAT="chat",p.NETWORK="network",p.LIVESTREAM="livestream",p.BLOCK="block",e.UserTypeEnum=void 0,(y=e.UserTypeEnum||(e.UserTypeEnum={})).SIGNED_IN="signed-in",y.VISITOR="visitor",y.BOT="bot",e.SearchUsersByEnum=void 0,(v=e.SearchUsersByEnum||(e.SearchUsersByEnum={})).DISPLAY_NAME="displayName",v.PROFILE_HANDLE="profileHandle",v.USER_ID="userId",e.UserReportTypeEnum=void 0,(f=e.UserReportTypeEnum||(e.UserReportTypeEnum={})).DISPLAY_NAME="displayName",f.DESCRIPTION="description",f.AVATAR="avatarFileId",f.BEHAVIOR="behavior";const D=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video",CLIP:"clip",AUDIO:"audio"}),U=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),k=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),j=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var E,M;e.FileAccessTypeEnum=void 0,(E=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",E.NETWORK="network",e.AmityChannelNotificationModeEnum=void 0,(M=e.AmityChannelNotificationModeEnum||(e.AmityChannelNotificationModeEnum={})).Default="default",M.Silent="silent",M.Subscribe="subscribe";const q=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),x=Object.freeze({ONLY_ADMIN_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!0},ADMIN_REVIEW_POST_REQUIRED:{needApprovalOnPostCreation:!0,onlyAdminCanPost:!1},ANYONE_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!1}}),N="ONLY_ADMIN_CAN_POST";var K;e.AmityCommunityType=void 0,(K=e.AmityCommunityType||(e.AmityCommunityType={})).Default="default",K.Event="event";const F=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"});var _;e.ContentFlagReasonEnum=void 0,(_=e.ContentFlagReasonEnum||(e.ContentFlagReasonEnum={})).CommunityGuidelines="Against community guidelines",_.HarassmentOrBullying="Harassment or bullying",_.SelfHarmOrSuicide="Self-harm or suicide",_.ViolenceOrThreateningContent="Violence or threatening content",_.SellingRestrictedItems="Selling and promoting restricted items",_.SexualContentOrNudity="Sexual content or nudity",_.SpamOrScams="Spam or scams",_.FalseInformation="False information or misinformation",_.Others="Others";const B=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),$=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll",CLIP:"clip",AUDIO:"audio",ROOM:"room",EVENT:"event"}),L=Object.freeze({TEXT:"text",IMAGE:"image",VIDEO:"video",FILE:"file",AUDIO:"audio",MIXED:"mixed",EVENT:"event"});var Q,V,J,H,G,z,Y,W,X,Z,ee,te,ne,ae,se,oe,ie,re,ce,de,le,ue,he;e.InvitationTypeEnum=void 0,(Q=e.InvitationTypeEnum||(e.InvitationTypeEnum={})).CommunityMemberInvite="communityMemberInvite",Q.LivestreamCohostInvite="livestreamCohostInvite",e.InvitationStatusEnum=void 0,(V=e.InvitationStatusEnum||(e.InvitationStatusEnum={})).Pending="pending",V.Approved="approved",V.Rejected="rejected",V.Cancelled="cancelled",e.InvitationSortByEnum=void 0,(J=e.InvitationSortByEnum||(e.InvitationSortByEnum={})).FirstCreated="firstCreated",J.LastCreated="lastCreated",e.InvitationTargetTypeEnum=void 0,(H=e.InvitationTargetTypeEnum||(e.InvitationTargetTypeEnum={})).Community="community",H.Room="room",e.JoinRequestStatusEnum=void 0,(G=e.JoinRequestStatusEnum||(e.JoinRequestStatusEnum={})).Pending="pending",G.Approved="approved",G.Rejected="rejected",G.Cancelled="cancelled",e.JoinResultStatusEnum=void 0,(z=e.JoinResultStatusEnum||(e.JoinResultStatusEnum={})).Success="success",z.Pending="pending",e.FeedDataTypeEnum=void 0,(Y=e.FeedDataTypeEnum||(e.FeedDataTypeEnum={})).Text="text",Y.Video="video",Y.Image="image",Y.File="file",Y.Audio="audio",Y.LiveStream="liveStream",Y.Clip="clip",Y.Poll="poll",Y.Room="room",e.FeedSortByEnum=void 0,(W=e.FeedSortByEnum||(e.FeedSortByEnum={})).LastCreated="lastCreated",W.FirstCreated="firstCreated",W.LastUpdated="lastUpdated",W.FirstUpdated="firstUpdated",e.FeedSourceEnum=void 0,(X=e.FeedSourceEnum||(e.FeedSourceEnum={})).Community="community",X.User="user",e.FeedTypeEnum=void 0,(Z=e.FeedTypeEnum||(e.FeedTypeEnum={})).Reviewing="reviewing",Z.Published="published",Z.Declined="declined",e.AmityEventType=void 0,(ee=e.AmityEventType||(e.AmityEventType={})).Virtual="virtual",ee.InPerson="in_person",e.AmityEventOriginType=void 0,(te=e.AmityEventOriginType||(e.AmityEventOriginType={})).Community="community",te.User="user",e.AmityEventStatus=void 0,(ne=e.AmityEventStatus||(e.AmityEventStatus={})).Scheduled="scheduled",ne.Live="live",ne.Ended="ended",ne.Cancelled="cancelled",e.AmityEventResponseStatus=void 0,(ae=e.AmityEventResponseStatus||(e.AmityEventResponseStatus={})).Going="going",ae.NotGoing="not_going",e.AmityEventSortOption=void 0,(se=e.AmityEventSortOption||(e.AmityEventSortOption={})).StartTime="startTime",se.CreatedAt="createdAt",e.AmityEventOrderOption=void 0,(oe=e.AmityEventOrderOption||(e.AmityEventOrderOption={})).Ascending="asc",oe.Descending="desc",e.AmitySharableContentType=void 0,(ie=e.AmitySharableContentType||(e.AmitySharableContentType={})).POST="post",ie.COMMUNITY="community",ie.USER="user",ie.LIVESTREAM="livestream",ie.EVENT="event",e.AnalyticsSourceTypeEnum=void 0,(re=e.AnalyticsSourceTypeEnum||(e.AnalyticsSourceTypeEnum={})).POST="post",re.ROOM="room",e.UserNotificationModuleNameEnum=void 0,(ce=e.UserNotificationModuleNameEnum||(e.UserNotificationModuleNameEnum={})).CHAT="chat",ce.SOCIAL="social",ce.VIDEO_STREAMING="video-streaming",e.CommunityNotificationEventNameEnum=void 0,(de=e.CommunityNotificationEventNameEnum||(e.CommunityNotificationEventNameEnum={})).POST_CREATED="post.created",de.POST_REACTED="post.reacted",de.COMMENT_CREATED="comment.created",de.COMMENT_REPLIED="comment.replied",de.COMMENT_REACTED="comment.reacted",de.STORY_CREATED="story.created",de.STORY_REACTED="story.reacted",de.STORY_COMMENT_CREATED="story-comment.created",de.LIVESTREAM_START="video-streaming.didStart",e.NotificationSettingsLevelEnum=void 0,(le=e.NotificationSettingsLevelEnum||(e.NotificationSettingsLevelEnum={})).USER="user",le.COMMUNITY="community",le.CHANNEL="channel",e.NotificationRolesFilterTypeEnum=void 0,(ue=e.NotificationRolesFilterTypeEnum||(e.NotificationRolesFilterTypeEnum={})).ALL="all",ue.ONLY="only",e.AmityLiveViewerCountMode=void 0,(he=e.AmityLiveViewerCountMode||(e.AmityLiveViewerCountMode={})).ALWAYS_SHOW="always",he.HIDE_ENTIRELY="hidden",he.SHOW_ABOVE_MINIMUM="above-minimum";const me=function(){try{return"v7.27.1-umd"}catch(e){return"__dev__"}}(),ge=5,pe=20,ye="cache_then_server",ve="For using Live Collection feature you need to enable Cache!",fe="Observing unsynced object is not supported by Live Object.",be=-5,Ie=1e3,Ce=6e5,we="/api/v1/feeds/for-you",Se="dead",Oe=6e4,Te=e=>JSON.stringify(e,((e,t)=>{return null!==t&&"object"==typeof t?(n=t,Object.keys(n).sort().reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:n[t]})),{})):t;var n})),Ae=e=>JSON.parse(e),Re=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>Re(e[n],t[n])))),Pe=e=>[400400,400300].includes(e),De=e=>["skip"].some((t=>t in e)),Ue=e=>["after","before","first","last","limit"].some((t=>t in e)),ke=e=>"limit"in e,je=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),Ee=(e,n)=>{var a;if(!e||!Object.keys(e).length)return;let s={};return"skiplimit"===n?s={skip:null!==(a=e.after)&&void 0!==a?a:0,limit:e.limit}:"afterbefore"===n&&Ue(e)?((null==e?void 0:e.before)&&(s=Object.assign(Object.assign({},s),{before:e.before})),(null==e?void 0:e.after)&&(s=Object.assign(Object.assign({},s),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(s=Object.assign(Object.assign({},s),{limit:e.limit}))):"afterbeforeraw"===n&&(s=e),Object.keys(s).length?t.encode(JSON.stringify(s)):void 0},Me=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(De(n))return{after:n.skip,limit:n.limit};if(Ue(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},qe=e=>"locally"in e,xe=e=>"optimistically"in e,Ne=e=>qe(e)||xe(e),Ke=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),Fe=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},_e=(e,...t)=>({func:e,args:t}),Be=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<Oe?Oe:t},$e=({func:e,args:t},n,a=Be("cache_then_server"))=>{let s;const{lifeSpan:o}=Be("cache_then_server",a.lifeSpan);if(Ne(e)){try{s=xe(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(Le(void 0,{origin:"local",loading:!1,error:e}))}const a=Ke(s)&&Fe(s,o);if(null==n||n(Le(s,{origin:"local",loading:!(qe(e)&&a)})),a)return}else null==n||n(Le(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(Le(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(Le(void 0,{origin:"server",loading:!1,error:e}))}))};function Le(e,t){return je(e)||Ke(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}class Qe extends Error{constructor(e,t,n){super(`Amity SDK (${t}): ${e}`),this.code=t,this.level=n,this.type="ASC",this.timestamp=Date.now(),Error.captureStackTrace&&Error.captureStackTrace(this,Qe)}}class Ve extends Qe{constructor(e,t,n){super(e,t,n)}}class Je extends Qe{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class He extends Qe{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class Ge extends Qe{constructor(e){super(e,800110,"error")}}let ze=null;const Ye=()=>{if(!ze)throw new Qe("There is no active client",8e5,"fatal");return ze},We=e=>{ze=e},Xe={user:({userId:e})=>e,file:({fileId:e})=>e,role:({roleId:e})=>e,channel:({channelInternalId:e})=>e,subChannel:({subChannelId:e})=>e,channelUsers:({channelId:e,userId:t})=>`${e}#${t}`,archivedChannel:({channelId:e})=>e,message:({messageId:e,referenceId:t})=>null!=t?t:e,messagePreviewChannel:({channelId:e})=>`${e}`,messagePreviewSubChannel:({subChannelId:e})=>`${e}`,channelUnreadInfo:({channelId:e})=>e,subChannelUnreadInfo:({subChannelId:e})=>e,channelUnread:({channelId:e})=>e,channelMarker:({entityId:e,userId:t})=>`${e}#${t}`,subChannelMarker:({entityId:e,feedId:t,userId:n})=>`${e}#${t}#${n}`,messageMarker:({feedId:e,contentId:t,creatorId:n})=>`${e}#${t}#${n}`,feedMarker:({feedId:e,entityId:t})=>`${e}#${t}`,userMarker:({userId:e})=>e,community:({communityId:e})=>e,category:({categoryId:e})=>e,communityUsers:({communityId:e,userId:t})=>`${e}#${t}`,post:({postId:e})=>e,comment:({commentId:e})=>e,commentChildren:({commentId:e})=>e,poll:({pollId:e})=>e,reaction:({referenceType:e,referenceId:t})=>`${e}#${t}`,reactor:({reactionId:e})=>e,stream:({streamId:e})=>e,streamModeration:({streamId:e})=>e,follow:({from:e,to:t})=>`${e}#${t}`,followInfo:({userId:e})=>e,followCount:({userId:e})=>e,feed:({targetId:e,feedId:t})=>`${e}#${t}`,story:({referenceId:e})=>e,storyTarget:({targetId:e})=>e,ad:({adId:e})=>e,advertiser:({advertiserId:e})=>e,pin:({placement:e,referenceId:t})=>`${e}#${t}`,pinTarget:({targetId:e})=>e,notificationTrayItem:({_id:e})=>e,notificationTraySeen:({userId:e})=>e,invitation:({_id:e})=>e,joinRequest:({joinRequestId:e})=>e,room:({roomId:e})=>e,viewer:({userId:e})=>e,event:({eventId:e})=>e,eventResponse:({userId:e})=>e,product:({productId:e})=>e,feedMetadata:({postId:e})=>e},Ze=e=>Xe[e],et={users:"user",files:"file",roles:"role",stories:"story",storyTargets:"storyTarget",channels:"channel",messageFeeds:"subChannel",channelUsers:"channelUsers",archives:"archivedChannel",messages:"message",messagePreviewChannel:"messagePreviewChannel",messagePreviewSubChannel:"messagePreviewSubChannel",channelUnreadInfo:"channelUnreadInfo",subChannelUnreadInfo:"subChannelUnreadInfo",userEntityMarkers:"channelMarker",userFeedMarkers:"subChannelMarker",contentMarkers:"messageMarker",feedMarkers:"feedMarker",userMarkers:"userMarker",communities:"community",categories:"category",communityUsers:"communityUsers",posts:"post",postChildren:"post",comments:"comment",commentChildren:"comment",polls:"poll",reactors:"reactor",reactions:"reaction",videoStreamings:"stream",videoStreamingChildren:"stream",videoStreamModerations:"streamModeration",follows:"follow",followCounts:"followCount",feeds:"feed",ads:"ad",advertisers:"advertiser",pinTargets:"pinTarget",pins:"pin",notificationTrayItems:"notificationTrayItem",invitations:"invitation",joinRequests:"joinRequest",rooms:"room",events:"event",viewers:"viewer",eventResponses:"eventResponse",products:"product",feedMetadata:"feedMetadata"};function tt(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}const nt=e=>{const{log:t,cache:n}=Ye();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=Ae(t);return Re(e,n)})).map((e=>n.data[e]))},at=e=>{const{log:t,cache:n}=Ye();if(!n)return;t("cache/api/pullFromCache",e);const a=Te(e);return n.data[a]?n.data[a]:void 0},st=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:s}=Ye();if(!s)return!1;a("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&s.persistIf&&(n.offline=s.persistIf(e,t));const o=Te(e);return s.data[o]=Object.assign({key:e,data:t},n),!0},ot=(e,t,n)=>{const{log:a,cache:s}=Ye();if(!s)return!1;a("cache/api/mergeInCache",{key:e,mutation:t});const o=at(e);if(!o)return!1;const i="function"==typeof t?t(o.data):Object.assign(Object.assign({},o.data),t);return r=o.data,!("updatedAt"in(c=i)&&"updatedAt"in r&&new Date(c.updatedAt)<new Date(r.updatedAt))&&(st(e,i,n),!0);var r,c},it=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:s}=Ye();if(!s)return!1;a("cache/api/upsertInCache",{key:e,data:t,options:n});return at(e)?ot(e,t,n):st(e,t,n)},rt=(e,t=!1)=>{const{log:n,cache:a}=Ye();if(!a)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(a.data).map((e=>Ae(e))).filter((t=>Re(e,t))).map((e=>rt(e,!0))).every((e=>e));const s=Te(e);return s in a.data&&(delete a.data[s],!0)},ct=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,dt=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,lt=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,ut=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;if("community"===e.type)return!0;const s=Ze("channelUsers")({channelId:e.channelPublicId,userId:n}),o=null===(a=at(["channelUsers","get",s]))||void 0===a?void 0:a.data;return"member"===t?o&&"none"!==o.membership:!o||"none"===o.membership})),ht=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var a;const s=null===(a=at(["feed","get",Ze("feed")({targetId:e,feedId:n})]))||void 0===a?void 0:a.data;return s&&s.feedType===t})),mt=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;const s=Ze("communityUsers")({communityId:e.communityId,userId:n}),o=null===(a=at(["communityUsers","get",s]))||void 0===a?void 0:a.data;return"member"===t?o&&"member"===o.communityMembership:!o||"none"!==o.communityMembership})),gt=(e,t)=>e.reduce(((e,n)=>{var a;if(null==t?void 0:t.includes(n.dataType))return[...e,n];if(((null==n?void 0:n.children)||[]).length>0){const s=null===(a=at(["post","get",n.children[0]]))||void 0===a?void 0:a.data;return(null==t?void 0:t.includes(null==s?void 0:s.dataType))?e:[...e,n]}return e}),[]),pt=(e,t)=>{const n=new RegExp(t,"i");return e.filter((e=>{var t;return!!e.userId.match(n)||e.user&&(null===(t=e.user.displayName)||void 0===t?void 0:t.match(n))}))},yt=()=>{var e;const{userId:t}=Ye(),n=new Set;return(null!==(e=nt(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&(e.from===t||e.to===t))).forEach((e=>{n.add(e.from===t?e.to:e.from)})),n},vt=e=>{const t=yt();return 0===t.size?e:e.filter((e=>{var n,a;if(t.has(e.postedUserId))return!1;return!(null!==(a=null===(n=e.mentionees)||void 0===n?void 0:n.flatMap((e=>"user"===e.type?e.userIds:[])))&&void 0!==a?a:[]).some((e=>t.has(e)))}))},ft=e=>{const t=yt();return 0===t.size?e:e.filter((e=>!t.has(e.userId)))},bt=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,It=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,Ct=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),wt=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),St=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),Ot=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Tt=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),At=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf(),Rt=e=>{if(void 0===e)return;const t=new Date(e).valueOf();if(!Number.isNaN(t))return e;console.warn("untilAt is an invalid Date — ignoring, pagination will not be bounded")},Pt=(e,t,n)=>{const a=new Date(e).valueOf(),s=new Date(t).valueOf();return"firstCreated"===n?a>=s:a<=s};let Dt=null;const Ut=()=>{if(!Dt)throw new Qe("Connect client first",8e5,"fatal");return Dt},kt=e=>{Dt={_id:e._id,userId:e.userId,path:e.path}};let jt,Et=[];const Mt=e=>{clearTimeout(jt),Et.push(e),jt=setTimeout((()=>{Et.forEach((e=>e())),Et=[]}),0)},qt=["connect","message","disconnect","error","close","end","reconnect","video-streaming.didStart","video-streaming.didRecord","video-streaming.didStop","video-streaming.didFlag","video-streaming.didTerminate","video-streaming.viewerDidBan","video-streaming.viewerDidUnban","liveReaction.created"],xt=(e,t,n,a)=>{const{log:s,emitter:o}=e,i=Date.now();s(`${t}(tmpid: ${i}) > listen`);const r=(...e)=>{s(`${t}(tmpid: ${i}) > trigger`,e);try{a(...e)}catch(e){s(`${t}(tmpid: ${i}) > error`,e)}};return o.on(n,r),()=>{s(`${t}(tmpid: ${i}) > dispose`),o.off(n,r)}},Nt=(e,t)=>{const{emitter:n}=Ye();Mt((()=>{n.emit(e,t)}))};let Kt,Ft;async function _t(){var e;const{mqtt:t,emitter:n,token:a}=Ye();if(!t)return;const s=null!==(e=null==a?void 0:a.accessToken)&&void 0!==e?e:"",o=Ut();Kt===s&&Ft===o._id||(Kt=s,Ft=o._id,await t.connect({accessToken:Kt,userId:Ft}),((e,t)=>{qt.forEach((n=>{null==e||e.on(n,((...e)=>{t.emit(n,1===e.length?e[0]:e)}))})),e.on("message",((e,n)=>{const a=JSON.parse(n.toString());t.emit(a.eventType,a.data)}))})(t,n))}const Bt=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=at(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),$t=()=>{var e;const t=Ye();if(!t)throw new Qe("Connect client first",8e5,"fatal");const n=null===(e=at(["user","get",t.userId]))||void 0===e?void 0:e.data;return n?Bt(n):null};var Lt;e.SubscriptionLevels=void 0,(Lt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",Lt.POST="post",Lt.COMMENT="comment",Lt.POST_AND_COMMENT="post_and_comment",Lt.USER="user";const Qt=(e,t)=>{switch(t){case"post":return`${e}/post/+`;case"comment":return`${e}/post/+/comment/+`;case"post_and_comment":return`${e}/post/#`;default:return e}},Vt=e=>e.path.split("/user/")[0],Jt=()=>{const e=Ut();return`${Vt(e)}/membership/${e._id}/+/+`},Ht=()=>{const e=Ut();return`${Vt(e)}/membership/+/${e._id}/+`},Gt=({channelId:e,subChannelId:t})=>{const n=Ut();return`${Vt(n)}/marker/channel/${e}/message/${t}`},zt=()=>Vt(Ut()),Yt=()=>{const e=Ut();return`${Vt(e)}/smartfeed/${e._id}/channels`},Wt=()=>{const e=Ut();return`${Vt(e)}/smartfeed/${e._id}/messagefeeds`},Xt=()=>{const e=Ut();return`${Vt(e)}/smartfeed/${e._id}/messages`},Zt=()=>{const e=Ut();return`${Vt(e)}/videostreaming`};function en(e,t){const{mqtt:n}=Ye();return n?(_t(),n.subscribe(e,t)):()=>null}var tn;const nn="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:an={}}=nn,sn="production"===(null===(tn=an.env)||void 0===tn?void 0:tn.NODE_ENV),on={EU:"eu",SG:"sg",US:"us"},rn={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function cn(e,t){return rn[e].replace("{region}",t)}class dn{constructor(){this._listener=new Map}onNetworkActivities(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setNetworkActivities(e,t){this._listener.forEach((n=>n(e,t)))}destroy(){this._listener.clear()}}let ln;var un,hn=()=>(ln||(ln=new dn),ln);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(un||(un={}));let mn=new AbortController;const gn=e=>{switch(e){case un.UserGlobalBanned:throw new Qe(e,400312,"fatal");case un.UserDeleted:throw new Qe(e,400100,"fatal");case un.TokenExpired:throw Nt("tokenExpired","tokenExpired"),new Qe(e,800403,"fatal");default:throw new Qe("Request Aborted",8e5,"error")}};let pn=0;const yn=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=C.default.create({baseURL:e,httpAgent:new w.default(t),httpsAgent:new o.HttpsAgent(t),signal:mn.signal});return n.defaults.withCredentials=!1,n.interceptors.request.use((e=>{if("/api/v5/sessions"===e.url)return e;if(e.metadata){const{tokenExpiry:t,isGlobalBanned:n,isUserDeleted:a}=e.metadata;n&&(mn.abort(),gn(un.UserGlobalBanned)),a&&(mn.abort(),gn(un.UserDeleted))}return e})),n.interceptors.response.use((e=>{var t;const n=new Headers;Object.entries(e.headers).forEach((([e,t])=>{"string"==typeof t&&n.append(e,t)}));const a=(e.config.baseURL||"")+(e.config.url||""),s=null===(t=e.config.method)||void 0===t?void 0:t.toUpperCase(),o={method:s,headers:e.config.headers};return"GET"!==s&&"HEAD"!==s&&(o.body=e.config.data),hn().setNetworkActivities(new Request(a,o),{data:e.data,status:e.status,statusText:e.statusText,headers:n}),e}),(e=>{var t,n,a;const{response:s}=e;if(400100===(null==s?void 0:s.data.code)&&Nt("tokenTerminated","terminated"),400323===(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.code))throw function(){const e=Date.now();e-pn<2e3||(pn=e,Nt("visitorUsageLimitReached",void 0))}(),new Qe("Visitor usage limit exceeded",400323,"error");if((null===(n=null==s?void 0:s.data)||void 0===n?void 0:n.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new Je(e.code);if("error"===e.status)throw new Ve(e.message,e.code,"error")})(null==s?void 0:s.data),mn.signal.aborted)throw e;throw new Error(null!==(a=null==s?void 0:s.data)&&void 0!==a?a:e)})),n.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},n};class vn{constructor(){this._sessionState="notLoggedIn",this._listener=new Map}onSessionStateChange(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setSessionState(e,t){this._sessionState!==e&&(this._sessionState=e,this._listener.forEach((n=>n(e,t))))}destroy(){this._listener.clear()}}let fn;var bn=()=>(fn||(fn=new vn),fn);const In=e=>bn().onSessionStateChange(e),Cn={[e.AmityAutoSubscription.NETWORK]:[zt],[e.AmityAutoSubscription.CHAT]:[Yt,Wt,Xt],[e.AmityAutoSubscription.LIVESTREAM]:[Zt],[e.AmityAutoSubscription.BLOCK]:[Jt,Ht]},wn=[e.AmityAutoSubscription.CHAT,e.AmityAutoSubscription.NETWORK,e.AmityAutoSubscription.LIVESTREAM,e.AmityAutoSubscription.BLOCK],Sn=Object.values(e.AmityAutoSubscription);class On{constructor(){this.refCountByFeature=new Map,this.disposers=new Map,this.seed()}seed(){this.refCountByFeature.clear(),wn.forEach((e=>this.refCountByFeature.set(e,1)))}isActive(e){var t;return(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)>0}subscribeTopics(e){this.unsubscribeTopics(e),this.disposers.set(e,Cn[e].map((e=>en(e()))))}unsubscribeTopics(e){var t;(null!==(t=this.disposers.get(e))&&void 0!==t?t:[]).forEach((e=>e())),this.disposers.delete(e)}initialize(){Sn.forEach((e=>{this.isActive(e)&&this.subscribeTopics(e)}))}subscribe(e){var t;const n=(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)+1;this.refCountByFeature.set(e,n),1===n&&this.subscribeTopics(e)}unsubscribe(e){var t;const n=Math.max(0,(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)-1);this.refCountByFeature.set(e,n),0===n&&this.unsubscribeTopics(e)}subscriptions(){return Sn.map((e=>({feature:e,isActive:this.isActive(e),isSystem:!0,topicCount:Cn[e].length})))}reset(){Sn.forEach((e=>this.unsubscribeTopics(e))),this.disposers.clear(),this.seed()}}let Tn=null;const An=()=>(Tn||(Tn=new On),Tn);class Rn{constructor(){this.store={},this.store={}}clear(){this.store={}}getItem(e){return this.store[e]||null}setItem(e,t){this.store[e]=String(t)}removeItem(e){delete this.store[e]}get length(){return Object.keys(this.store).length}key(e){return Object.keys(this.store)[e]||null}}const Pn=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new Rn},Dn=async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await O.default.setItem(e,t),!0):new Promise((n=>{Pn().localStorage.setItem(e,t),n(!0)})),Un=async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){return await O.default.getItem(e)}return new Promise((t=>{t(Pn().localStorage.getItem(e))}))},kn=()=>T.default.v4().toString();let jn=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=kn(),t={},n=new BroadcastChannel("amity_ts_sdk");let a;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:s})=>{s.tabId!==e&&("startup"===s.type&&n.postMessage({type:"identify",tabId:e,tabIndex:jn}),"identify"===s.type&&void 0!==s.tabIndex&&s.tabId&&(t[s.tabId]=s.tabIndex,a||(a=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(jn=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const En=async()=>{var e;const t=`${null!==(e=Ye().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await Un(t);if(n)return n;const a=`ascWebSdk#${kn()}`;return await Dn(t,a),a},Mn=()=>{const e=(()=>{var e,t;return(null===(e=an.versions)||void 0===e?void 0:e.node)?an.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:me}},qn=1e3;var xn;!function(e){e[e.IDENTIFIER_REJECTED=2]="IDENTIFIER_REJECTED",e[e.CLIENT_IDENTIFIER_NOT_VALID=133]="CLIENT_IDENTIFIER_NOT_VALID",e[e.BAD_USERNAME_OR_PASSWORD=134]="BAD_USERNAME_OR_PASSWORD",e[e.NOT_AUTHORIZED=135]="NOT_AUTHORIZED"}(xn||(xn={}));const Nn=e=>{let t,n="disconnected";const a=new Set,s=e=>{n!==e&&(n=e,a.forEach((t=>{t(e)})))},o=new Map;function i(e,n,a){const s=(t,s)=>{var r;if(t||128===(null===(r=null==s?void 0:s[0])||void 0===r?void 0:r.qos))if(n<2){const t=Math.min(2**n*1e3,5e3);console.warn(`Failed to subscribe to topic ${e} (attempt ${n+1}/3). Retrying in ${t}ms.`);const s=setTimeout((()=>{i(e,n+1,a)}),t);o.set(e,{timer:s,callback:a})}else{o.delete(e);const n=t?new Qe(t.message,8e5,"error"):new Je(8e5,"error");console.warn(`Failed to subscribe to topic ${e} after 3 attempts`,n),null==a||a(n)}else o.delete(e),console.log(`Subscribed to topic ${e}`),null==a||a()};t?t.subscribe(e,{qos:0},s):s(new Error("No connection to broker"),[])}return{connect:async function(n){const a=await(async e=>`mqttjs_${await En()}_${e}_${jn}`)(n.userId);return s("connecting"),t&&(s("disconnecting"),t.removeAllListeners(),t.on("error",(e=>{console.warn("MQTT discarded connection error:",null==e?void 0:e.message)})),t.end(!0)),t=S.default.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:5,reconnectPeriod:qn,resubscribe:!0,keepalive:30,properties:{sessionExpiryInterval:1800}},e)}({username:n.userId,password:n.accessToken,clientId:a})),t.on("connect",(()=>{t.options.reconnectPeriod=qn,s("connected"),An().initialize()})),t.on("error",(e=>{switch("code"in e?e.code:void 0){case 2:case 133:case 134:case 135:t.end(),s("disconnected")}})),t.on("reconnect",(()=>{s("reconnecting"),t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||qn),8e3)})),t.on("close",(()=>{o.forEach((({timer:e})=>clearTimeout(e))),o.clear()})),new Promise((e=>t.once("connect",(()=>e()))))},async disconnect(e){if(this.connected)return(null==e?void 0:e.endSession)?new Promise((e=>null==t?void 0:t.end(!1,{reasonCode:0,properties:{sessionExpiryInterval:0}},(()=>e())))):new Promise((e=>null==t?void 0:t.end(!0,void 0,(()=>e()))))},reconnect:async()=>new Promise((e=>{null==t||t.reconnect(),e()})),listen:e=>(a.add(e),n&&e(n),()=>{a.delete(e)}),get connected(){return!!(null==t?void 0:t.connected)},on(e,n){null==t||t.on(e,n)},once(e,n){null==t||t.once(e,n)},off(e,n){void 0!==n?null==t||t.off(e,n):null==t||t.removeAllListeners(e)},removeAllListeners(){null==t||t.removeAllListeners()},subscribe(e,t){return i(e,0,t),()=>this.unsubscribe(e)},unsubscribe(e){var n;const a=o.get(e);if(void 0!==a){clearTimeout(a.timer),o.delete(e);const t=new Qe("Subscription retry cancelled due to unsubscribe call",8e5,"error");null===(n=a.callback)||void 0===n||n.call(a,t)}null==t||t.unsubscribe(e)}}},Kn=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t},Fn=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,a])=>{const s=et[e];if(!s)return;const o=Ze(s);o&&a&&a.forEach((e=>{(n?st:it)([s,"get",o(e)],e,t)}))}))},_n=(e,t)=>{const{log:n,cache:a}=Ye(),s=[e,Se,t],o={cachedAt:Date.now()};a&&(n("cache/api/pushToTombstone",{cacheKey:s,data:o}),rt([e,"get",t],!0),st(s,o))};function Bn(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.indexOf(a)<0&&(n[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(a=Object.getOwnPropertySymbols(e);s<a.length;s++)t.indexOf(a[s])<0&&Object.prototype.propertyIsEnumerable.call(e,a[s])&&(n[a[s]]=e[a[s]])}return n}const $n=(e,t="userId",n="user")=>{var a;return null!==(a=null==e?void 0:e.map((e=>((e,t="userId",n="user")=>e[n]?e:Object.assign({get[n](){var n;if(!Ye().cache)return;return(null===(n=at(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==a?a:e},Ln=(e,t,n="userId",a="user")=>{const s=e,o=t,i=s[o],r=Bn(s,["symbol"==typeof o?o:o+""]),c=$n(i,n,a);return Object.assign(Object.assign({},r),{[t]:c})};function Qn(e){return e.map((e=>{var{isMentioned:t}=e,n=Bn(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function Vn(e){return Qn(e)}function Jn(e){return Qn(e)}const Hn=e=>{var t,n;return null!==(n=null===(t=at(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Gn=e=>new Date(e).getTime(),zn=e=>{var t,n;return null!==(n=null===(t=at(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Yn=e=>{var t;const n=e.messagePreviewId?zn(e.subChannelId):null,a=n?Object.assign(Object.assign({},n),{user:null===(t=at(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:a})},Wn=e=>{var t,n;const a={messagePreviewSubChannel:null!==(n=null===(t=e.messages)||void 0===t?void 0:t.map((t=>(t=>{var n;const a=null===(n=e.messageFeeds)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:o,messageId:i,creatorPublicId:r,data:c,dataType:d,isDeleted:l,segment:u,createdAt:h,updatedAt:m}=t;return{messagePreviewId:i,channelId:s,subChannelId:o,data:c,dataType:d,isDeleted:l,segment:u,creatorId:r,createdAt:h,updatedAt:m,subChannelName:null==a?void 0:a.name,subChannelUpdatedAt:null==a?void 0:a.updatedAt}})(t))))&&void 0!==n?n:[]};Fn(a)};function Xn(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function Zn(e,t,n){st(["subChannel","get",e],Xn(t,n))}const ea=(e,t)=>{const{log:n,cache:a}=Ye(),s=[e,Se,t];if(!a)return;n("cache/api/isInTombstone",s);const o=at(s),{lifeSpan:i}=Be("cache_then_server",18e4);if(o&&Fe(o.data,i))throw new Ve("Item not found!",400400,"error")},ta=e=>{var t;const n=["channelUnreadInfo","get",e],a=null===(t=at(n))||void 0===t?void 0:t.data,s=nt(["subChannelUnreadInfo","get"]);let o=0,i=!1;if(s&&(null==s?void 0:s.length)>0){const t=null==s?void 0:s.filter((({data:t})=>t.channelId===e&&!t.isDeleted));o=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),i=t.some((({data:e})=>e.isMentioned))}const r=Object.assign(Object.assign({},null!=a?a:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:o,isMentioned:i});return st(n,r),r},na=e=>{const{feedMarkers:t,userFeedMarkers:n}=e;if(t.length>0&&n.length>0){const e=[],a=new Map(t.map((e=>[e.feedId,e])));n.forEach((t=>{const n=a.get(t.feedId);if(n&&n.feedId===t.feedId){const a=n.lastSegment-t.readToSegment,s={subChannelId:n.feedId,channelId:n.entityId,readToSegment:t.readToSegment,lastSegment:n.lastSegment,lastMentionSegment:t.lastMentionSegment,unreadCount:Math.max(0,a),isMentioned:t.isMentioned,isDeleted:n.isDeleted,createdAt:t.createdAt,updatedAt:t.updatedAt};Fn({subChannelUnreadInfo:[s]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{ta(e)}))}},aa=async()=>{const e=Ye();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:n}=t,a=e.cache&&Date.now();e.cache&&Fn({userMarkers:n},{cachedAt:a}),Nt("local.userMarker.fetched",{userMarkers:n});return{data:n.reduce(((e,t)=>null==e||new Date(e.lastSyncAt).getTime()<new Date(t.lastSyncAt).getTime()?t:e),void 0),cachedAt:a}},sa=e=>{var t,n;const a=null===(t=at(["message","get",e]))||void 0===t?void 0:t.data;if(a)return a;const s=nt(["message","get"]);return null===(n=null==s?void 0:s.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data},oa=e=>!0===e&&void 0;function ia(e,t,n){var a,s;if(n)return n.hasMentioned;const o=Ye();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(a=at(["subChannelUnreadInfo","get",t]))||void 0===a?void 0:a.data;return!!e&&e.isMentioned}const i={entityId:e,feedId:t,userId:Ut()._id},r=null===(s=at(["subChannelMarker","get",Ze("subChannelMarker")(i)]))||void 0===s?void 0:s.data;return!!r&&r.hasMentioned}const ra=["broadcast","conversation","community"],ca=({channelType:e})=>ra.includes(e);function da(e){var{channelId:t,channelPublicId:n,channelType:a,childCount:s,creatorId:o,creatorPublicId:i,lastMessageId:r,lastMessageTimestamp:c,messageFeedId:d,name:l}=e,u=Bn(e,["channelId","channelPublicId","channelType","childCount","creatorId","creatorPublicId","lastMessageId","lastMessageTimestamp","messageFeedId","name"]);return Object.assign(Object.assign({get unreadCount(){return function(e,t,n){var a,s;if(n)return n.unreadCount;const o=Ye();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(a=at(["subChannelUnreadInfo","get",t]))||void 0===a?void 0:a.data;return e?e.isDeleted?0:e.unreadCount:0}const i={entityId:e,feedId:t,userId:Ut()._id},r=null===(s=at(["subChannelMarker","get",Ze("subChannelMarker")(i)]))||void 0===s?void 0:s.data;return r?r.unreadCount:0}(t,d)},get hasMentioned(){return ia(t,d)},get isMentioned(){return ia(t,d)}},u),{channelId:n,creatorId:i,displayName:l,lastActivity:c,latestMessageId:r,messageCount:s,subChannelId:d,isUnreadCountSupport:ca({channelType:a})})}function la(e,t,n){var a;const s=(e=>{var t,n,a;const s=null===(n=null===(t=nt(["message","get"]))||void 0===t?void 0:t.find((({data:t})=>t.messageId===e.messageId)))||void 0===n?void 0:n.data;return s?Object.assign(Object.assign(Object.assign({},s),e),{referenceId:null!==(a=s.referenceId)&&void 0!==a?a:e.referenceId}):e})(e),{channelPublicId:o,childCount:i,creatorPublicId:r,mentionedUsers:c,messageFeedId:d,myReactions:l,reactionCount:u,reactions:h,referenceId:m,segment:g,messageId:p,creatorId:y}=s,v=Bn(s,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let f;m&&(f=at(["message","get",m])),f||(f=at(["message","get",p]));const b=Object.assign(Object.assign({},v),{messageId:p,channelId:o,channelSegment:g,childrenNumber:i,creatorId:r,creatorPrivateId:e.creatorId,reactions:null!=h?h:{},myReactions:l||(null!==(a=null==f?void 0:f.data.myReactions)&&void 0!==a?a:[]),reactionsCount:u,subChannelId:d,uniqueId:f?f.data.uniqueId:p,referenceId:m,syncState:"synced"});return c&&(b.mentionees=c.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&n&&((e,t,n)=>{const a=Ye(),s=sa(e.messageId),o=(null==s?void 0:s.myReactions)||[];Object.assign(e,{myReactions:o});const i=t[0];i&&i.userId===a.userId&&("message.reactionAdded"!==n||o.includes(i.reactionName)||Object.assign(e,{myReactions:[...o,i.reactionName]}),"message.reactionRemoved"===n&&o.includes(i.reactionName)&&Object.assign(e,{myReactions:o.filter((e=>e!==i.reactionName))}))})(b,t,n),b}const ua={},ha=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Fn({messages:(a=e).messages.map((e=>la(e,a.reactions)))});const t=n.join("");ua[t]&&clearTimeout(ua[t]),ua[t]=setTimeout((()=>{try{(async e=>{const t=Ye();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:a,feedMarkers:s,userMarkers:o}=n,i=t.cache&&Date.now();t.cache&&Fn({contentMarkers:a,feedMarkers:s,userMarkers:o},{cachedAt:i}),Nt("local.feedMarker.fetched",{feedMarkers:s}),Nt("local.messageMarker.fetched",{contentMarkers:a}),Nt("local.userMarker.fetched",{userMarkers:o})})(n)}catch(e){}}),2e3)}var a;const{messageFeeds:s}=e,o=Bn(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,n;const a=null!==(n=null===(t=at(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},s=Bn(da(e),["unreadCount","isMentioned"]);Zn(e.messageFeedId,a,s)}))),Object.assign(Object.assign({},o),{messages:e.messages.map((n=>la(n,e.reactions,t)))})};function ma(e){var{subChannelId:t,mentionees:n,dataType:a,data:s}=e,o=Bn(e,["subChannelId","mentionees","dataType","data"]);return a===B.IMAGE||a===B.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:a,data:Object.assign({caption:""},s)},o):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:a,data:s},o)}function ga(e){var{sortBy:t,subChannelId:n,includingTags:a,excludingTags:s,includeDeleted:o,aroundMessageId:i,limit:r,type:c}=e,d=Bn(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const l=Object.assign(Object.assign({},d),{messageFeedId:n,isDeleted:oa(o),options:{sortBy:t,limit:r||ge,around:i}});return a&&(l.includeTags=a),c&&(l.dataType=c),s&&(l.excludeTags=s),l}function pa(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const ya=["broadcast","conversation","community"],va=({channelType:e})=>ya.includes(e),fa=async e=>{const t=e.messageFeeds.filter(va).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Fn({messageFeeds:e.messageFeeds.map((e=>da(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=Ye();n.log("channel/getSubChannelMarkers",e,t);const{data:a}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:Ee(t,"skiplimit")}}}),{paging:s}=a,o=Bn(a,["paging"]),{userEntityMarkers:i,userFeedMarkers:r,userMarkers:c,feedMarkers:d}=o;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&na({feedMarkers:d,userFeedMarkers:r});const l=Vn(i),u=Jn(r),h=n.cache&&Date.now();n.cache&&Fn({userEntityMarkers:l,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),Nt("local.channelMarker.fetched",{userEntityMarkers:l}),Nt("local.subChannelMarker.fetched",{userFeedMarkers:u}),Nt("local.userMarker.fetched",{userMarkers:c});const m=Me(s.next);return{data:u,cachedAt:h,prevPage:Me(s.previous),nextPage:m}})(t)}catch(e){}}Wn(e);const n=e.messageFeeds.map(da),a=e.messages.map((e=>la(e))),s=e.users.map(pa);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:a,users:s})};const ba=async e=>{const t=Ye();t.log("channel/getSubChannel",e),ea("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),a=await fa(n.data),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),Nt("local.message-feed.fetched",a),{data:a.messageFeeds[0],cachedAt:s}}catch(t){throw Pe(null==t?void 0:t.code)&&_n("subChannel",e),t}};ba.locally=e=>{const t=Ye();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=at(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ia=async e=>{var t;let n=null===(t=at(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await ba(e)).data),n},Ca=async e=>{const t=await(async()=>Ye().getMessagePreviewSetting(!1))(),{channelId:n,messageId:a,creatorId:s,createdAt:o,updatedAt:i,data:r,dataType:c,subChannelId:d,channelSegment:l,isDeleted:u}=e,h=await Ia(d);"no-message-preview"!==t?(e=>{var t;const n=null===(t=at(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Gn(n.createdAt)<=Gn(e.createdAt)})(e)&&(st(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:s,messagePreviewId:a,createdAt:o,updatedAt:i,subChannelId:d,data:r,dataType:c,segment:l,isDeleted:u,subChannelUpdatedAt:null==h?void 0:h.updatedAt,subChannelName:null==h?void 0:h.displayName}),Zn(e.subChannelId,h,{lastActivity:o,messagePreviewId:a})):Gn(h.lastActivity)<Gn(o)&&Zn(e.subChannelId,h,{lastActivity:o})},wa=async e=>{var t;const{channelId:n,messageId:a,creatorId:s,createdAt:o,updatedAt:i,data:r,dataType:c,subChannelId:d,channelSegment:l,isDeleted:u}=e,h=null===(t=at(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Ia(d);st(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:s,messagePreviewId:a,createdAt:o,updatedAt:i,subChannelId:d,data:r,dataType:c,segment:l,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Sa=async e=>{const{channelId:t,messageId:n,creatorId:a,createdAt:s,updatedAt:o,data:i,dataType:r,subChannelId:c,channelSegment:d,isDeleted:l}=e;if((e=>{var t;const n=null===(t=at(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Gn(n.createdAt)<=Gn(e.createdAt)})(e)){const u=await Ia(c);st(["messagePreviewChannel","get",e.channelId],{channelId:t,creatorId:a,messagePreviewId:n,createdAt:s,updatedAt:o,subChannelId:c,data:i,dataType:r,segment:d,isDeleted:l,subChannelUpdatedAt:null==u?void 0:u.updatedAt,subChannelName:null==u?void 0:u.displayName})}},Oa=async e=>{var t;const{channelId:n,messageId:a,creatorId:s,createdAt:o,updatedAt:i,data:r,dataType:c,subChannelId:d,channelSegment:l,isDeleted:u}=e,h=null===(t=at(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Ia(d);st(["messagePreviewChannel","get",e.channelId],{channelId:n,creatorId:s,messagePreviewId:a,createdAt:o,updatedAt:i,subChannelId:d,data:r,dataType:c,segment:l,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Ta=async e=>{var t,n,a,s;const{channelId:o,subChannelId:i}=e,r=null===(t=at(["messagePreviewChannel","get",o]))||void 0===t?void 0:t.data;if((null==r?void 0:r.subChannelId)===i){const e=null===(n=at(["subChannel","get",i]))||void 0===n?void 0:n.data;st(["messagePreviewChannel","get",o],Object.assign(Object.assign({},r),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const c=null===(a=at(["messagePreviewSubChannel","get",i]))||void 0===a?void 0:a.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(s=at(["subChannel","get",i]))||void 0===s?void 0:s.data;st(["messagePreviewSubChannel","get",i],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Aa=["broadcast","conversation","community"],Ra=({type:e})=>Aa.includes(e);function Pa(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:a}=e;const s=null===(n=at(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==s?void 0:s.messagePreviewId)&&!t.isMessagePreviewUpdated&&(a=s.messagePreviewId),Object.assign(Object.assign({},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:Ra(e),messagePreviewId:a})}const Da=(e,t={isMessagePreviewUpdated:!0})=>{Fn({channels:e.channels.map((e=>Pa(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Ua=async(e,t={isMessagePreviewUpdated:!0})=>{const n=Ye(),a=await n.getMessagePreviewSetting(!1);if(t.isMessagePreviewUpdated&&"no-message-preview"!==a&&e.messagePreviews&&e.messagePreviews.length>0&&(e=>{var t;const n=(null!==(t=e.messagePreviews)&&void 0!==t?t:[]).map((t=>{var n;const a=null===(n=e.messageFeedsInfo)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:o,data:i,dataType:r,isDeleted:c,segment:d,creatorPublicId:l,createdAt:u,updatedAt:h}=t;return{channelId:s,subChannelId:o,data:i,dataType:r,isDeleted:c,segment:d,creatorId:l,createdAt:u,updatedAt:h,subChannelName:null==a?void 0:a.name,messagePreviewId:null==a?void 0:a.messagePreviewId,subChannelUpdatedAt:null==a?void 0:a.updatedAt}})).filter((e=>{var t;const n=null===(t=at(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Gn(n.createdAt)<=Gn(e.createdAt)}));0!==n.length&&Fn({messagePreviewChannel:n})})(e),n.useLegacyUnreadCount)(({currentUserId:e,channels:t,channelUsers:n})=>{var a,s;const o=[];for(let i=0;i<t.length;i+=1)if(Ra(t[i])){const r=["channelUnread","get",t[i].channelId],c=n.find((n=>n.channelId===t[i].channelId&&n.userId===e)),d=null===(a=at(r))||void 0===a?void 0:a.data,l=Math.max(null!==(s=null==d?void 0:d.lastSegment)&&void 0!==s?s:0,t[i].messageCount);let u=null,h=null,m=0,g=!1;if(c){const e=c.readToSegment,t=c.lastMentionedSegment;u="number"==typeof(null==d?void 0:d.readToSegment)&&("number"!=typeof e||d.readToSegment>e)?d.readToSegment:null!=e?e:null,h="number"==typeof(null==d?void 0:d.lastMentionedSegment)&&("number"!=typeof t||d.lastMentionedSegment>t)?d.lastMentionedSegment:null!=t?t:null;const n=null!=u?u:0;m=Math.max(l-n,0),g="number"==typeof h&&n<h}const p={channelId:t[i].channelId,lastSegment:l,readToSegment:u,lastMentionedSegment:h,unreadCount:m,isMentioned:g,isDeleted:t[i].isDeleted||!1};st(r,p),o.push(p)}o.length>0&&Nt("local.channelUnread.updated",o)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(Ra).map((({channelInternalId:e})=>e));if(n.length>0){Da(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=Ye();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:a,userMarkers:s}=n,o=Vn(a),i=t.cache&&Date.now();return t.cache&&Fn({userEntityMarkers:o,userMarkers:s},{cachedAt:i}),Nt("local.channelMarker.fetched",{userEntityMarkers:o}),Nt("local.userMarker.fetched",{userMarkers:s}),{data:o,cachedAt:i}})(n)}catch(e){}}}const s=e.channels.map((e=>Pa(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),o=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(Ye().cache)return(null===(e=at(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),i=e.users.map(pa),r=Bn(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},r),{users:i,channels:s,channelUsers:o})},ka=async e=>{const t=Ye();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return Nt("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},ja=async e=>{const t=Ye(),n=await ka(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:a,userFeedMarkers:s}=n;na({feedMarkers:a,userFeedMarkers:s}),t.log("channel/prepareUnreadCountInfo",e.channels)},Ea=(e,t)=>{var n,a,s,o;const i=Ye();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=at(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===n?void 0:n.isMentioned)&&void 0!==a&&a:void 0!==(null==t?void 0:t.hasMentioned)?null==t?void 0:t.hasMentioned:null!==(o=null===(s=(e=>{var t;const n={entityId:e,userId:Ut()._id};return null===(t=at(["channelMarker","get",Ze("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===s?void 0:s.hasMentioned)&&void 0!==o&&o},Ma=(e,t)=>{var n,a,s,o,i;const r=Ye();return r.isUnreadCountEnabled&&r.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=at(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===n?void 0:n.unreadCount)&&void 0!==a?a:0:(null==t?void 0:t.isDeleted)?0:null!==(i=null!==(s=null==t?void 0:t.unreadCount)&&void 0!==s?s:null===(o=(e=>{var t;const n={entityId:e,userId:Ut()._id};return null===(t=at(["channelMarker","get",Ze("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===o?void 0:o.unreadCount)&&void 0!==i?i:0},qa=e=>{var t;return null===(t=at(["channelUnread","get",e]))||void 0===t?void 0:t.data},xa=e=>{const t=Ye(),n=Bn(e,["messageCount"]);return Xn(n,{get unreadCount(){var e,t;return null!==(t=null===(e=qa(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Ma(n)},get isMentioned(){var e,a;return t.useLegacyUnreadCount?null!==(a=null===(e=qa(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==a&&a:Ea(n)}})},Na=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],a=null===(t=at(n))||void 0===t?void 0:t.data;return a?Bt(a):void 0})()}}),Ka=e=>{const t=Ye();t.log("channel/getMyMembership.locally");const n=at(["channelUsers","get",`${e}#${t.userId}`]);if(!n)throw new Ve("Item not found!",400400,"error");return{data:n.data,cachedAt:n.cachedAt}};function Fa(e,t){if(null==e||null==t)return e===t;if(e.constructor!==t.constructor)return!1;if(e instanceof Function)return e===t;if(e instanceof RegExp)return e===t;if(e===t||e.valueOf()===t.valueOf())return!0;if(Array.isArray(e)&&e.length!==t.length)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Fa(e[n],t[n]))return!1;return!0}if(e instanceof Date)return!1;if(!(e instanceof Object))return!1;if(!(t instanceof Object))return!1;const n=Object.keys(e);return Object.keys(t).every((e=>-1!==n.indexOf(e)))&&n.every((n=>Fa(e[n],t[n])))}const _a=[];let Ba=null;const $a=e=>{if(0===_a.length){const e=Ye();Ba=xt(e,"onChannelCreated","channel.created",(async e=>{const t=await Ua(e);Fn(t),_a.forEach((e=>e(t.channels[0])))}))}return _a.push(e),()=>(e=>{const t=_a.indexOf(e);t>-1&&_a.splice(t,1),0===_a.length&&(null==Ba||Ba())})(e)},La=[],Qa=[],Va=e=>{const t=Ye();if(0===La.length){const e=async e=>{const t=await Ua(e);Fn(t),La.forEach((e=>e(t.channels[0])))};Qa.push(xt(t,"onChannelUpdated","channel.updated",e)),Qa.push(xt(t,"onChannelUpdated","local.channel.updated",(e=>La.forEach((t=>t(e.channels[0]))))))}return La.push(e),()=>(e=>{const t=La.indexOf(e);t>-1&&La.splice(t,1),0===La.length&&Qa.forEach((e=>e()))})(e)},Ja=e=>{const t=nt(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{st(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Ha=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=at(n))||void 0===t?void 0:t.data)&&rt(n)},Ga=[];let za=null;const Ya=e=>{if(0===Ga.length){const e=Ye(),t=async t=>{const n=await Ua(t),a=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,s=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(a)Ja(e.channelId),Ha(e.channelId);else if(s){const t=["channelUnread","get",e.channelId],n=at(t);n&&st(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Fn(n),Ga.forEach((e=>e(n.channels[0])))};za=xt(e,"onChannelDeleted","channel.deleted",t)}return Ga.push(e),()=>(e=>{const t=Ga.indexOf(e);t>-1&&Ga.splice(t,1),0===Ga.length&&(null==za||za())})(e)},Wa=[];let Xa=null;const Za=e=>{if(0===Wa.length){const e=Ye();Xa=xt(e,"onChannelJoined","channel.joined",(async e=>{const t=await Ua(e),{channels:n,channelUsers:a}=t;Fn(t),Wa.forEach((e=>e(n[0],a[0])))}))}return Wa.push(e),()=>(e=>{const t=Wa.indexOf(e);t>-1&&Wa.splice(t,1),0===Wa.length&&(null==Xa||Xa())})(e)},es=[];let ts=null;const ns=e=>{if(0===es.length){const e=Ye(),t=async t=>{const{userId:n}=Ye(),{channelUsers:a}=t,s=a.some((e=>e.userId===n)),o=await Ua(t,{isMessagePreviewUpdated:s}),i=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,r=e.useLegacyUnreadCount;s&&o.channels.forEach((e=>{i?(Ja(e.channelId),Ha(e.channelId)):r&&rt(["channelUnread","get",e.channelId])}));const{channels:c,channelUsers:d}=o;Fn(o),es.forEach((e=>e(c[0],d[0])))};ts=xt(e,"onChannelLeft","channel.left",t)}return es.push(e),()=>(e=>{const t=es.indexOf(e);t>-1&&es.splice(t,1),0===es.length&&(null==ts||ts())})(e)},as=[];let ss=null;const os=e=>{if(0===as.length){const e=Ye(),t=async e=>{var t;it(["channel","get",e.channelId],{isMuted:Date.parse(e.muteTimeout)>Date.now()});const n=null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data;n&&as.forEach((e=>e(n)))};ss=xt(e,"onChannelMute","channel.setMuted",t)}return as.push(e),()=>(e=>{const t=as.indexOf(e);t>-1&&as.splice(t,1),0===as.length&&(null==ss||ss())})(e)},is=[];let rs=null;const cs=e=>{if(0===is.length){const e=Ye();rs=xt(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await Ua(e),{channels:n,channelUsers:a}=t;Fn(t),is.forEach((e=>e(n[0],a.find((e=>"member"===e.membership)))))}))}return is.push(e),()=>(e=>{const t=is.indexOf(e);t>-1&&is.splice(t,1),0===is.length&&(null==rs||rs())})(e)},ds=[];let ls=null;const us=e=>{if(0===ds.length){const e=Ye();ls=xt(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await Ua(e),{channels:n,channelUsers:a}=t;Fn(t),ds.forEach((e=>e(n[0],a[0])))}))}return ds.push(e),()=>(e=>{const t=ds.indexOf(e);t>-1&&ds.splice(t,1),0===ds.length&&(null==ls||ls())})(e)},hs=[];let ms=null;const gs=e=>{const t=Ye();return ms=xt(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await Ua(e),{channels:a,channelUsers:s}=n,o=s.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&o&&n.channels.forEach((e=>{Ja(e.channelId),Ha(e.channelId)})),Fn(n),hs.forEach((e=>e(a[0],s.find((e=>"banned"===e.membership)))))})),hs.push(e),()=>(e=>{const t=hs.indexOf(e);t>-1&&hs.splice(t,1),0===hs.length&&(null==ms||ms())})(e)},ps=[];let ys=null;const vs=e=>{if(0===ps.length){const e=Ye();ys=xt(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await Ua(e),{channels:n,channelUsers:a}=t;Fn(t),ps.forEach((e=>e(n[0],a.find((e=>"none"===e.membership)))))}))}return ps.push(e),()=>(e=>{const t=ps.indexOf(e);t>-1&&ps.splice(t,1),0===ps.length&&(null==ys||ys())})(e)},fs=[];let bs=null;const Is=e=>{if(0===fs.length){const e=Ye();bs=xt(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;fs.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return fs.push(e),()=>(e=>{const t=fs.indexOf(e);t>-1&&fs.splice(t,1),0===fs.length&&(null==bs||bs())})(e)},Cs=[];let ws=null;const Ss=e=>{if(0===Cs.length){const e=Ye();ws=xt(e,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async e=>{const{channels:t,channelUsers:n}=e;Cs.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return Cs.push(e),()=>(e=>{const t=Cs.indexOf(e);t>-1&&Cs.splice(t,1),0===Cs.length&&(null==ws||ws())})(e)},Os=e=>{const t=Ye();return xt(t,"onChannelArchived","local.channel.archived",(async t=>{e(t)}))},Ts=e=>{const t=Ye();return xt(t,"onChannelUnarchived","local.channel.unarchived",(async t=>{e(t)}))},As=[];let Rs=null;const Ps=e=>{if(0===As.length){const e=Ye(),t=async e=>{var t,n,a;e.userIds.forEach((t=>it(["channelUsers","get",`${e.channelId}#${t}`],{isMuted:Date.parse(e.muteTimeout)>Date.now()})));const s=null===(n=null===(t=nt(["channel","get"]))||void 0===t?void 0:t.find((({data:t})=>t.channelPublicId===e.channelId)))||void 0===n?void 0:n.data,o=null===(a=at(["channelUsers","get",`${e.channelId}#${e.userIds[0]}`]))||void 0===a?void 0:a.data;s&&o&&As.forEach((e=>e(s,o)))};Rs=xt(e,"onChannelUserMute","channel.setMutedUsers",t)}return As.push(e),()=>(e=>{const t=As.indexOf(e);t>-1&&As.splice(t,1),0===As.length&&(null==Rs||Rs())})(e)},Ds=e=>{var t;let n=[];if(["conversation","community"].includes(e.type)){const a=nt(["channelUsers","get"]);a&&(null==a?void 0:a.length)>0&&(n=(null!==(t=null==a?void 0:a.filter((({data:t})=>t.channelId===e.channelId&&"none"!==t.membership)))&&void 0!==t?t:[]).sort(((e,t)=>e.data.userInternalId.localeCompare(t.data.userInternalId))).slice(0,4).map((({data:e})=>Na(e))))}return Xn(e,{markAsRead:()=>(async e=>{const t=Ye();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:a,userEntityMarkers:s,userFeedMarkers:o}=n,i=Bn(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),r=t.cache&&Date.now(),c=Vn(s),d=Jn(o);return t.cache&&Fn(Object.assign({userMarkers:a,userEntityMarkers:c,userFeedMarkers:d},i),{cachedAt:r}),Nt("local.channelMarker.updated",{userEntityMarkers:c}),Nt("local.subChannelMarker.updated",{userFeedMarkers:d}),!0})(e.channelInternalId),previewMembers:n,myMembership:t=>((e,t)=>{const{_id:n}=Ut();if(!n)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:a,cache:s}=Ye();s||console.log("This observable object need the cache data!"),a(`liveMymembership(tmpid: ${Date.now()}) > listen`);const o=[];let i=!1;const r=e=>{t(Object.assign(Object.assign({},e),{data:e.data?Na(e.data):e.data}))},c=(t,n)=>{const{data:a}=Ka(e);Fa(void 0,a)||r({loading:!1,data:a})};return o.push(gs(c)),o.push(vs(c)),o.push(Ps(c)),(()=>{const t=_e((async()=>Ka(e)));$e(t,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{s===be?(r({data:t,origin:a,loading:!1,error:new Ve(fe,800800,"error")}),i=!0,o.forEach((e=>e()))):i||r({loading:n,data:t,origin:a,error:e}),e&&o.forEach((e=>e()))}))})(),()=>{o.forEach((e=>e()))}})(e.channelId,t),get avatar(){var t;if(!e.avatarFileId)return;return null===(t=at(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}})},Us=e=>Ds(xa((e=>{var t;const n=e.messagePreviewId?Hn(e.channelId):null,a=null===(t=at(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,s=n?Object.assign(Object.assign({},n),{user:a?Bt(a):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})})(e))),ks=async e=>{const t=Ye();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{Pe(null==t?void 0:t.code)&&_n("channel",e)})),t}const s=await Ua(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ja(a);const o=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:o}),Nt("local.channel.fetched",s.channels),{data:s.channels.map((e=>Us(e))),cachedAt:o}};ks.locally=e=>{var t,n;const a=Ye();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const s=null===(t=nt(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;const o=s.map((({data:e})=>e)),i=null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:o.map((e=>Us(e))),cachedAt:i.cachedAt}};const js=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let Es=!1;const Ms={},qs=async()=>{const e=Object.entries(Ms).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=Ye();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:a,userFeedMarkers:s,feedMarkers:o,userMarkers:i}=n,r=Vn(a),c=Jn(s),d=t.cache&&Date.now();return t.cache&&Fn({userEntityMarkers:r,userFeedMarkers:c,feedMarkers:o,userMarkers:i},{cachedAt:d}),Nt("local.feedMarker.fetched",{feedMarkers:o}),Nt("local.channelMarker.fetched",{userEntityMarkers:r}),Nt("local.subChannelMarker.fetched",{userFeedMarkers:c}),Nt("local.userMarker.fetched",{userMarkers:i}),!0})(e)},xs=()=>{Es=!1},Ns=()=>(Es=!0,In((e=>{"notLoggedIn"===e&&xs()})),()=>{xs()});js((async()=>{Es&&await qs()}),3e4);const Ks=async e=>{const t=Ye();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),a=await fa(n.data),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),Nt("local.message-feed.fetched",a),{data:a.messageFeeds,cachedAt:s}};Ks.locally=e=>{var t;const n=Ye();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const a=e.map((e=>at(["subChannel","get",e]))).filter(Boolean);if((null==a?void 0:a.length)<e.length)return;return{data:a.map((({data:e})=>e)),cachedAt:(null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const Fs=async(e=!0)=>{var t;const n=null===(t=at(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const a=await Kn();var s;return(s=a).messagePreview.enabled?s.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},_s=async()=>{var e;const t=await Fs();if(t===(null===(e=at(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;st(["MessagePreviewSetting"],t);const n=[],a=[];if("no-message-preview"===t){const e=nt(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{rt(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&a.push(t.subChannelId)}))}else if("message-preview-not-include-deleted"===t){const e=nt(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(rt(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&a.push(t.subChannelId))})),0!==n.length&&await ks(n),0!==a.length&&await Ks(a)}},Bs=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},$s=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/users");return t},Ls={mode:e.AmityLiveViewerCountMode.ALWAYS_SHOW,threshold:50},Qs=async()=>{var t,n;const a=Ye(),{data:s}=await a.http.get("/api/v3/network-settings/video-streaming"),o=null===(t=null==s?void 0:s.videoStreaming)||void 0===t?void 0:t.viewerCountDisplayMode,i=null===(n=null==s?void 0:s.videoStreaming)||void 0===n?void 0:n.viewerCountDisplayMinimum;return(r=o)!==e.AmityLiveViewerCountMode.ALWAYS_SHOW&&r!==e.AmityLiveViewerCountMode.HIDE_ENTIRELY&&r!==e.AmityLiveViewerCountMode.SHOW_ABOVE_MINIMUM||!(e=>"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=1e3)(i)?(a.log("client/getLiveViewerCountConfig","malformed videoStreaming settings, falling back to default",{mode:o,threshold:i}),Ls):{mode:o,threshold:i};var r},Vs=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/product");return t},Js=async()=>{var e,t;const n=Ye(),{data:a}=await n.http.get("/api/v3/network-settings/for-you-feed");return{forYouFeed:{enabled:null!==(t=null===(e=a.forYouFeed)||void 0===e?void 0:e.enabled)&&void 0!==t&&t}}},Hs=(e,t)=>{var n;const a=null===(n=at(["user","get",e]))||void 0===n?void 0:n.data;return!!a&&a.permissions.some((e=>e===t))},Gs=e=>{const{userId:t}=Ye();return{currentUser:()=>Hs(t,e),community:n=>((e,t,n)=>{var a;if(!e)return!1;const s=null===(a=at(["communityUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!s&&(!!s.permissions.some((e=>e===t))||Hs(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var a;if(!e)return!1;const s=null===(a=at(["channelUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!s&&(!!s.permissions.some((e=>e===t))||Hs(e,t))})(t,e,n)}},zs=async e=>{const t=Ye();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/allowlists/verify",{data:e});return n.success},Ys=async e=>{const t=Ye();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/blocklists/verify",{data:e});return n.success},Ws=async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Xs={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Zs=(e,t)=>{const n=Ye();n.log("client/api/setSessionState",e,t);const{sessionState:a}=n;if(a===e)return!1;if(!((e,t)=>Xs[e].includes(t))(a,e))throw new Qe(`Session state cannot change from ${a} to ${e}`,8e5,"error");return n.sessionState=e,bn().setSessionState(e,t),!0};function eo(e){return{users:e.users.map(pa),files:e.files}}const to=async e=>{const t=Ye();Zs("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getToken",e);const a=Mn(),{data:s}=await n.http.post("/api/v5/sessions",Object.assign(Object.assign({},e),{deviceInfo:a}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.upload.defaults.headers.common.Authorization=`Bearer ${n}`,t.upload.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:s},Zs("established"),Fn(eo({users:a,files:r})),{accessToken:n,users:a,userType:i}},no=async e=>{const t=Ye();Zs("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getVisitorToken",e);const a=Mn(),{data:s}=await n.http.post("/api/v5/sessions/visitor",Object.assign(Object.assign({},e),{deviceInfo:a}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:s},Zs("established"),Fn(eo({users:a,files:r})),{accessToken:n,users:a,userType:i}},ao=async()=>{var e;const t=Ye();return t.log("client/api/disconnectClient"),t.mqtt&&t.mqtt.connected&&await t.mqtt.disconnect({endSession:!0}),"established"===t.sessionState&&Zs("notLoggedIn"),t.emitter.all.clear(),null===(e=t.mqtt)||void 0===e||e.removeAllListeners(),t.userId=void 0,t.token=void 0,t.loginType=void 0,t.isGloballyBanned=!1,t.http.defaults.headers.common.Authorization="",t.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},"undefined"!=typeof document&&(document.cookie="_ascSession=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"),"tokenExpired"!==t.sessionState&&t.cache&&(t.cache={data:{}}),!0},so=e=>{const t=Ye();Zs("terminated",e),t.http.defaults.metadata&&("globalBan"===e&&(t.http.defaults.metadata.isGlobalBanned=!0),"userDeleted"===e&&(t.http.defaults.metadata.isUserDeleted=!0)),t.sessionHandler=void 0,ao()};let oo=null;const io=e=>{oo=e},ro=({user:e,userType:t})=>{kt(e),io(t)},co=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=eo(e);n.cache&&Fn(a),t(a.users[0])}))},lo=e=>co("user.deleted",e),uo=["analytic","normal-priority"],ho=["analytic","high-priority"],mo=async e=>{const t=Ye(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class go{constructor(){this._timer=void 0,this._high_priority_timer=void 0}start(){this.syncCapturedEvent(),this._timer=setInterval((()=>{this.syncCapturedEvent()}),6e4),this._high_priority_timer=setInterval((()=>{this.syncHighPriorityCapturedEvent()}),1e4)}stop(){this._timer&&(clearInterval(this._timer),this._timer=void 0),this._high_priority_timer&&(clearInterval(this._high_priority_timer),this._high_priority_timer=void 0)}async syncCapturedEvent(){try{const e=at(uo);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await mo(t),rt(uo)}catch(e){this.stop(),rt(uo)}}async syncHighPriorityCapturedEvent(){try{const e=at(ho);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await mo(t),rt(ho)}catch(e){this.stop(),rt(ho)}}}class po{constructor(){this._expireTime=5e3,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({uniqueId:e,expireTime:t,isHighPriority:n=!1}){const a=new Date,s=n?this._recentHighPriorityViewed[e]:this._recentViewed[e];if(!s)return!0;return!(a.getTime()-s.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:a,metadata:s}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const o=new Date,i={event:[]},r=at(uo);(null==r?void 0:r.data)&&(i.event=r.data.event),i.event.length>=this._poolLimit&&i.event.shift();const c={contentId:t,contentType:n,activityType:a,timestamp:o.toISOString()};s&&(c.metadata=s),i.event.push(c),it(uo,i),this._recentViewed[e]=o}markPostAsViewed(e){this.markAs({uniqueId:`post.${e}`,contentId:e,contentType:"post",activityType:"view"})}markPostAsMeaningfullyViewed(e,t){var n;const a=null===(n=at(["feedMetadata","get",e]))||void 0===n?void 0:n.data,s={};void 0!==t&&(s.feedRenderPosition=t),a&&(s.feedSnapshotPosition=a.feedSnapshotPosition,s.feedInjectionType=a.feedInjectionType,s.feedRelevanceScore=a.feedRelevanceScore,s.feedPopularityScore=a.feedPopularityScore,s.feedFreshnessScore=a.feedFreshnessScore,s.feedAffinityScore=a.feedAffinityScore,s.feedFinalScore=a.feedFinalScore,s.feedMmrPenalty=a.feedMmrPenalty),this.markAs({uniqueId:`post.${e}.meaningfulView`,contentId:e,contentType:"post",activityType:"meaningfulView",metadata:Object.keys(s).length>0?s:void 0})}markStory(e,t){if(!e.expiresAt)return;const n=new Date,a=new Date(e.expiresAt);if(!this.isAbleToEnqueue({uniqueId:e.storyId,expireTime:a.getTime(),isHighPriority:!0}))return;const s={event:[]},o=at(ho);if((null==o?void 0:o.data)&&(s.event=o.data.event),s.event.length>=this._poolLimit&&s.event.shift(),s.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),it(ho,s),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;st(["story-seen","get",e.storyId],(new Date).toISOString());const i=at(["story-last-seen",e.targetId]);(null==i?void 0:i.data)?new Date(i.data).getTime()<new Date(e.expiresAt).getTime()&&st(["story-last-seen",e.targetId],e.expiresAt):st(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),Nt("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},rt(uo),rt(ho)}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}markAdAsViewed(e,t){const n={placement:t},a="view";this.markAs({uniqueId:`${e.adId}.view.${t}`,contentId:e.adId,contentType:"ad",activityType:a,metadata:n})}markAdAsClicked(e,t){const n={placement:t},a="linkClicked";this.markAs({uniqueId:`${e.adId}.linkClicked.${t}`,contentId:e.adId,contentType:"ad",activityType:a,metadata:n})}markProductAsClicked(e,t,n,a){const s={location:t,sourceType:n,sourceId:a},o="linkClicked";this.markAs({uniqueId:`${e.productId}.linkClicked.${t}`,contentId:e.productId,contentType:"product",activityType:o,metadata:s})}markProductAsViewed(e,t,n,a){const s={location:t,sourceType:n,sourceId:a},o="view";this.markAs({uniqueId:`${e.productId}.view.${t}`,contentId:e.productId,contentType:"product",activityType:o,metadata:s})}}class yo{constructor(){this._client=Ye(),this._eventCapturer=new po,this._eventSyncer=new go}markPostAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsViewed(e)}markPostAsMeaningfullyViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsMeaningfullyViewed(e,t)}markStoryAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsViewed(e)}markAdAsViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsViewed(e,t)}markAdAsClicked(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsClicked(e,t)}markStoryAsClicked(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsClicked(e)}markProductAsClicked(e,t,n,a){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markProductAsClicked(e,t,n,a)}markProductAsViewed(e,t,n,a){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markProductAsViewed(e,t,n,a)}established(){this._eventSyncer.start()}handleTokenExpired(){this._stopAndDestroy()}destroy(){this._stopAndDestroy()}_stopAndDestroy(){this._eventSyncer.stop(),this._eventCapturer.resetAllBuckets()}}let vo;var fo=()=>(vo||(vo=new yo),vo),bo=()=>{const e=fo();return e.established(),In((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}};class Io{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ye(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipts();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=nt(["readReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.channelId,e.latestSegment)}))}getReadReceipts(){const e=this.jobQueue.splice(0,this.jobQueue.length);if(0!==e.length)return e.filter((e=>{var t;const n=null===(t=at(["readReceipt",e.channelId]))||void 0===t?void 0:t.data;return!!n&&n.latestSegment>n.latestSyncSegment}))}async markReadApi(e){var t;const n=e.map((e=>({channelId:e.channelId,readToSegment:e.segment})));if(await(async e=>{const t=Ye();try{return await t.http.post("api/v3/channels/seen",{channels:e}),!0}catch(e){return!1}})(n))for(let n=0;n<e.length;n+=1){const a=["readReceipt",e[n].channelId],s=null===(t=at(a))||void 0===t?void 0:t.data;st(a,Object.assign(Object.assign({},s),{latestSyncSegment:e[n].segment}))}else for(let t=0;t<e.length;t+=1){if(e[t].retryCount>=this.MAX_RETRY)return;const n=Object.assign(Object.assign({},e[t]),{syncState:"create",retryCount:e[t].retryCount+1});this.enqueueJob(n)}}startObservingReadReceiptQueue(){this.client.useLegacyUnreadCount&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1,this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const a=["channelUnread","get",e],s=null===(n=at(a))||void 0===n?void 0:n.data;s&&("number"!=typeof s.readToSegment||t>s.readToSegment)&&(s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0),st(a,s),Nt("local.channelUnread.updated",[s])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=at(["readReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)st(["readReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{st(["readReceipt",e],{channelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={channelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){const{jobQueue:t}=this;return t.find((t=>t.channelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}}let Co=null;var wo=()=>(Co||(Co=new Io),Co),So=()=>{const e=wo();return e.startSyncReadReceipt(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Oo{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ye(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipt();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=nt(["legacyReadReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.subChannelId,e.latestSegment)}))}getReadReceipt(){var e;const t=this.jobQueue[0];if(!t)return;if("syncing"===t.syncState)return;const n=null===(e=at(["legacyReadReceipt",t.subChannelId]))||void 0===e?void 0:e.data;return n?(null==n?void 0:n.latestSegment)>(null==n?void 0:n.latestSyncSegment)?(t.segment=n.latestSegment,t):(this.removeSynedReceipt(n.subChannelId,n.latestSegment),this.getReadReceipt()):void 0}async markReadApi(e){var t;const n=e;n.syncState="syncing";const{subChannelId:a,segment:s}=n,o=await(async({subChannelId:e,readToSegment:t})=>{const n=Ye();n.log("subChannel/markAsReadBySegment",e);try{return await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-read`,{readToSegment:t}),!0}catch(e){return!1}})({subChannelId:a,readToSegment:s});if(o){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=at(["legacyReadReceipt",a]))||void 0===t?void 0:t.data;st(["legacyReadReceipt",a],Object.assign(Object.assign({},n),{latestSyncSegment:s}))}else o||(n.retryCount>this.MAX_RETRY?this.removeJobFromQueue(n):(n.retryCount+=1,n.syncState="create"))}removeSynedReceipt(e,t){this.jobQueue.forEach((n=>{n.subChannelId===e&&n.segment<=t&&this.removeJobFromQueue(n)}))}startObservingReadReceiptQueue(){this.client.isUnreadCountEnabled&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1;this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const a=["subChannelUnreadInfo","get",e],s=null===(n=at(a))||void 0===n?void 0:n.data;if(s&&t>s.readToSegment){s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0);const e=ta(s.channelId);Nt("local.channelUnreadInfo.updated",e),st(a,s),Nt("local.subChannelUnread.updated",s)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=at(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)st(["legacyReadReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{st(["legacyReadReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){return this.jobQueue.find((t=>t.subChannelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}removeJobFromQueue(e){const t=this.jobQueue.indexOf(e);t>-1&&this.jobQueue.splice(t,1)}}let To=null;var Ao=()=>(To||(To=new Oo),To),Ro=()=>{const e=Ao();return e.startSyncReadReceipt(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const Po=e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("online",e),()=>window.removeEventListener("online",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("online",e),()=>document.removeEventListener("online",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return import("@react-native-community/netinfo").then((n=>{t=n.addEventListener((t=>{t.isConnected&&e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")},Do=e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("offline",e),()=>window.removeEventListener("offline",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("offline",e),()=>document.removeEventListener("offline",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return import("@react-native-community/netinfo").then((n=>{t=n.addEventListener((t=>{t.isConnected||e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")},Uo=async e=>{const t=Ye();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{Pe(null==t?void 0:t.code)&&_n("channel",e)})),t}const s=await Ua(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ja(a);const o=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:o}),Nt("local.channel.fetched",s.channels),{data:s.channels,cachedAt:o}};Uo.locally=e=>{var t,n;const a=Ye();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const s=null===(t=nt(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;return{data:s.map((({data:e})=>e)),cachedAt:(null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0]).cachedAt}};class ko{constructor(){this.TIMER_INTERVAL_MS=Ie,this.BUFFER_ID_LIMIT=100,this.buffer={channel:[],userMessageFeedMarker:[]},this.isResolvingTask=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startResolver(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.resolveObjects()}),this.TIMER_INTERVAL_MS))}stopResolver(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}resolve(e,t){const n=this.getBuffer(t);n.includes(e)||(n.length>=this.BUFFER_ID_LIMIT&&n.shift(),n.push(e))}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push(Po((()=>{this.isConnected=!0}))),this.connectionListener.push(Do((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&this.connectionListener.forEach((e=>e()))}resolveObjects(){if(this.isResolvingTask)return;this.isResolvingTask=!0;const e=this.getBuffer("channel"),t=this.getBuffer("userMessageFeedMarker");this.clearBuffer(),e.length>0&&(async e=>{var t,n,a;await Uo(e);const s=null!==(a=null===(n=null===(t=nt(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId&&e.includes(t.channelPublicId))))||void 0===n?void 0:n.map((({data:e})=>e)))&&void 0!==a?a:[];Nt("local.channel.resolved",s)})(e),t.length>0&&(async e=>{const t=await ka(e),{feedMarkers:n,userFeedMarkers:a}=t;na({feedMarkers:n,userFeedMarkers:a}),Nt("local.userMessageFeedMarkers.resolved",{feedMarkers:n,userFeedMarkers:a})})(t),this.isResolvingTask=!1}clearBuffer(){this.buffer={channel:[],userMessageFeedMarker:[]}}getBuffer(e){return this.buffer[e]}onSessionEstablished(){this.startResolver(),this.addConnectionListener()}onSessionDestroyed(){this.stopResolver(),this.clearBuffer(),this.isResolvingTask=!1,this.removeConnectionListener()}onTokenExpired(){this.stopResolver()}}let jo=null;var Eo=()=>(jo||(jo=new ko),jo),Mo=()=>{const e=Eo();return e.startResolver(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class qo{constructor(){this.TIMER_INTERVAL_MS=1e3,this.buffer=[],this.isSyncing=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startReactionsSync(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.syncLiveReactions()}),this.TIMER_INTERVAL_MS))}stopReactionsSync(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}createLiveReaction(e){this.buffer.push(e)}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push(Po((()=>{this.isConnected=!0}))),this.connectionListener.push(Do((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&(this.connectionListener.forEach((e=>e())),this.connectionListener=[])}syncLiveReactions(){if(this.isSyncing)return;this.isSyncing=!0;const e=this.buffer;this.clearBuffer();const t=e.reduce(((e,t)=>{const{roomId:n,streamId:a}=t,s=Bn(t,["roomId","streamId"]),o=a?"liveStream":"room",i=null!=a?a:n;return e[i]||(e[i]={referenceType:o,reactions:[]}),e[i].reactions.push(s),e}),{});Object.entries(t).forEach((([t,n])=>{(async({reactions:e,liveStreamId:t,roomId:n})=>{const a=Ye();a.log("live_reaction/addReaction",e);const{data:s}=await a.http.post("/api/v1/reactions/live",{liveStreamId:t,reactions:e,roomId:n})})({["room"===n.referenceType?"roomId":"liveStreamId"]:t,reactions:e})})),this.isSyncing=!1}clearBuffer(){this.buffer=[]}onSessionEstablished(){this.startReactionsSync(),this.addConnectionListener()}onSessionDestroyed(){this.stopReactionsSync(),this.clearBuffer(),this.isSyncing=!1,this.removeConnectionListener()}onTokenExpired(){this.stopReactionsSync()}}let xo;var No=()=>(xo||(xo=new qo),xo);function Ko(e){const{users:t,follows:n}=e,a=Bn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:pa(n)})})),users:t.map(pa)})}class Fo{constructor(){this.lastFetchedAt=null}onSessionEstablished(){}onSessionDestroyed(){this.lastFetchedAt=null}onTokenExpired(){}isCacheExpired(){return null===this.lastFetchedAt||Date.now()-this.lastFetchedAt>3e5}async ensureFetched(){if(!this.isCacheExpired())return;const e=Ye(),{data:t}=await e.http.get("/api/v4/me/user-blocks",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=Ko(t);e.cache&&Fn(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ye();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=nt(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&e.from===n)).sort(((e,t)=>{var n,a;return(null!==(n=e.updatedAt)&&void 0!==n?n:"")<(null!==(a=t.updatedAt)&&void 0!==a?a:"")?1:-1})).map((e=>{var t;return null===(t=at(["user","get",e.to]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(Bt)}}let _o=null;var Bo=()=>(_o||(_o=new Fo),_o);function $o(e){const{users:t,follows:n}=e,a=Bn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:pa(n)})})),users:t.map(pa)})}class Lo{constructor(){this.lastFetchedAt=null}onSessionEstablished(){}onSessionDestroyed(){this.lastFetchedAt=null}onTokenExpired(){}isCacheExpired(){return null===this.lastFetchedAt||Date.now()-this.lastFetchedAt>3e5}async ensureFetched(){if(!this.isCacheExpired())return;const e=Ye(),{data:t}=await e.http.get("/api/v4/me/blockers",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=$o(t);e.cache&&Fn(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ye();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=nt(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&e.to===n)).sort(((e,t)=>{var n,a;return(null!==(n=e.updatedAt)&&void 0!==n?n:"")<(null!==(a=t.updatedAt)&&void 0!==a?a:"")?1:-1})).map((e=>{var t;return null===(t=at(["user","get",e.from]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(Bt)}}let Qo=null;var Vo=()=>(Qo||(Qo=new Lo),Qo);function Jo(e){const{users:t,follows:n}=e,a=Bn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(pa)})}function Ho(e){const{users:t,follows:n}=e,a=Bn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(pa)})}function Go(e){const{follows:t}=e,n=Bn(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const zo=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Jo(e);n.cache&&Fn(a),t(a.follows[0])}))},Yo=e=>zo("user.didBlock",e),Wo=e=>zo("user.didUnblock",e);class Xo{constructor(e,t){this.networkId=e,this.userId=t}static current(){try{const e=$t();if(!e)return null;const t=Vt(e),{userId:n}=e;return t&&n?new Xo(t,n):null}catch(e){return null}}static isExpired(e){return Date.now()>=e}static clearOnLogout(){return In((e=>{var t;"terminated"===e&&(null===(t=Xo.current())||void 0===t||t.clear())}))}get key(){return`amity:forYouFeed:cursor:${this.networkId}:${this.userId}`}async get(){const e=await Un(this.key);if(!e)return null;try{const t=JSON.parse(e);return"string"!=typeof(null==t?void 0:t.cursor)||"number"!=typeof(null==t?void 0:t.expiredAt)?null:{cursor:t.cursor,expiredAt:t.expiredAt,reachedEndOfFeed:!0===t.reachedEndOfFeed}}catch(e){return null}}async set(e){await Dn(this.key,JSON.stringify(e))}async markReachedEndOfFeed(e){var t;const n=await this.get();await this.set({cursor:null!==(t=null==n?void 0:n.cursor)&&void 0!==t?t:"",expiredAt:e,reachedEndOfFeed:!0})}async clear(){await Dn(this.key,"")}}const Zo=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],ei=e=>{const t=Ye(),n=Zo.map((n=>xt(t,`client/onConnectionError(${n})`,n,(t=>{const a=(null==t?void 0:t.code)?new Qe(t.message,t.code,"fatal"):new He(n);e(a)}))));return()=>{n.forEach((e=>e()))}},ti=e=>{const t=Ye();return xt(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},ni=e=>{const t=Ye();return xt(t,"client/onTokenExpired","tokenExpired",e)},ai=e=>{const t=Ye();return xt(t,"client/onTokenTerminated","tokenTerminated",e)},si=e=>{const t=Ze("channelMarker")({userId:Ut()._id,entityId:e.channelId});rt(["channelMarker","get",t],!0)},oi=e=>{const t=Ye(),n=[];return n.push(ti((t=>{so("globalBan"),n.forEach((e=>e())),e()})),ai((t=>{so(),n.forEach((e=>e())),e()})),lo((a=>{a.userId===t.userId&&(so("userDeleted"),n.forEach((e=>e())),e())})),ni((e=>{bn().setSessionState(e),ao(),n.forEach((e=>e()))})),Ya(si),gs(si),Ns(),bo(),Mo(),(()=>{const e=No();return e.startReactionsSync(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=Bo();return In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=Vo();return In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=[Yo((()=>{})),Wo((()=>{}))];return()=>e.forEach((e=>e()))})(),In((e=>{"established"!==e&&An().reset()})),Xo.clearOnLogout()),t.useLegacyUnreadCount?n.push(So()):n.push(Ro()),n};let ii=[];const ri=async(e,t,n)=>{const a=Ye();let s;a.log("client/api/connectClient",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&a.userId!==e.userId&&(await ao(),ii.forEach((e=>e())),ii=[]);const o=await En();try{const{users:n,userType:i}=await to({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||o}),options:{setAccessTokenCookie:!0}}),r=n.find((t=>t.userId===e.userId));if(null==r)throw new Qe(`${e.userId} has not been founded`,8e5,"error");if(r.isDeleted)return so("userDeleted"),!1;if(r.isGlobalBan)return so("globalBan"),!1;a.userId=r.userId,a.sessionHandler=t,a.loginType="userId",s=a.accessTokenExpiryWatcher(),ro({user:r,userType:i})}catch(e){throw bn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await _t()}(),await _s(),0===ii.length&&(ii=oi(s)),!0},ci=[],di=async e=>{const t=Ye();let n;t.log("client/api/connectClient",Object.assign({apiKey:t.apiKey,sessionState:t.sessionState},e));const a=await En();let s;try{const{users:o,userType:i}=await no({params:Object.assign(Object.assign({},e),{deviceId:a}),options:{setAccessTokenCookie:!0}});[s]=o,t.userId=s.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),ro({user:s,userType:i})}catch(e){throw bn().setSessionState("notLoggedIn"),e}return await _s(),0===ci.length&&ci.push(ai((e=>{so(),ci.forEach((e=>e())),n()})),ni((e=>{bn().setSessionState(e),ao(),ci.forEach((e=>e()))}))),!0},li=()=>{let e,t=!1;const n=Ye();n.log("initiating access token renewal");const a=async a=>{const{userId:s,displayName:o}=Ut(),i={userId:s,displayName:o,authToken:a,deviceId:await En()};"tokenExpired"===n.sessionState&&n.sessionHandler?await ri(i,n.sessionHandler):await to({params:i,options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):a()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):a(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(li())}),Ce)},renewWithAuthSignature:a=>{t?console.log("'renew' method can be called only once per renewal instance"):(async({authSignature:a,authSignatureExpiresAt:s})=>{const o=await En();"tokenExpired"===n.sessionState&&n.sessionHandler?await di({sessionHandler:n.sessionHandler}):await no({params:{authSignature:a,authSignatureExpiresAt:s,deviceId:o},options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)})(a)},unableToRetrieveAuthSignature:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(li())}),Ce)}}},ui=async({token:e,userId:t})=>{const n=Ye(),{data:a}=await n.http.get("/api/v4/sessions",{headers:{Authorization:`Bearer ${e.accessToken}`}}),{users:s,files:o,userType:i}=a,[r]=s;return t&&(null==r?void 0:r.userId)&&t!==r.userId&&n.log("client/api/validateAccessToken",{message:"session userId does not match the token userId; using the server value",tokenUserId:t,sessionUserId:r.userId}),n.http.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.http.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.upload.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.upload.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.token=e,Fn(eo({users:s,files:o})),io(i),r},hi=e=>{var t;const n=Ye(),a=A.default(e);return(null===(t=null==a?void 0:a.user)||void 0===t?void 0:t.publicUserId)===n.userId};let mi=[];const gi=async e=>{var t,n;const a=Ye();let s,o;if(a.log("client/api/loginWithAccessToken",{apiKey:a.apiKey,sessionState:a.sessionState}),!e||"string"!=typeof e||""===e.trim())throw new Qe("Access token must be a non-empty string",8e5,"error");try{o=A.default(e)}catch(e){throw new Qe("Invalid access token format",400100,"error")}const i=(null===(t=null==o?void 0:o.user)||void 0===t?void 0:t.publicUserId)||(null===(n=null==o?void 0:o.user)||void 0===n?void 0:n.userId);if(!i)throw new Qe("Access token does not contain userId",400100,"error");if(a.userId){hi(e)||await ao()}try{Zs("establishing");const t={accessToken:e,issuedAt:o.iat?new Date(1e3*o.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*o.exp).toISOString()},n=await ui({token:t,userId:i});if(null==n)throw Zs("notLoggedIn"),new Qe(`User ${i} has not been found`,8e5,"error");a.userId=n.userId,a.loginType="accessToken",kt(n),s=a.accessTokenExpiryWatcher(),Zs("established")}catch(e){if(Zs("notLoggedIn"),e instanceof Qe)throw 400312===e.code&&(a.isGloballyBanned=!0),e;throw new Qe((e instanceof Error?e.message:void 0)||"Login with access token failed",400100,"error")}return async function(){await _t()}(),await _s(),0===mi.length&&(mi=oi(s)),!0},pi=async e=>{var t,n;const a=Ye();if(a.log("initiating access token renewal"),!e||"string"!=typeof e||""===e.trim())throw new Qe("Access token must be a non-empty string",8e5,"error");let s;try{s=A.default(e)}catch(e){throw new Qe("Invalid access token format",400100,"error")}const o=(null===(t=null==s?void 0:s.user)||void 0===t?void 0:t.publicUserId)||(null===(n=null==s?void 0:s.user)||void 0===n?void 0:n.userId);if(!o)throw new Qe("Access token does not contain userId",400100,"error");if(a.userId){hi(e)||await ao()}const i={accessToken:e,issuedAt:s.iat?new Date(1e3*s.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*s.exp).toISOString()};if("tokenExpired"===a.sessionState&&a.sessionHandler)await gi(e);else try{await ui({token:i,userId:o})}catch(e){throw e instanceof Qe&&400312===e.code&&(a.isGloballyBanned=!0),e}},yi=async({useScheduledTask:e=!1})=>{const t=Ye();if(t.userId&&t.accessTokenHandler&&!t.isGloballyBanned)try{const n=await t.accessTokenHandler.onTokenRenew(t.userId);e?Mt((()=>pi(n))):pi(n)}catch(e){t.log("Proactive token renewal failed, will retry when token expires",e)}},vi=3e5,fi=()=>{const e=setInterval((async()=>{const e=Ye(),{sessionHandler:t,accessTokenHandler:n,loginType:a}=e;if(!e.token||!e.userId)return;const{issuedAt:s,expiresAt:o}=e.token;if((e=>Date.now()>Date.parse(e)-vi)(o))return Nt("tokenExpired","tokenExpired"),void("accessToken"===a&&n?await yi({useScheduledTask:!1}):"userId"===a&&t&&Mt((()=>t.sessionWillRenewAccessToken(li()))));(e=>{const{expiresAt:t,issuedAt:n}=e,a=Date.parse(t),s=Date.parse(n),o=Date.now();return o>s+.8*(a-s-vi)&&o<a})({expiresAt:o,issuedAt:s})&&("accessToken"===a&&n?await yi({useScheduledTask:!1}):"userId"===a&&t&&t.sessionWillRenewAccessToken(li()))}),Ce);return()=>clearInterval(e)},bi=e=>{if(Ye().useLegacyUnreadCount){wo().markRead(e.channelId,e.channelSegment)}else{Ao().markRead(e.subChannelId,e.channelSegment)}},Ii=e=>{const t=Ye(),n=Ut(),a=[xt(t,"message/onMessageCreated","message.created",(async a=>{const s=await ha(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messages.forEach((e=>{(e=>{var t;const n=Ye(),a=["subChannelUnreadInfo","get",e.messageFeedId],s=null===(t=at(a))||void 0===t?void 0:t.data;if(!s)return;const o=s.lastSegment<e.segment?e.segment:s.lastSegment,i=o-s.readToSegment;let{lastMentionSegment:r}=s;e.mentionedUsers&&e.mentionedUsers.length>0&&e.mentionedUsers.forEach((t=>{("channel"===t.type||"user"===t.type&&n.userId&&t.userPublicIds.includes(n.userId))&&(r=e.segment)}));const c=Object.assign(Object.assign({},s),{lastMentionSegment:r,lastSegment:o,isMentioned:!(s.readToSegment>=r),unreadCount:Math.max(i,0)});st(a,c)})(e),ta(e.channelId)})),t.useLegacyUnreadCount&&a.messages.forEach((e=>{var n,a,s;const o=null===(n=at(["channelUnread","get",e.channelId]))||void 0===n?void 0:n.data;if(!o||o.lastSegment>=e.segment)return;const i=e.segment,r=(null===(a=e.mentionedUsers)||void 0===a?void 0:a.some((e=>"channel"===e.type||"user"===e.type&&t.userId&&e.userPublicIds.includes(t.userId))))?e.segment:o.lastMentionedSegment,c=null!==(s=o.readToSegment)&&void 0!==s?s:0,d=Object.assign(Object.assign({},o),{lastSegment:i,unreadCount:Math.max(i-c,0),lastMentionedSegment:r,isMentioned:"number"==typeof r&&c<r});st(["channelUnread","get",e.channelId],d),Nt("local.channelUnread.updated",[d])})),Fn(s),s.messages.forEach((t=>{t.creatorPrivateId===n._id&&bi(t),e(t)}))}))];return()=>{a.forEach((e=>e()))}},Ci=e=>{const t=Ye(),n=[xt(t,"message/onMessageCreated","local.message.created",(async t=>(Fn(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},wi=e=>{const t=Ye();return xt(t,"onSubChannelCreated","message-feed.created",(async n=>{const a=await fa(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:a,updatedAt:s}=e,o={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:a,updatedAt:s};st(["subChannelUnreadInfo","get",o.subChannelId],o)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Fn(a),e(a.messageFeeds[0])}))},Si=e=>{const t=Ye(),n=[xt(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const a=await fa(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],a=null===(t=at(n))||void 0===t?void 0:t.data;a&&st(n,Object.assign(Object.assign({},a),{isDeleted:!0}))})(e.subChannelId),ta(e.channelId)})),Fn(a),e(a.messageFeeds[0])})),xt(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Oi=async e=>{const t=Ye();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:a,userFeedMarkers:s,feedMarkers:o,userMarkers:i}=n,r=Vn(a),c=Jn(s),d=t.cache&&Date.now();return t.cache&&Fn({userEntityMarkers:r,userFeedMarkers:c,feedMarkers:o,userMarkers:i},{cachedAt:d}),Nt("local.feedMarker.fetched",{feedMarkers:o}),Nt("local.channelMarker.fetched",{userEntityMarkers:r}),Nt("local.subChannelMarker.fetched",{userFeedMarkers:c}),Nt("local.userMarker.fetched",{userMarkers:i}),{data:n,hasMore:n.feedMarkers.length>0}};let Ti=!1,Ai=[],Ri=!1;let Pi=null;let Di=[];const Ui=e=>{Di=e},ki=async()=>{var e;if(!Ri&&0!==Di.length)try{Ri=!0,Di=[];const t=await Oi((null==Pi?new Date:Pi).toISOString()),n=t.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);null!=(e=n)&&(!Pi||e.getTime()>Pi.getTime())&&(Pi=e),t.hasMore&&Di.push("has_more")}catch(e){}finally{Ri&&(Ri=!1)}};js((async()=>{Ti&&await ki()}),2e3);const ji=()=>true,Ei=e=>{var t;const n=Ye();if(n.mqtt)return null===(t=n.mqtt)||void 0===t?void 0:t.listen(e)},Mi=async()=>{const e=Ye(),t=await En(),{data:{status:n,error:a}}=await e.http.delete("/v1/notification",{params:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(a)throw new Ve(a,5e5,"error");return"success"===n};let qi=[];var xi;class Ni{constructor(){xi.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,a,s){if("m"===a)throw new TypeError("Private method is not writable");if("a"===a&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===a?s.call(e,n):s?s.value=n:t.set(e,n)}(this,xi,e,"f")}getFileAccessType(){return function(e,t,n,a){if("a"===n&&!a)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?a:"a"===n?a.call(e):a?a.value:t.get(e)}(this,xi,"f")}}let Ki;xi=new WeakMap;var Fi=()=>(Ki||(Ki=new Ni),Ki);const _i={[e.AmitySharableContentType.POST]:{key:"posts",placeholder:"postId"},[e.AmitySharableContentType.COMMUNITY]:{key:"communities",placeholder:"communityId"},[e.AmitySharableContentType.USER]:{key:"users",placeholder:"userId"},[e.AmitySharableContentType.LIVESTREAM]:{key:"livestream",placeholder:"livestream"},[e.AmitySharableContentType.EVENT]:{key:"events",placeholder:"eventId"}},Bi=async e=>{const t=Ye();Zs("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ye();n.log("client/api/getBotToken");const a=Mn(),{data:s}=await n.http.post("/api/v5/sessions/bot",Object.assign(Object.assign({},e),{deviceInfo:a}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:s},Zs("established"),Fn(eo({users:a,files:r})),{accessToken:n,users:a,userType:i}},$i=[];function Li(t,n){return n&&n.length>0?{type:"not",roleIds:n}:t&&t.length>0?{type:e.NotificationRolesFilterTypeEnum.ONLY,roleIds:t}:{type:e.NotificationRolesFilterTypeEnum.ALL}}function Qi(t){return(null==t?void 0:t.type)===e.NotificationRolesFilterTypeEnum.ONLY?{listenFromRoleIds:t.roleIds}:{listenFromRoleIds:[]}}class Vi{constructor(e){this.channelId=e}async enable(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!0};await t.http.post("/api/v3/notification/setting",n)}async disable(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!1};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){const t=Ye(),{data:n}=await t.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.CHANNEL}&channelId=${encodeURIComponent(this.channelId)}`);return{isEnabled:n.isPushNotifiable}}}class Ji{async enable(t){var n;const a=Ye(),s=null!==(n=null==t?void 0:t.map((e=>Object.assign({moduleName:e.moduleName,isPushNotifiable:e.isEnabled},Qi(e.rolesFilter)))))&&void 0!==n?n:[],o={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!0,notifiableEvents:s};await a.http.post("/api/v3/notification/setting",o)}async disableAllNotifications(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=Ye(),{data:a}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.USER}`),s=Object.values(e.UserNotificationModuleNameEnum),o=(null!==(t=a.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.moduleName&&s.includes(e.moduleName))).map((e=>({moduleName:e.moduleName,isEnabled:e.isPushNotifiable,rolesFilter:Li(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,modules:o}}}class Hi{constructor(e){this.communityId=e}async enable(t){var n;const a=Ye(),s=null!==(n=null==t?void 0:t.map((t=>Object.assign({moduleName:e.UserNotificationModuleNameEnum.SOCIAL,name:t.eventName,isPushNotifiable:t.isEnabled},Qi(t.rolesFilter)))))&&void 0!==n?n:[],o={level:e.NotificationSettingsLevelEnum.COMMUNITY,communityId:this.communityId,isPushNotifiable:!0,notifiableEvents:s};await a.http.post("/api/v3/notification/setting",o)}async disable(){const t=Ye(),n={level:e.NotificationSettingsLevelEnum.COMMUNITY,communityId:this.communityId,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=Ye(),{data:a}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.COMMUNITY}&communityId=${encodeURIComponent(this.communityId)}`),s=Object.values(e.CommunityNotificationEventNameEnum),o=(null!==(t=a.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.name&&s.includes(e.name))).map((e=>({eventName:e.name,isEnabled:e.isPushNotifiable,isNetworkEnabled:e.isNetworkEnabled,rolesFilter:Li(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,events:o}}}class Gi{user(){return new Ji}community(e){return new Hi(e)}channel(e){return new Vi(e)}}const zi=e=>{const t=Ye();return xt(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},Yi=e=>{const t=Ye();return xt(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},Wi=e=>{const t=Ye();return xt(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},Xi=e=>{const t=Ye();return xt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},Zi=e=>{const t=Ye();return xt(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},er=e=>{const t=Ye();return xt(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,a,s;Fn(t);const o=nt(["message","collection"]),{contentMarkers:i,feedMarkers:r}=t;if(o&&(null==o?void 0:o.length)>0&&(null==r?void 0:r.length)>0){const e=o.filter((e=>{var t,n;return(null===(n=null===(t=e.data)||void 0===t?void 0:t.query)||void 0===n?void 0:n.subChannelId)===r[0].feedId}));if(e.length>0&&(null==i?void 0:i.length)>0){(null!==(s=null===(a=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===a?void 0:a.map((e=>at(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==s?s:[]).forEach((e=>{var t,n;const a=["messageMarker","get",Ze("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],s=null===(t=at(a))||void 0===t?void 0:t.data;if(!s)return;const o=i[0].feedId===s.feedId,r=i[0].readCount>s.readCount,c=(null===(n=i[0])||void 0===n?void 0:n.deliveredCount)>s.deliveredCount;if(o){const e=Object.assign(Object.assign({},s),{readCount:r?i[0].readCount:s.readCount,deliveredCount:c?i[0].deliveredCount:s.deliveredCount});st(a,e)}}))}}e(t.contentMarkers[0])}))};function tr(e){return"object"==typeof e&&null!==e}const nr=e=>{if(!tr(e))return e;const t=Object.entries(e).map((([t,n])=>{const a=Object.getOwnPropertyDescriptor(e,t);return"function"==typeof(null==a?void 0:a.get)?[t,a.get.call(e)]:[t,n]}));return Object.fromEntries(t)},ar=e=>{if(!tr(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var sr=Object.freeze({__proto__:null,getActiveClient:Ye,getActiveUser:Ut,setActiveUser:kt,createClient:(e,t=on.SG,{debugSession:n="amity",apiEndpoint:a,prefixDeviceIdKey:s,rteEnabled:o=!0}={})=>{var i,r,c;const d=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!sn,n=I.default(e),a=(e,...a)=>{t&&n(e,a)};return a.__instance__=n,a})(n);d("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const l=null!==(i=null==a?void 0:a.http)&&void 0!==i?i:cn("http",t),u=null!==(r=null==a?void 0:a.upload)&&void 0!==r?r:cn("upload",t),h=null!==(c=null==a?void 0:a.mqtt)&&void 0!==c?c:cn("mqtt",t),m=yn(l),g=yn(u);let p;o&&(p=Nn(h));const y=b.default(),v={version:`${me}`,apiKey:e,log:d,cache:{data:{}},http:m,ws:undefined,mqtt:p,upload:g,emitter:y,sessionState:"notLoggedIn",accessTokenExpiryWatcher:fi,sessionHandler:undefined,hasPermission:Gs,validateUrls:zs,validateTexts:Ys,getFeedSettings:Ws,getCoreUserSettings:$s,getSocialSettings:Bs,getChatSettings:Kn,getLiveViewerCountConfig:Qs,getVisitorDeviceId:En,getMessagePreviewSetting:Fs,onRTEConnectionStateChange:Ei,use:()=>We(v),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:ji,getProductCatalogueSetting:Vs,getForYouFeedSetting:Js,prefixDeviceIdKey:s};try{const t=Ye();if(t.apiKey===e)return t;We(v)}catch(e){We(v)}return v},login:ri,loginWithAccessToken:gi,logout:ao,secureLogout:async()=>{const e=Ye();try{await Mi()}catch(t){e.log("client/api/secureLogout: failed to unregister push notification",t)}const{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return ao()},resumeSession:async(e,t,n)=>{const a=Ye();let s;a.log("client/api/resumeSession",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&(a.userId===e.userId&&hi(e.token.accessToken)?(a.mqtt&&a.mqtt.connected&&a.mqtt.disconnect(),qi.forEach((e=>e())),qi=[]):(await ao(),qi.forEach((e=>e())),qi=[]));try{Zs("establishing");const n=await ui(e);if(null==n)throw new Qe(`${e.userId} has not been found`,8e5,"error");a.userId=n.userId,a.sessionHandler=t,s=a.accessTokenExpiryWatcher(),kt(n)}catch(e){throw bn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await _t()}(),await _s(),0===qi.length&&(qi.push(ti((e=>{so("globalBan"),qi.forEach((e=>e())),s()})),ai((e=>{so(),qi.forEach((e=>e())),s()})),lo((e=>{e.userId===a.userId&&(so("userDeleted"),qi.forEach((e=>e())),s())})),ni((e=>{bn().setSessionState(e),ao(),qi.forEach((e=>e()))})),Ya(si),gs(si),Ns(),bo(),Mo()),a.useLegacyUnreadCount?qi.push(So()):qi.push(Ro())),!0},isConnected:()=>{var e,t;const n=Ye();return n.log("client/api/isConnected",n),!(!n.userId||!(null===(t=String(null===(e=n.http.defaults.headers.common)||void 0===e?void 0:e.Authorization))||void 0===t?void 0:t.length))},getFeedSettings:Ws,renewal:li,markerSync:Oi,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){Fi().setFileAccessType(e)},registerPushNotification:async e=>{const t=Ye();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new Ge("Unsupported platform");n=l.Platform.OS;const a=await En(),{data:{status:s,error:o}}=await t.http.post("/v1/notification",{userId:t.userId,deviceId:a,platform:n,token:e},{headers:{"X-API-Key":t.apiKey}});if(o)throw new Ve(o,5e5,"error");return"success"===s},unregisterPushNotification:Mi,onRTEConnectionStateChange:Ei,fetchLinkPreview:async e=>{const t=Ye();let n=e;/^https?:\/\//i.test(e)||(n=`https://${e}`);const{data:a}=await t.http.get(`/api/v1/link-preview?url=${encodeURIComponent(n)}`);return a},getLinkPreviewMetadata:async e=>{const t=Ye(),{data:n}=await t.http.get(`/api/v1/link-preview?url=${e}`);return n},getSocialSettings:Bs,getShareableLinkConfiguration:async()=>{var e,t;const n=Ye(),{data:a}=await n.http.get("/api/v3/network-settings/shareable-deep-links"),s=null!==(e=a.domain)&&void 0!==e?e:"",o=null!==(t=a.patterns)&&void 0!==t?t:{};return{domain:s,patterns:o,isEnabled(e){const{key:t}=_i[e];return!!s&&!!o[t]},getPattern(e){const{key:t}=_i[e];return o[t]||null},generateLink(e,t){const{key:n,placeholder:a}=_i[e];return s&&o[n]?s+o[n].replace(`{${a}}`,t):null}}},getProductCatalogueSetting:Vs,getForYouFeedSetting:Js,loginAsVisitor:di,loginAsBot:async e=>{const t=Ye();let n;t.log("client/api/connectClient",{apiKey:t.apiKey,sessionState:t.sessionState});const a=await En();let s;try{const{users:o,userType:i}=await Bi({params:{deviceId:a},options:{setAccessTokenCookie:!0}});[s]=o,t.userId=s.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),ro({user:s,userType:i})}catch(e){throw bn().setSessionState("notLoggedIn"),e}return await _s(),0===$i.length&&$i.push(ai((e=>{so(),$i.forEach((e=>e())),n()})),ni((e=>{bn().setSessionState(e),ao(),$i.forEach((e=>e()))}))),!0},getCurrentUser:$t,getCurrentUserType:()=>{if(!oo)throw new Qe("Connect client first",8e5,"fatal");return oo},setCurrentUserType:io,setAccessTokenHandler:e=>{const t=Ye();if(t.log("client/api/setAccessTokenHandler",{apiKey:t.apiKey,sessionState:t.sessionState,hasOnTokenRenew:"function"==typeof(null==e?void 0:e.onTokenRenew)}),!e||"function"!=typeof e.onTokenRenew)throw new Error("AccessTokenHandler must implement onTokenRenew() method");t.accessTokenHandler=e},getChatSettings:Kn,getLiveViewerCountConfig:Qs,getCoreUserSettings:$s,notifications:()=>new Gi,enableAutoSubscriptions:e=>{const t=An();e.forEach((e=>t.subscribe(e)))},disableAutoSubscriptions:e=>{const t=An();e.forEach((e=>t.unsubscribe(e)))},autoSubscriptions:()=>An().subscriptions(),onConnectionError:ei,onClientDisconnected:e=>ei((({code:t})=>{800211===t&&e()})),onClientBanned:ti,onSessionStateChange:In,onNetworkActivities:e=>hn().onNetworkActivities(e),onVisitorUsageLimitReached:e=>{const t=Ye();return xt(t,"client/onVisitorUsageLimitReached","visitorUsageLimitReached",e)},getUserUnread:e=>{const{_id:t}=Ut();if(!t)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=Ye();a||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const s=[];let o,i=!1;const r=t=>{const{data:n}=t,a=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;o=a?nr(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return s.push(Xi((e=>(e=>{var n;const a=e.filter((e=>t===e.userId)),s=a.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),i={unreadCount:null!==(n=null==s?void 0:s.unreadCount)&&void 0!==n?n:0,isMentioned:a.some((e=>!!e.isMentioned))};Fa(o,i)||r({loading:!1,data:i})})(e)))),(()=>{const e=_e(aa);$e(e,(({error:e,data:t,loading:n,origin:a,cachedAt:o})=>{!function(e){return null!=e&&null!=e}(t)?r({loading:n,data:void 0,origin:a,error:e}):(o===be?(r({data:t,origin:a,loading:!1,error:new Ve(fe,800800,"error")}),i=!0,s.forEach((e=>e()))):i||r({loading:n,data:t,origin:a,error:e}),e&&s.forEach((e=>e())))}))})(),()=>{s.forEach((e=>e()))}},getMarkerSyncEvents:()=>Di,setMarkerSyncEvents:Ui,pushMarkerSyncEvent:e=>Di.push(e),markerSyncTrigger:ki,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{Ti=!1,Ui([]),Ai.forEach((e=>e())),Ai=[]},getMarkerSyncConsistentMode:ji});const or=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Jo(e);n.cache?(Fn(a),t(a.follows[0])):t(a.follows[0])}))},ir=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Go(e);n.cache?(Fn(a),t(a.follows[0])):t(a.follows[0])}))},rr=e=>or("follow.created",e),cr=e=>or("follow.unfollowed",e),dr=e=>or("follow.followerDeleted",e),lr=e=>or("follow.requested",e),ur=e=>or("follow.requestCanceled",e),hr=e=>or("follow.accepted",e),mr=e=>or("follow.requestDeclined",e),gr=async e=>{var t,n;const a=Ye();a.log("follow/getFollowInfo",e);const{data:s}=await a.http.get(a.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),o=a.cache&&Date.now(),i="follows"in s?Object.assign(Object.assign({},s.followCounts[0]),{status:null===(n=null===(t=s.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):s.followCounts[0];return a.cache&&st(["followInfo","get",e],i,{cachedAt:o}),{data:i,cachedAt:o}};gr.locally=e=>{const t=Ye();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=at(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const pr=e=>{const t=async t=>{const[{data:n},{data:a}]=await Promise.all([gr(t.from),gr(t.to)]);e(n),e(a)},n=[or("follow.created",t),or("follow.requested",t),or("follow.accepted",t),or("follow.unfollowed",t),or("follow.requestCanceled",t),or("follow.requestDeclined",t),or("follow.followerDeleted",t),ir("local.follow.created",t),ir("local.follow.requested",t),ir("local.follow.accepted",t),ir("local.follow.unfollowed",t),ir("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},yr=e=>ir("local.follow.created",e),vr=e=>ir("local.follow.unfollowed",e),fr=e=>ir("local.follow.requested",e),br=e=>ir("local.follow.accepted",e),Ir=e=>ir("local.follow.requestDeclined",e);class Cr{constructor(e){const{http:t}=Ye();this.queryParams=e,this.http=t}loadFirstPage(){return this.onFetch("first")}loadNextPage(){return this.onFetch("next")}loadPreviousPage(){return this.onFetch("prev")}async onFetch(e="first"){var t,n,a,s;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let o;"prev"===e&&(o=this.previousToken),"next"===e&&(o=this.nextToken);const i=await this.getRequest(this.queryParams,o);return"first"===e&&(this.nextToken=null===(t=i.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=i.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(a=i.paging)||void 0===a?void 0:a.previous),"next"===e&&(this.nextToken=null===(s=i.paging)||void 0===s?void 0:s.next),i}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class wr extends Cr{async getRequest(e,t){const{limit:n=ge,userId:a}=e,s=Bn(e,["limit","userId"]),o=t?{token:t}:{limit:n},i=Ye().userId===a?"/api/v4/me/followers":`/api/v4/users/${a}/followers`,{data:r}=await this.http.get(i,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:!1})});return r}}class Sr{constructor(e,t){this.query=e,this.cacheKey=t}}var Or;!function(e){e.OnRequested="onRequested",e.OnAccepted="onAccepted",e.OnDeclined="onDeclined",e.OnCanceled="onCanceled",e.OnFollowed="onFollowed",e.OnUnfollowed="onUnfollowed",e.OnDeleted="onDeleted",e.OnUserDeleted="onUserDeleted"}(Or||(Or={}));class Tr extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.follows.map(Ze("follow"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Ze("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&a){switch(e){case Or.OnDeclined:case Or.OnCanceled:case Or.OnUnfollowed:case Or.OnDeleted:a.data=a.data.filter((e=>e!==Ze("follow")(t)));break;case Or.OnRequested:case Or.OnAccepted:case Or.OnFollowed:a.data=[...new Set([Ze("follow")(t),...a.data])]}st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ar{constructor(e){const{http:t}=Ye();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class Rr{constructor(e,t,n,a){this.paginationController=e,this.queryStreamId=t,this.cacheKey=n,this.callback=a}async refresh(){try{let e;if(e=this.paginationController instanceof Ar?await this.paginationController.onFetch():await this.paginationController.loadFirstPage(),!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next",refresh:!0}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}loadPage({initial:e=!1,direction:t="next"}){this.setup(),this.notifyChange({origin:"local",loading:!0}),e?this.refresh():"prev"===t?this.loadPrevPage():"next"===t&&this.loadNextPage()}async loadNextPage(){try{if(this.paginationController instanceof Ar)return;const e=await this.paginationController.loadNextPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}async loadPrevPage(){try{if(this.paginationController instanceof Ar)return;const e=await this.paginationController.loadPreviousPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"prev"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}shouldNotify(e){const t=e.map(nr).map(ar);return!Fa(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function Pr(e){return null!=e}const Dr=({userId:e})=>t=>{const n=Ye();return xt(n,"user.deleted","user.deleted",(n=>{const a=eo(n);Fn(a);const s=at(["follow","get",Ze("follow")({from:a.users[0].userId,to:e})]);s&&t(null==s?void 0:s.data)}))};class Ur extends Rr{constructor(e,t){const n=R.default(Object.assign(Object.assign({},e),{type:"follower"})),a=["follow","collection",n];super(new wr(e),n,a,t),this.query=e,this.queryStreamController=new Tr(this.query,this.cacheKey,this.notifyChange.bind(this),Jo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:rr,action:Or.OnFollowed},{fn:cr,action:Or.OnUnfollowed},{fn:hr,action:Or.OnAccepted},{fn:mr,action:Or.OnDeclined},{fn:ur,action:Or.OnCanceled},{fn:dr,action:Or.OnDeleted},{fn:br,action:Or.OnAccepted},{fn:Ir,action:Or.OnDeclined},{fn:yr,action:Or.OnFollowed},{fn:vr,action:Or.OnUnfollowed},{fn:Dr({userId:this.query.userId}),action:Or.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["follow","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=at(["user","get",e.from]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}class kr extends Cr{async getRequest(e,t){const{limit:n=ge,userId:a}=e,s=Bn(e,["limit","userId"]),o=t?{token:t}:{limit:n},i=Ye().userId===a?"/api/v4/me/following":`/api/v4/users/${a}/following`,{data:r}=await this.http.get(i,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:!1})});return r}}class jr extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.follows.map(Ze("follow"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Ze("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&a){switch(e){case Or.OnDeclined:case Or.OnCanceled:case Or.OnUnfollowed:case Or.OnDeleted:a.data=a.data.filter((e=>e!==Ze("follow")(t)));break;case Or.OnRequested:case Or.OnAccepted:case Or.OnFollowed:a.data=[...new Set([Ze("follow")(t),...a.data])]}st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Er=({userId:e})=>t=>{const n=Ye();return xt(n,"user.deleted","user.deleted",(n=>{const a=eo(n);Fn(a);const s=at(["follow","get",Ze("follow")({from:e,to:a.users[0].userId})]);s&&t(null==s?void 0:s.data)}))};class Mr extends Rr{constructor(e,t){const n=R.default(Object.assign(Object.assign({},e),{type:"following"})),a=["follow","collection",n];super(new kr(e),n,a,t),this.query=e,this.queryStreamController=new jr(this.query,this.cacheKey,this.notifyChange.bind(this),Ho),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:lr,action:Or.OnRequested},{fn:hr,action:Or.OnAccepted},{fn:mr,action:Or.OnDeclined},{fn:ur,action:Or.OnCanceled},{fn:rr,action:Or.OnFollowed},{fn:cr,action:Or.OnUnfollowed},{fn:dr,action:Or.OnDeleted},{fn:fr,action:Or.OnRequested},{fn:br,action:Or.OnAccepted},{fn:Ir,action:Or.OnDeclined},{fn:yr,action:Or.OnFollowed},{fn:vr,action:Or.OnUnfollowed},{fn:Er({userId:this.query.userId}),action:Or.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["follow","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=at(["user","get",e.to]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}const qr=(e,t,n,a,s,o)=>{const{forceDispatch:i,callbackDataSelector:r,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},o),{cache:d}=Ye();let l;d||console.log("For using Live Object feature you need to enable Cache!");let u=!1;const h=[],m=e=>{const{data:n}=e,a=Bn(e,["data"]);c&&!c(n,l)||t(Object.assign({data:r(n)},a)),l=nr(n)};return h.push(...s.map((t=>t((t=>((t,a=!1)=>{e===t[n]&&(l&&!a&&Fa(l,t)||m({loading:!1,data:t,origin:"event"}))})(t,i)))))),(()=>{const t=_e(a,e,!0);$e(t,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{s===be?(m({data:t,origin:a,loading:!1,error:new Ve(fe,800800,"error")}),u=!0,h.forEach((e=>e()))):u||m({loading:n,data:t,origin:a,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var xr=Object.freeze({__proto__:null,blockUser:async e=>{const t=Ye();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),a=t.cache&&Date.now(),{follows:s,followCounts:o}=n,i={follows:s};t.cache&&(Fn(i,{cachedAt:a}),it(["followInfo","get",e],o[0],{cachedAt:a}));const r={follows:s.map((e=>{const t=Object.assign(Object.assign({},e),{to:e.from,from:e.to,status:"none"});return"blocked"===e.status?t:e}))},c=Go(r);return Nt("local.follow.unfollowed",c),n},unBlockUser:async e=>{const t=Ye();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),a=t.cache&&Date.now(),{follows:s,followCounts:o}=n,i={follows:s};t.cache&&(Fn(i,{cachedAt:a}),it(["followInfo","get",e],o[0],{cachedAt:a}));const r=Go(i);return Nt("local.follow.created",r),n},onUserDidBlock:Yo,onUserDidUnblock:Wo,follow:async e=>{const t=Ye();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const s=Go(n);return"accepted"===n.follows[0].status?Nt("local.follow.created",s):Nt("local.follow.requested",s),{data:n.follows[0],cachedAt:a}},unfollow:async e=>{const t=Ye();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Fn(n);const a=Go(n);return Nt("local.follow.unfollowed",a),!0},acceptMyFollower:async e=>{const t=Ye();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Fn(n);const a=Go(n);return Nt("local.follow.accepted",a),!0},declineMyFollower:async e=>{const t=Ye();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Fn(n);const a=Go(n);return Nt("local.follow.requestDeclined",a),!0},onUserFollowed:rr,onUserUnfollowed:cr,onFollowerDeleted:dr,onFollowerRequested:lr,onFollowRequestCanceled:ur,onFollowRequestAccepted:hr,onFollowRequestDeclined:mr,onFollowInfoUpdated:pr,onLocalUserFollowed:yr,onLocalUserUnfollowed:vr,onLocalFollowerRequested:fr,onLocalFollowRequestAccepted:br,onLocalFollowRequestDeclined:Ir,getFollowers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getFollowers(tmpid: ${o}) > listen`);const i=new Ur(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getFollowers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();a(`getFollowings(tmpid: ${o}) > listen`);const i=new Mr(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getFollowings(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getFollowInfo:(e,t)=>qr(e,t,"userId",gr,[pr],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=Ut();return qr(t,e,"userId",gr,[pr],{forceDispatch:!0})}});function Nr(e,t){return e.map((e=>{const n=at(["community","get",e.communityId]);if((null==n?void 0:n.data)&&(null==n?void 0:n.data.hasOwnProperty("isJoined")))return Object.assign(Object.assign({},n.data),e);const a=void 0!==e.isJoined?e.isJoined:t.some((t=>function(e,t){const{userId:n}=Ut();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:a})}))}const Kr=e=>{var t;return null!==(t=Object.keys(x).find((t=>e.needApprovalOnPostCreation===x[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===x[t].onlyAdminCanPost)))&&void 0!==t?t:N};function Fr({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,a=Bn(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:Kr({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},a)}))}const _r=e=>{const t=Fr({communities:e.communities}),n=e.users.map(pa),a=e.communityUsers.map((e=>{const t=n.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),s=Nr(t,a);return Object.assign(Object.assign({},e),{users:e.users.map(pa),communities:s,communityUsers:a})},Br=e=>{const t=e.joinRequests.map((e=>Object.assign(Object.assign({},e),{joinRequestId:e._id}))),n=e.users.map(pa);return Object.assign(Object.assign({},e),{joinRequests:t,users:n})},$r=e=>{const t=Fr({communities:e.communities}),n=e.communityUsers.map((t=>{const n=e.users.find((e=>e.userId===t.userId));return Object.assign(Object.assign({},t),{user:n})})),a=Nr(t,n);return Object.assign(Object.assign({},e),{communities:a,communityUsers:n})},Lr=e=>{const{postSetting:t,storySetting:n}=e,a=Bn(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},a),t?x[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},Qr=e=>{var t=Bn(e,["searchResult"]);const n=_r(t);return Object.assign({},n)},Vr=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=at(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return Bt(n)},cancel:async()=>{await(async e=>{var t;const n=Ye();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:a}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),s=null===(t=at(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(it(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),Nt("local.joinRequest.deleted",[s])),a.success})(e)},approve:async()=>{await(async e=>{var t;const n=Ye();n.log("joinRequest/approveJoinRequest",e.joinRequestId);const{data:a}=await n.http.post(`/api/v4/communities/${e.targetId}/join/approve`,{userId:e.requestorInternalId}),s=null===(t=at(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(it(["joinRequest","get",e.joinRequestId],{status:"approved"}),Nt("local.joinRequest.updated",[s])),a.success})(e)},reject:async()=>{await(async e=>{var t;const n=Ye();n.log("joinRequest/rejectJoinRequest",e.joinRequestId);const{data:a}=await n.http.post(`/api/v4/communities/${e.targetId}/join/reject`,{userId:e.requestorInternalId}),s=null===(t=at(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(it(["joinRequest","get",e.joinRequestId],{status:"rejected"}),Nt("local.joinRequest.updated",[s])),a.success})(e)}});class Jr extends Cr{async getRequest(e,t){const{limit:n=20,communityId:a}=e,s=Bn(e,["limit","communityId"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get(`/api/v4/communities/${a}/join`,{params:Object.assign(Object.assign({},s),{options:o})});return i}}var Hr;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Hr||(Hr={}));class Gr extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.joinRequests.map((e=>Ze("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Ze("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Hr.OnLocalJoinRequestUpdated){if(!a.data.find((e=>e===t[0].joinRequestId)))return}e===Hr.OnLocalJoinRequestCreated&&(a.data=[...new Set([...t.map((e=>e.joinRequestId)),...a.data])]),e===Hr.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>e!==t[0].joinRequestId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const zr=e=>{const t=Ye(),n=[xt(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Yr=e=>{const t=Ye(),n=[xt(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Wr=e=>{const t=Ye(),n=[xt(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Xr extends Rr{constructor(e,t){const n=R.default(e),a=["joinRequest","collection",n];super(new Jr(e),n,a,t),this.query=e,this.queryStreamController=new Gr(this.query,this.cacheKey,this.notifyChange.bind(this),Br),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const a=e;this.queryStreamController.appendToQueryStream(a,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:zr,action:Hr.OnLocalJoinRequestCreated},{fn:Yr,action:Hr.OnLocalJoinRequestUpdated},{fn:Wr,action:Hr.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(s.data.map((e=>at(["joinRequest","get",e]))).filter(Pr).map((({data:e})=>e)).map(Vr));(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.status&&(t=t.filter((e=>e.status===this.query.status)));const n=(()=>"firstCreated"===this.query.sortBy?Ct:St)();return t=t.sort(n),t}}const Zr=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),ec=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map(Zr),users:e.users.map(pa)}),tc=async e=>{const t=Ye();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),a=ec(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),Nt("local.invitation.created",a.invitations),{data:a.invitations,cachedAt:s}},nc=e=>Object.assign(Object.assign({},e),{users:e.users.map(pa),invitations:e.invitations.map(Zr)}),ac=e=>Object.assign(Object.assign({},e),{get user(){const t=at(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return Bt(t.data)},get createdBy(){const t=at(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return Bt(t.data)},get target(){if("community"===e.targetType){const t=at(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=Ye();n.log("invitation/acceptInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/accept`),s=null===(t=at(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(it(["invitation","get",e],{status:"approved"}),Nt("local.invitation.updated",[s])),a.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=Ye();n.log("invitation/rejectInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/reject`),s=null===(t=at(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(it(["invitation","get",e],{status:"rejected"}),Nt("local.invitation.updated",[s])),a.success})(e._id)}}),sc=async e=>{const t=Ye();t.log("invitation/getInvitation",e.targetType,e.targetId,e.type);const{data:n}=await t.http.get("/api/v1/invitations/me",{params:e}),a=nc(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.invitations[0]?ac(a.invitations[0]):void 0,cachedAt:s}};var oc;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationCanceled="onLocalInvitationCanceled"}(oc||(oc={}));class ic extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/invitations",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class rc extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.invitations.map(Ze("invitation"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Ze("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===oc.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}e===oc.OnLocalInvitationCreated&&(a.data=[...new Set([...t.map((e=>e.invitationId)),...a.data])]),e===oc.OnLocalInvitationDeleted&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const cc=e=>{const t=Ye(),n=[xt(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},dc=e=>{const t=Ye(),n=[xt(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},lc=e=>{const t=Ye(),n=[xt(t,"onLocalInvitationCanceled","local.invitation.canceled",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class uc extends Rr{constructor(e,t){const n=R.default(e),a=["invitation","collection",n];super(new ic(e),n,a,t),this.query=e,this.queryStreamController=new rc(this.query,this.cacheKey,this.notifyChange.bind(this),ec),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:cc,action:oc.OnLocalInvitationCreated},{fn:dc,action:oc.OnLocalInvitationUpdated},{fn:lc,action:oc.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["invitation","get",e]))).filter(Pr).map((({data:e})=>ac(e))))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?Ct:St)();return t=t.sort(n),t}}const hc=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=at(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),mc=e=>Object.assign(Object.assign({},e),{get categories(){var t;return(null!==(t=null==e?void 0:e.categoryIds)&&void 0!==t?t:[]).map((e=>{const t=at(["category","get",e]);if(null==t?void 0:t.data)return hc(t.data)})).filter((e=>!!e))},get avatar(){var t;if(!e.avatarFileId)return;return null===(t=at(["file","get",e.avatarFileId]))||void 0===t?void 0:t.data},createInvitations:async t=>{await tc({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getInvitations: (tmpid: ${o}) > listen`);const i=new uc(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getInvitations (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{targetId:e.communityId,targetType:"community",type:"communityMemberInvite"}),n),getInvitation:async()=>{const{data:t}=await sc({targetType:"community",targetId:e.communityId});return t},join:async()=>(async e=>{var t;const n=Ye();n.log("community/joinRequest",e);const{data:a}=await n.http.post(`/api/v4/communities/${e}/join`),s=Br(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const i="approved"===s.joinRequests[0].status?"success":"pending";if("success"===i&&n.cache){const n=null===(t=at(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});it(["community","get",e],t)}}return Nt("v4.local.community.joined",s.joinRequests),"success"===i?{status:i}:{status:i,request:Vr(s.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getJoinRequests: (tmpid: ${o}) > listen`);const i=new Xr(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getJoinRequests (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{communityId:e.communityId}),n),getMyJoinRequest:async()=>{const{data:t}=await(async e=>{const t=Ye();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),a=Br(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.joinRequests[0]?Vr(a.joinRequests[0]):void 0,cachedAt:s}})(e.communityId);return t}});class gc{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=at(["story-expire",this._targetId]),this.cacheStoreSeenTime=at(["story-last-seen",this._targetId]),this.getTotalStoryByStatus()}get lastStoryExpiresAt(){return this._lastStoryExpiresAt?new Date(this._lastStoryExpiresAt).getTime():0}get lastStorySeenExpiresAt(){return this._lastStorySeenExpiresAt?new Date(this._lastStorySeenExpiresAt).getTime():0}get localLastStoryExpires(){var e,t;return(null===(e=this.cacheStoryExpireTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoryExpireTime)||void 0===t?void 0:t.data).getTime():0}get localLastStorySeenExpiresAt(){var e,t;return(null===(e=this.cacheStoreSeenTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoreSeenTime)||void 0===t?void 0:t.data).getTime():0}get isContainUnSyncedStory(){const e=at(["story-sync-state",this._targetId]);return!!(null==e?void 0:e.data)&&["syncing","error"].includes(e.data)}getLocalLastSortingDate(){return this.isContainUnSyncedStory?this.localLastStoryExpires:this.lastStoryExpiresAt}getHasUnseenFlag(){const e=(new Date).getTime(),t=Math.max(this.lastStorySeenExpiresAt,this.localLastStorySeenExpiresAt);return at(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=nt(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:a,isDeleted:s}}=t;return n!==this._targetId||s||(e[a]+=1),e}),{syncing:0,error:0,synced:0});this._errorStoriesCount=t.error,this._syncingStoriesCount=t.syncing}get syncingStoriesCount(){return this._syncingStoriesCount}get failedStoriesCount(){return this._errorStoriesCount}}const pc=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:a,lastStorySeenExpiresAt:s,targetUpdatedAt:o,localFilter:i}=e,r=new gc(n,a,s);return{targetType:t,targetId:n,lastStoryExpiresAt:a,updatedAt:o,hasUnseen:r.getHasUnseenFlag(),syncingStoriesCount:r.syncingStoriesCount,failedStoriesCount:r.failedStoriesCount,localFilter:i,localLastExpires:r.localLastStoryExpires,localLastSeen:r.localLastStorySeenExpiresAt,localSortingDate:r.getLocalLastSortingDate()}},yc=async e=>{const t=Ye();let n;if(t.log("user/createChannel",e),"conversation"===(null==e?void 0:e.type))n=await t.http.post("/api/v3/channels/conversation",Object.assign(Object.assign({},e),{isDistinct:!0}));else{const{isPublic:a}=e,s=Bn(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},s),{isPublic:"community"===(null==e?void 0:e.type)?a:void 0}))}const a=await Ua(n.data),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{channels:o}=a;return{data:Us(o[0]),cachedAt:s}},vc=async e=>{const t=Ye();let n;t.log("channel/getChannel",e),ea("channel",e);try{const{data:a}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await Ua(a),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&ja(a)}catch(t){throw Pe(null==t?void 0:t.code)&&_n("channel",e),t}const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{channels:s}=n;return{data:s.find((t=>t.channelId===e)),cachedAt:a}};vc.locally=e=>{var t;const n=Ye();if(n.log("channel/getChannel.locally",e),!n.cache)return;const a=null===(t=nt(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId===e));return a&&0!==(null==a?void 0:a.length)?{data:a[0].data,cachedAt:a[0].cachedAt}:void 0};const fc=Symbol("getWatcherUrls"),bc=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=at(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=at(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=at(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=at(["user","get",e.userId]))||void 0===t?void 0:t.data},get childStreams(){return e.childStreamIds&&0!==e.childStreamIds.length?e.childStreamIds.map((e=>{var t;const n=null===(t=at(["stream","get",e]))||void 0===t?void 0:t.data;if(n)return bc(n)})).filter(Pr):[]},getLiveChat:()=>(async e=>{var t;const n=Ye();if(n.log("stream/getLiveChat",e.streamId),e.channelId){const n=null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data;if(n)return Ds(Us(n));const{data:a}=await vc(e.channelId);return Ds(Us(a))}if(e.userId===n.userId){const{data:t}=await yc({type:"live",postId:e.postId,videoStreamId:e.streamId});return ot(["stream","get",e.streamId],{channelId:t.channelId}),t}})(e),isBanned:!e.watcherUrl,watcherUrl:null,get[fc](){return e.watcherUrl}}),Ic=e=>Object.assign(Object.assign({},e),{get target(){const t={type:e.targetType};if("user"===e.targetType)return Object.assign(Object.assign({},t),{userId:e.targetId});if("content"===t.type)return Object.assign(Object.assign({},t),{contentId:e.targetId});if("community"===t.type){const n=at(["communityUsers","get",`${e.targetId}#${e.userId}`]);return Object.assign(Object.assign({},t),{communityId:e.targetId,creatorMember:null==n?void 0:n.data})}return{type:"unknown"}},get creator(){const t=at(["user","get",e.userId]);if(null==t?void 0:t.data)return Bt(t.data)},get childrenComment(){return e.children.map((e=>{const t=at(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(Pr).map((e=>Ic(e)))}});function Cc(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}function wc(e){return!(!e.data||"string"==typeof e.data||!("streamId"in e.data)||"liveStream"!==e.dataType)}class Sc{constructor(){this.sessions=new Map}addSession(e){this.sessions.set(e.sessionId,e)}getSession(e){return this.sessions.get(e)}updateSession(e,t){const n=this.sessions.get(e);n&&this.sessions.set(e,Object.assign(Object.assign({},n),t))}getSessionsByState(e){return Array.from(this.sessions.values()).filter((t=>t.syncState===e))}deleteSession(e){this.sessions.delete(e)}getPendingSessions(){return this.getSessionsByState("PENDING")}getSyncingSessions(){return this.getSessionsByState("SYNCING")}}let Oc=null;const Tc=()=>(Oc||(Oc=new Sc),Oc),Ac={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},Rc="-----BEGIN PRIVATE KEY-----";function Pc(e){const n=new Uint8Array(e);let a="";return n.forEach((e=>{a+=String.fromCharCode(e)})),t.btoa(a)}function Dc(e){return e<128?new Uint8Array([e]):e<256?new Uint8Array([129,e]):new Uint8Array([130,e>>8&255,255&e])}async function Uc(e){let n=e;n=e.includes(Rc)?e.substring(Rc.length,e.length-"-----END PRIVATE KEY-----".length).replace(/\s/g,""):e.replace(/\s/g,"");const a=t.atob(n),s=new Uint8Array(a.length);for(let e=0;e<a.length;e+=1)s[e]=a.charCodeAt(e);const o=function(e){const t=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),n=new Uint8Array([2,1,0]),a=Dc(e.length),s=n.length+t.length+1+a.length+e.length,o=Dc(s),i=new Uint8Array(1+o.length+s);let r=0;return i[r]=48,r+=1,i.set(o,r),r+=o.length,i.set(n,r),r+=n.length,i.set(t,r),r+=t.length,i[r]=4,r+=1,i.set(a,r),r+=a.length,i.set(e,r),i}(s);return await crypto.subtle.importKey("pkcs8",o.buffer,Ac,!1,["sign"])}async function kc({timestamp:e,rooms:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),a=T.default.v4(),s=`nonceStr=${a}&timestamp=${e}&data=${n}==`,o=(new TextEncoder).encode(s),i=await Uc("-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDAARz+hmBgi8pJ\nQb8LeY41gtHhk+ACMwRfhsn7GqpqRQNG2qU0755mzZuVDUqjQMGSo8THJB7O+OJs\nflbZRkFXlFoFOVNw1UpNOgwEQZ6wB9oRwzepTJAfF1sVhm/o/ixvXh1zDFNDy6yZ\npXyiiJHUVxqyjllZhxnwdvjoVtDs6hW6awG09bB9nh/TTejlUKXoAgzqVwu/1QMu\nUVViET495elEe19aUarEy+oL2iKeXCEvqda/pWNBdbieFyJvvZ08HN8dPuT88wq2\njZLEAth1vrwQ2IAa4ktaLcBQdLJgIkrbDvAiVZ8lQAjS/bq5vXQikTGvoPlC5bbn\nvuOM/3eLAgMBAAECggEAVZ+peHAghq2QVj71nX5lxsNCKaCyYwixSJBpfouTt7Rz\nE6PpzMOXFi1W1o+I22jDakuSM2SOQKqI/u0QefB0r0O/KVk5NrZHXk0mkrdYtxOp\nUgaGyf8UvmjB+8VqHrNKyZdk9qtmbnNj01kTTcAtmE4H39zPR7eR/8Rul94vaZbs\nwCnKJS3mLT3JxyGug6lxanveKkjG+CKC1nJQYWaxCJxaFSzbwXQPvDhB+TvrIbee\npd5v4EAyEJohpr+T9oDGGJkb/KARBZCtwLyB976PKJwwBA8MRVL1i5QwawuMiMq5\nUtnOnbGKtCeFzaLbNU0Qi8bqyims84EQxC6DOu1fkQKBgQDdvsoBsEhsOXV7hlIJ\naEd0eSJZVkdqimxH8uGoMM2FeNaOrcB6yBXqTSP0R3OIyf8eaY6yjRvP30ZNXcll\n/gD3O1Mu6YmWQdt1W2WA6pKOsUuPXasf0pdOF7IiFZKlSabz5YHXFqwVuqm8loaj\nsXel3YWqPVdHiankE7tz+3ssnQKBgQDdqi4TNdD1MdEpihx19jr0QjUiXW3939FK\nqp30HESPEGDGQzXdmJgif9HhZb+cJSuWaHEbjgBrYahvgCF+y6LbEpOD+D/dmT+s\nDEAQaR84sah6dokwPjV8fjBSrcVFjCS+doxv0d3p/9OUEeyUhFrY03nxtIEYkLIE\n/Zvn37b4RwKBgQCLENVFe9XfsaVhQ5r9dV2iyTlmh7qgMZG5CbTFs12hQGhm8McO\n+Z7s41YSJCFr/yq1WwP4LJDtrBw99vyQr1zRsG35tNLp3gGRNzGQSQyC2uQFVHw2\np+7mNewsfhUK/gbrXNsyFnDz6635rPlhfbII3sWuP2wWXFqkxE9CbMwR7QKBgQC6\nawDMzxmo2/iYArrkyevSuEuPVxvFwpF1RgAI6C0QVCnPE38dmdN4UB7mfHekje4W\nVEercMURidPp0cxZolCYBQtilUjAyL0vqC3In1/Ogjq6oy3FEMxSop1pKxMY5j+Q\nnoqFD+6deLUrddeNH7J3X4LSr4dSbX4JjG+tlgt+yQKBgQCuwTL4hA6KqeInQ0Ta\n9VQX5Qr8hFlqJz1gpymi/k63tW/Ob8yedbg3WWNWyShwRMFYyY9S81ITFWM95uL6\nvF3x9rmRjwElJw9PMwVu6dmf/CO0Z1wzXSp2VVD12gbrUD/0/d7MUoJ9LgC8X8f/\nn0txLHYGHbx+nf95+JUg6lV3hg==\n-----END PRIVATE KEY-----");return{signature:Pc(await crypto.subtle.sign(Ac,i,o)),nonceStr:a}}async function jc(){const e=Tc(),t=e.getPendingSessions();if(0===t.length)return!0;try{const n=(new Date).toISOString(),a=t.map((e=>({sessionId:e.sessionId,roomId:e.roomId,watchSeconds:e.watchSeconds,startTime:e.startTime.toISOString(),endTime:e.endTime?e.endTime.toISOString():""}))),s=await kc({timestamp:n,rooms:a});if(!s||!s.signature)throw new Error("Signature is undefined");t.forEach((t=>{e.updateSession(t.sessionId,{syncState:"SYNCING"})}));const o={signature:s.signature,nonceStr:s.nonceStr,timestamp:n,rooms:a},i=Ye();return await i.http.post("/api/v3/user-event/room",o),t.forEach((t=>{e.updateSession(t.sessionId,{syncState:"SYNCED",syncedAt:new Date})})),!0}catch(n){return console.error("[SDK syncWatchSessions] ERROR caught:",(null==n?void 0:n.message)||n),t.forEach((t=>{const n=e.getSession(t.sessionId);if(n){const a=n.retryCount+1;a>=3?e.deleteSession(t.sessionId):e.updateSession(t.sessionId,{syncState:"PENDING",retryCount:a})}})),!1}}const Ec=["live","recorded"];class Mc{constructor(e){this.storage=Tc(),this.client=Ye(),this.room=e}async createWatchSession(e){if(!Ec.includes(this.room.status))throw new Ve("room is not in watchable state",5e5,"error");const t=("live"===this.room.status?"room_":"room_playback_")+T.default.v4(),n={sessionId:t,roomId:this.room.roomId,watchSeconds:0,startTime:e,endTime:null,syncState:"PENDING",syncedAt:null,retryCount:0};return this.storage.addSession(n),t}async updateWatchSession(e,t,n){if(!this.storage.getSession(e))throw new Error(`Watch session ${e} not found`);this.storage.updateSession(e,{watchSeconds:t,endTime:n})}syncPendingWatchSessions(){const e=Math.floor(25001*Math.random())+5e3;this.client.log("room/RoomAnalytics: syncPendingWatchSessions called, jitter delay:",`${e}ms`),setTimeout((async()=>{this.client.log("room/RoomAnalytics: Jitter delay completed, starting sync process");try{const e=this.storage.getSyncingSessions();this.client.log("room/RoomAnalytics: SYNCING sessions to reset:",e.length),e.forEach((e=>{this.storage.updateSession(e.sessionId,{syncState:"PENDING"})})),await((e=6e4)=>new Promise((t=>{if("undefined"==typeof navigator||void 0===navigator.onLine)return void t();const n=Date.now(),a=()=>{navigator.onLine||Date.now()-n>=e?t():setTimeout(a,1e3)};a()})))(6e4),this.client.log("room/RoomAnalytics: Network available"),this.client.log("room/RoomAnalytics: Calling syncWatchSessions()"),await jc(),this.client.log("room/RoomAnalytics: syncWatchSessions completed")}catch(e){console.error("Failed to sync watch sessions:",e)}}),e)}}const qc=e=>Object.assign(Object.assign({},e),{get post(){var t;if("post"===e.referenceType)return null===(t=at(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=at(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;const n=null===(t=at(["user","get",e.createdBy]))||void 0===t?void 0:t.data;return n?Bt(n):n},get childRooms(){return e.childRoomIds&&0!==e.childRoomIds.length?e.childRoomIds.map((e=>{var t;const n=null===(t=at(["room","get",e]))||void 0===t?void 0:t.data;if(n)return qc(n)})).filter(Pr):[]},participants:e.participants.map((e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=at(["user","get",e.userId]))||void 0===t?void 0:t.data;return n?Bt(n):n}}))),getLiveChat:()=>(async e=>{var t;const n=Ye();if(n.log("room/getLiveChat",e.roomId),e.liveChannelId){const n=null===(t=at(["channel","get",e.liveChannelId]))||void 0===t?void 0:t.data;if(n)return Ds(Us(n));const{data:a}=await vc(e.liveChannelId);return Ds(Us(a))}if(e.createdBy===n.userId){const{data:t}=await yc({type:"live",postId:e.referenceId,roomId:e.roomId});return ot(["room","get",e.roomId],{liveChannelId:t.channelId}),t}})(e),createInvitation:t=>tc({type:"livestreamCohostInvite",targetType:"room",targetId:e.roomId,userIds:[t]}),getInvitations:async()=>{const{data:t}=await sc({targetId:e.roomId,targetType:"room",type:"livestreamCohostInvite"});return t},analytics(){return new Mc(this)}}),xc=e=>Object.assign(Object.assign({},e),{answers:e.answers.map((e=>Object.assign(Object.assign({},e),{get image(){var t;if(e.fileId)return null===(t=at(["file","get",e.fileId]))||void 0===t?void 0:t.data}})))}),Nc=e=>{const t=fo();return Object.assign(Object.assign({},e),{analytics:{markAsClicked:(n,a,s)=>{t.markProductAsClicked(e,n,a,s)},markAsViewed:(n,a,s)=>{t.markProductAsViewed(e,n,a,s)}}})},Kc=e=>{var t,n,a;if(!e)return e;if("video"===e.type){const a=null===(n=null===(t=e.attributes)||void 0===t?void 0:t.metadata)||void 0===n?void 0:n.video;return Object.assign(Object.assign({},e),{getWidth:()=>{var e;return null!==(e=null==a?void 0:a.width)&&void 0!==e?e:0},getHeight:()=>{var e;return null!==(e=null==a?void 0:a.height)&&void 0!==e?e:0},getRotation:()=>{var e;return null!==(e=null==a?void 0:a.rotation)&&void 0!==e?e:0}})}if("image"===e.type){const t=null===(a=e.attributes)||void 0===a?void 0:a.metadata;return Object.assign(Object.assign({},e),{getWidth:()=>{var e;return null!==(e=null==t?void 0:t.width)&&void 0!==e?e:0},getHeight:()=>{var e;return null!==(e=null==t?void 0:t.height)&&void 0!==e?e:0}})}return e},Fc=e=>Xn(e,{childrenPosts:e.children.map((e=>{var t;return null===(t=at(["post","get",e]))||void 0===t?void 0:t.data})).filter(Pr).map(Fc),analytics:{markAsViewed:()=>{fo().markPostAsViewed(e.postId)},markAsMeaningfullyViewed:t=>{fo().markPostAsMeaningfullyViewed(e.postId,t)}},get productTags(){var t,n;return null!==(n=null===(t=e.productTags)||void 0===t?void 0:t.map((e=>(e=>{var t;const n=null===(t=at(["product","get",e.productId]))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{product:n?Nc(n):void 0})})(e))))&&void 0!==n?n:[]},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=at(["comment","get",e]))||void 0===t?void 0:t.data;return n?Ic(n):null})).filter(Boolean)||[]},get creator(){if(!e.postedUserId)return;const t=at(["user","get",e.postedUserId]);return(null==t?void 0:t.data)?Bt(t.data):void 0},get targetCommunity(){var t;if(!e.targetId)return;const n=null===(t=at(["community","get",e.targetId]))||void 0===t?void 0:t.data;return n?mc(n):void 0},getImageInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return Kc(null===(n=at(["file","get",e.data.fileId]))||void 0===n?void 0:n.data)},getVideoInfo(){var t,n,a;const s=Cc(e)?null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original:void 0;if(s)return Kc(null===(a=at(["file","get",s]))||void 0===a?void 0:a.data)},getVideoThumbnailInfo(){var t,n;const a=Cc(e)?null===(t=e.data)||void 0===t?void 0:t.thumbnailFileId:void 0;if(a)return Kc(null===(n=at(["file","get",a]))||void 0===n?void 0:n.data)},getFileInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"file"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=at(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getLivestreamInfo(){var t,n;if(!wc(e)||!(null===(t=e.data)||void 0===t?void 0:t.streamId))return;const a=null===(n=at(["stream","get",e.data.streamId]))||void 0===n?void 0:n.data;return a?bc(a):void 0},getPollInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("pollId"in e.data)||"poll"!==e.dataType)}(e)||!(null===(t=e.data)||void 0===t?void 0:t.pollId))return;const a=null===(n=at(["poll","get",e.data.pollId]))||void 0===n?void 0:n.data;return a?xc(a):void 0},getClipInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"clip"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=at(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getAudioInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"audio"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=at(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getRoomInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("roomId"in e.data)||"room"!==e.dataType)}(e)||!(null===(t=e.data)||void 0===t?void 0:t.roomId))return;const a=null===(n=at(["room","get",e.data.roomId]))||void 0===n?void 0:n.data;return a?qc(a):void 0},getEventInfo(){var t,n;if(!function(e){return"event"===e.dataType||"event"===e.structureType}(e))return;const a=e=>{if(e&&"object"==typeof e&&"eventId"in e){const t=e.eventId;return"string"==typeof t?t:void 0}},s=a(e.data),o=null!=s?s:null===(t=e.children)||void 0===t?void 0:t.map((e=>{var t;return null===(t=at(["post","get",e]))||void 0===t?void 0:t.data})).map((e=>a(null==e?void 0:e.data))).find(Boolean);if(!o)return;const i=null===(n=at(["event","get",o]))||void 0===n?void 0:n.data;return i?Object.assign(Object.assign({},i),{get creator(){const e=at(["user","get",i.userId]);if(null==e?void 0:e.data)return Bt(e.data)},get targetCommunity(){var e;if(!i.originId)return;const t=null===(e=at(["community","get",i.originId]))||void 0===e?void 0:e.data;return t?mc(t):void 0},get coverImage(){var e;if(i.coverImageFileId)return null===(e=at(["file","get",i.coverImageFileId]))||void 0===e?void 0:e.data}}):void 0}}),_c=(e,t)=>{"message"===e?Nt("local.message.updated",{messages:[t]}):"post"===e?Nt("post.updated",{posts:[t]}):"comment"===e?Nt("comment.updated",{comments:[t]}):"story"===e&&Nt("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Bc=async(e,t,n,a)=>{var s,o,i;const r=Ye();if(r.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ve("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:c}=await r.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:a});if(r.cache){const a=at([e,"get",t]);if(!a||(null===(s=a.data.myReactions)||void 0===s?void 0:s.includes(n)))return!0;const d=Object.assign(Object.assign({},a.data),{reactionsCount:a.data.reactionsCount+1,myReactions:[...null!==(o=a.data.myReactions)&&void 0!==o?o:[],n],reactions:Object.assign(Object.assign({},a.data.reactions),{[n]:(null!==(i=a.data.reactions[n])&&void 0!==i?i:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return Nt("local.comment.addReaction",{comment:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("post"===e)return Nt("local.post.addReaction",{post:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("story"===e)return Nt("local.story.reactionAdded",{story:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("message"===e)return it(["message","get",t],d),Nt("local.message.updated",{messages:[d]}),!0}return!0};Bc.optimistically=(e,t,n)=>{var a,s,o,i,r;const c=Ye();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const d=at([e,"get",t]);if(!(null==d?void 0:d.data)||(null===(a=d.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const l=Object.assign(Object.assign({},d.data),{reactionsCount:d.data.reactionsCount+1,myReactions:[...null!==(s=d.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},d.data.reactions),{[n]:(null!==(o=d.data.reactions[n])&&void 0!==o?o:0)+1})});return it([e,"get",t],l,{cachedAt:be}),_c(e,l),null!==(r=null===(i=null==l?void 0:l.myReactions)||void 0===i?void 0:i.includes(n))&&void 0!==r&&r};const $c=(e,t)=>{var n;return null!==(n=null!=t?t:(e=>{var t,n;const a={creatorId:"creatorPrivateId"in e?e.creatorPrivateId:e.creatorId,feedId:null!==(t=e.messageFeedId)&&void 0!==t?t:e.subChannelId,contentId:e.messageId};return null===(n=at(["messageMarker","get",Ze("messageMarker")(a)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},Lc=(e,t)=>{const n=t.publicId!==t.messageId;return(async(e,t,n,a)=>{var s,o;const i=Ye();if(i.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ve("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:r}=await i.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:a}});if(i.cache){const a=at([e,"get",t]);if(!a)return!0;const c=Object.assign(Object.assign({},a.data),{reactionsCount:Math.max(0,a.data.reactionsCount-1),myReactions:(null!==(s=a.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},a.data.reactions),{[n]:Math.max(0,(null!==(o=a.data.reactions[n])&&void 0!==o?o:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return Nt("local.comment.removeReaction",{comment:c,reactor:{reactionId:r.removedId,reactionName:n,userId:i.userId}}),!0;if("post"===e)return Nt("local.post.removeReaction",{post:c,reactor:{reactionId:r.removedId,reactionName:n,userId:i.userId}}),!0;if("story"===e)return Nt("local.story.reactionRemoved",{story:c,reactor:{userId:i.userId,reactionName:n,reactionId:r.removedId}}),!0;if("message"===e)return it(["message","get",t],c),Nt("local.message.updated",{messages:[c]}),!0}return!0})("message",n?t.publicId:t.messageId,e,n?3:5)},Qc=e=>Object.assign(Object.assign({},e),{users:e.users.map(pa)}),Vc=e=>Object.assign(Object.assign({},e),{get status(){return e.status},get userId(){return e.userId},get eventId(){return e.eventId},get respondedAt(){return e.respondedAt},get event(){const t=at(["event","get",e.eventId]);if(null==t?void 0:t.data)return t.data},get user(){const t=at(["user","get",e.userId]);if(null==t?void 0:t.data)return Bt(t.data)}}),Jc=e=>Object.assign(Object.assign({},e),{users:e.users.map(pa)}),Hc=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Jc(e);if(n.cache){Fn(a);const e=at(["event","get",a.events[0].eventId]);t(e.data)}else t(a.events[0])}))},Gc=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=Qc(e);if(n.cache){Fn(a);const e=at(["eventResponse","get",a.eventResponses[0].userId]);t(e.data)}else t(a.eventResponses[0])}))},zc=async e=>{const t=Ye();t.log("event/getMyRSVP",e);const{data:n}=await t.http.get(`/api/v1/events/${e}/me/rsvp`),a=Qc(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:Vc(a.eventResponses[0]),cachedAt:s}};var Yc;zc.locally=e=>{const t=Ye();if(t.log("event/getMyRSVP.locally",e),!t.cache)return;const n=at(["event","getMyRSVP",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0},function(e){e.OnEventCreated="onEventCreated",e.OnEventUpdated="onEventUpdated",e.OnEventDeleted="onEventDeleted",e.OnRSVPCreated="onRSVPCreated",e.OnRSVPUpdated="onRSVPUpdated"}(Yc||(Yc={}));class Wc extends Cr{async getRequest(e,t){const{limit:n=ge,eventId:a}=e,s=Bn(e,["limit","eventId"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get(`/api/v1/events/${a}/rsvp`,{params:Object.assign(Object.assign({},s),{options:o})});return i}}class Xc extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.eventResponses.map(Ze("eventResponse"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.eventResponses.map(Ze("eventResponse"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Yc.OnRSVPCreated&&(a.data=[...new Set([t.userId,...a.data])]),e===Yc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Zc=e=>Hc("event.created",e),ed=e=>Hc("event.updated",e),td=e=>Hc("event.deleted",e),nd=e=>Hc("local.event.created",e),ad=e=>Hc("local.event.updated",e),sd=e=>Hc("local.event.deleted",e),od=e=>Gc("event.rsvp.created",e),id=e=>Gc("event.rsvp.updated",e),rd=e=>Gc("local.rsvp.created",e),cd=e=>Gc("local.rsvp.updated",e);class dd extends Rr{constructor(e,t){const n=R.default(e),a=["eventResponse","collection",n];super(new Wc(e),n,a,t),this.query=e,this.queryStreamController=new Xc(this.query,this.cacheKey,this.notifyChange.bind(this),Qc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:od,action:Yc.OnRSVPCreated},{fn:id,action:Yc.OnRSVPUpdated},{fn:rd,action:Yc.OnRSVPCreated},{fn:cd,action:Yc.OnRSVPUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=s.data.map((e=>at(["eventResponse","get",e]))).filter(Pr).map((({data:e})=>Vc(e)));(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}const ld=(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getRSVPs: (tmpid: ${o}) > listen`);const i=new dd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getRSVPs (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},ud=e=>Object.assign(Object.assign({},e),{get creator(){const t=at(["user","get",e.userId]);if(null==t?void 0:t.data)return Bt(t.data)},get targetCommunity(){if(!e.originId)return;const t=at(["community","get",e.originId]);return(null==t?void 0:t.data)?mc(t.data):void 0},get coverImage(){if(!e.coverImageFileId)return;const t=at(["file","get",e.coverImageFileId]);return(null==t?void 0:t.data)?t.data:void 0},get post(){if(!e.postId)return;const t=at(["post","get",e.postId]);return(null==t?void 0:t.data)?Fc(t.data):void 0},get room(){var t;if(!e.postId)return;const n=null===(t=nt(["room","get"]))||void 0===t?void 0:t.filter((t=>t.data.referenceId===e.postId));return(null==n?void 0:n.length)&&n[0].data?qc(n[0].data):void 0},createRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ye();n.log("event/createRSVP",e,t);const{data:a}=await n.http.post(`/api/v1/events/${e}/rsvp`,{status:t});Nt("local.rsvp.created",a);const s=Qc(a),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),{data:Vc(s.eventResponses[0]),cachedAt:o}})(e.eventId,t);return n},updateRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ye();n.log("event/updateRSVP",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}/rsvp`,{status:t});Nt("local.rsvp.updated",a);const s=Qc(a),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),{data:Vc(s.eventResponses[0]),cachedAt:o}})(e.eventId,t);return n},getMyRSVP:async()=>{const{data:t}=await zc(e.eventId);return t},getRSVPs:(t,n)=>ld(Object.assign({eventId:e.eventId},t),n)}),hd={file:Kc,ad:e=>{const t=fo(),{image9_16:n,image1_1:a}=e,s=Bn(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},s),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const a=null===(t=at(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!a)return;const s=null===(n=at(["file","get",a.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},a),{avatar:s})},get image1_1(){const e=at(["file","get",a]);if(e)return e.data||void 0},get image9_16(){const e=at(["file","get",n]);if(e)return e.data||void 0}})},comment:Ic,post:Fc,user:Bt,category:hc,stream:bc,story:e=>{const t=fo(),n=at(["storyTarget","get",e.targetId]),a=at(["community","get",e.targetId]);return Object.assign(Object.assign({},e),{analytics:{markAsSeen:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsViewed(e)},markLinkAsClicked:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsClicked(e)}},get videoData(){var t,n;const a=at(["file","get",null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]);if(!a)return;const{data:s}=a;return s||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const a=at(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!a)return;const{data:s}=a;return s?Object.assign(Object.assign({},s),{fileUrl:`${s.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&(null==a?void 0:a.data))return mc(a.data)},get communityCategories(){if("community"!==e.targetType)return;if(!a)return;const{data:{categoryIds:t}}=a;return 0!==t.length?t.map((e=>{const t=at(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=at(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return Bt(t.data)},get storyTarget(){if(null==n?void 0:n.data)return pc(n.data)},get isSeen(){const t=at(["story-last-seen",e.targetId]);if(!(null==n?void 0:n.data))return!1;const a=(null==t?void 0:t.data)?new Date(t.data).getTime():0,s=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,o=new Date(e.expiresAt).getTime();return Math.max(a,s)>=o}})},storyTarget:pc,message:e=>{const t=Bn(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return $c(e).readCount},get deliveredCount(){return $c(e).deliveredCount},get creator(){var t;return null===(t=at(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>bi(e),addReaction:t=>((e,t)=>{const n=t.publicId!==t.messageId;return Bc("message",n?t.publicId:t.messageId,e,n?3:5)})(t,e),removeReaction:t=>Lc(t,e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=at(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return Bt(n)}}),channel:Ds,pinnedPost:e=>{var t;const n=at(["post","get",e.referenceId]),a=null===(t=nt(["user","get"]).find((t=>{var n;return(null===(n=t.data)||void 0===n?void 0:n.userInternalId)===e.pinnedBy})))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{pinnedBy:a,get post(){if(null==n?void 0:n.data)return Fc(n.data)},get target(){const e=at(["pinTarget","get",null==n?void 0:n.data.targetId]);if(null==e?void 0:e.data)return null==e?void 0:e.data}})},notificationTray:e=>Object.assign(Object.assign({},e),{isSeen:e.lastSeenAt>e.lastOccurredAt,isRecent:new Date(e.lastOccurredAt).getTime()>=Date.now()-6048e5,users:e.actors.map((({publicId:e})=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map((e=>Bt(e))),get event(){const t=at(["event","get",e.actionReferenceId]);if(null==t?void 0:t.data)return t.data}}),community:mc,invitation:ac,joinRequest:Vr,channelMember:Na,room:qc,event:ud,eventResponse:Vc,product:Nc,poll:xc},md=async e=>{const t=Ye();t.log("user/getUsers",e);const n=e.map((e=>encodeURIComponent(e))),{data:a}=await t.http.get("/api/v3/users/list",{params:{userIds:n}}),s=eo(a),o=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:o}),Nt("user.fetched",a),{data:s.users.map((e=>hd.user(e))),cachedAt:o}};md.locally=e=>{var t;const n=Ye();if(n.log("user/getUsers.locally",e),!n.cache)return;const a=e.map((e=>at(["user","get",e]))).filter(Boolean),s=a.map((({data:e})=>hd.user(e))),o=null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==a?void 0:a.length)<e.length?void 0:{data:s,cachedAt:o.cachedAt}};const gd=async(e,t)=>{var n;const a=Ye();a.log("user/flagUser",{userId:e,options:t});const s=(e=>{if(!e)return;const t={};return void 0!==e.reportType&&(t.reportType=e.reportType),void 0!==e.reason&&(t.reason=e.reason),void 0!==e.comment&&(t.comment=e.comment),Object.keys(t).length>0?t:void 0})(t),{data:o}=await a.http.post(`/api/v4/me/flags/${encodeURIComponent(e)}`,s),i=eo(o);return a.cache&&Fn(i),Nt("user.flagged",o),null!==(n=i.users.find((t=>t.userId===e)))&&void 0!==n?n:i.users[0]},pd=e=>co("user.updated",e),yd=e=>co("user.flagged",e),vd=e=>co("user.unflagged",e),fd=e=>co("user.flagCleared",e),bd=e=>co("user.fetched",e),Id=async e=>{const t=Ye();t.log("user/getUser",e),ea("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),a=t.cache&&Date.now(),s=eo(n);return t.cache&&Fn(s,{cachedAt:a}),Nt("user.fetched",n),{data:s.users.find((t=>t.userId===e)),cachedAt:a}}catch(t){throw Pe(null==t?void 0:t.code)&&_n("user",e),t}};Id.locally=e=>{const t=Ye();if(t.log("user/getUser.locally",e),!t.cache)return;const n=at(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Cd extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return o}}class wd extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.users.map(Ze("user"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ze("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Sd;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(Sd||(Sd={}));class Od extends Rr{constructor(e,t){const n=R.default(e),a=["user","collection",n];super(new Cd(e),n,a,t),this.query=e,this.queryStreamController=new wd(this.query,this.cacheKey,this.notifyChange.bind(this),eo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:lo,action:Sd.OnUserDeleted},{fn:pd,action:Sd.OnUserUpdated},{fn:yd,action:Sd.OnUserFlagged},{fn:vd,action:Sd.OnUserUnflagged},{fn:fd,action:Sd.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;const n=(()=>"firstCreated"===this.query.sortBy?Ct:St)();return t=t.sort(n),"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Td extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return o}}var Ad;!function(e){e.OnBlocked="onBlocked",e.OnUnblocked="onUnblocked"}(Ad||(Ad={}));class Rd extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.users.map(Ze("user"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ze("user"))])]}))}}reactor(e){return t=>{var n,a;const s=e===Or.OnFollowed||e===Ad.OnUnblocked,o=e===Ad.OnBlocked;if(s||o){const e=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data,s=null!==(a=null==e?void 0:e.data)&&void 0!==a?a:[],i=o?[...new Set([...s,t.userId])]:s.filter((e=>e!==t.userId));st(this.cacheKey,Object.assign(Object.assign({},e),{data:i}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Pd=(e,t,n)=>a=>e((e=>{var s;if(!e)return e;const o=[n,"get",`${e[t]}`],i=null===(s=at(o))||void 0===s?void 0:s.data;return i?a(i):void 0}));class Dd extends Rr{constructor(e,t){const n=R.default(e),a=["blockedUsers","collection",n];super(new Td(e),n,a,t),this.query=e,this.queryStreamController=new Rd(this.query,this.cacheKey,this.notifyChange.bind(this),Ko),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:lo,action:Sd.OnUserDeleted},{fn:Pd(yr,"to","user"),action:Or.OnFollowed},{fn:Pd(rr,"to","user"),action:Or.OnFollowed},{fn:e=>Yo((t=>{var n;if(t.from!==Ye().userId)return;const a=null===(n=at(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:Ad.OnBlocked},{fn:e=>Wo((t=>{var n;if(t.from!==Ye().userId)return;const a=null===(n=at(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:Ad.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Ud extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.users.map(Ze("user"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ze("user"))])]}))}}reactor(e){return t=>{var n,a;if(t&&(e===Ad.OnBlocked||e===Ad.OnUnblocked)){const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[],i=e===Ad.OnBlocked?[...new Set([...o,t.userId])]:o.filter((e=>e!==t.userId));st(this.cacheKey,Object.assign(Object.assign({},s),{data:i}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class kd extends Cr{async getRequest(e,t){const{limit:n=pe}=e,a=Bn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/blockers",{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return o}}class jd extends Rr{constructor(e){const t=`blocking-users-${Ye().userId}`,n={},a=["blockingUsers","collection",t];super(new kd(n),t,a,e),this.queryStreamController=new Ud(n,this.cacheKey,this.notifyChange.bind(this),$o),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:lo,action:Sd.OnUserDeleted},{fn:e=>Yo((t=>{var n;if(t.to!==Ye().userId)return;const a=null===(n=at(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:Ad.OnBlocked},{fn:e=>Wo((t=>{var n;if(t.to!==Ye().userId)return;const a=null===(n=at(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:Ad.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Ed extends Cr{async getRequest(e,t){const{limit:n=ge,displayName:a}=e,s=Bn(e,["limit","displayName"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},s),{keyword:a,options:o,isDeleted:!1})});return i}}class Md extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.users.map(Ze("user"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ze("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class qd extends Rr{constructor(e,t){var n;const a=R.default(e),s=["user","collection",a];super(new Ed(e),a,s,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new Md(this.query,this.cacheKey,this.notifyChange.bind(this),eo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:lo,action:Sd.OnUserDeleted},{fn:pd,action:Sd.OnUserUpdated},{fn:yd,action:Sd.OnUserFlagged},{fn:vd,action:Sd.OnUserUnflagged},{fn:fd,action:Sd.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["user","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const xd=async({viewId:e,viewedType:t,limit:n,token:a})=>{const s=Ye(),o={};a?o.token=a:o.limit=n;const i=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,r=await s.http.get(i,{params:o});return Fn(r.data),r.data};var Nd;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(Nd||(Nd={}));var Kd=Object.freeze({__proto__:null,Relationship:xr,getUserByIds:md,updateUser:async(e,t)=>{const n=Ye();n.log("user/updateUser",e,t);const{data:a}=await n.http.put("/api/v3/users/",Object.assign(Object.assign({userId:e},t),{createNewUserWhenNotFound:!1})),s=eo(a),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),Nt("user.updated",a),{data:s.users.find((t=>t.userId===e)),cachedAt:o}},flagUser:gd,unflagUser:async e=>{const t=Ye();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),a=eo(n);return t.cache&&Fn(a),Nt("user.unflagged",n),!!a},isUserFlaggedByMe:async e=>{const t=Ye();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},getAllBlockedUsers:async()=>{Ye().log("user/getAllBlockedUsers");const e=Bo();return await e.ensureFetched(),e.getCachedUsers()},getAllBlockingUsers:async()=>{Ye().log("user/getAllBlockingUsers");const e=Vo();return await e.ensureFetched(),e.getCachedUsers()},onUserUpdated:pd,onUserDeleted:lo,onUserFlagged:yd,onUserUnflagged:vd,onUserFlagCleared:fd,getUser:(e,t)=>qr(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?hd.user(e.data):e.data}))),"userId",Id,[bd,pd,lo,yd,vd,fd]),getUsers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`liveUsers(tmpid: ${o}) > listen`);const i=new Od(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`liveUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getBlockedUsers(tmpid: ${o}) > listen`);const i=new Dd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getBlockedUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e())),rt(c)}},getBlockingUsers:e=>{const{log:t,cache:n}=Ye();n||console.log(ve);const a=Date.now();t(`getBlockingUsers(tmpid: ${a}) > listen`);const s=new jd(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>rt(i))),()=>{t(`getBlockingUsers(tmpid: ${a}) > dispose`),o.forEach((e=>e())),rt(i)}},searchUsers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`liveSearchUsers(tmpid: ${o}) > listen`);const i=new qd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`liveSearchUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchUserByDisplayName:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`liveSearchUsers(tmpid: ${o}) > listen`);const i=new qd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`liveSearchUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:a,cache:s}=Ye(),o=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(ve);const i=Date.now();a(`getReachUsers(tmpid: ${i}) > listen`);const{limit:r,viewId:c,viewedType:d}=e;return n=(e=!1)=>{var a,s,i;const l=null===(a=at(o))||void 0===a?void 0:a.data,u=null!==(s=null==l?void 0:l.data)&&void 0!==s?s:[];if(!e&&u.length>0&&!(null==l?void 0:l.params.page))return;const h=_e(xd,{viewId:c,viewedType:d,limit:r||10,token:e||null===(i=null==l?void 0:l.params.page)||void 0===i?void 0:i.next});$e(h,(e=>{var a,s,i,r,c;let d=null!==(i=null===(s=null===(a=at(o))||void 0===a?void 0:a.data)||void 0===s?void 0:s.data)&&void 0!==i?i:[];(null===(r=e.data)||void 0===r?void 0:r.users)&&(d=[...new Set([...d,...e.data.users.map((({userId:e})=>e))])]);const l={loading:e.loading,params:{page:null===(c=e.data)||void 0===c?void 0:c.paging},data:d||[]};st(o,l),(e=>{var a,s;let o=[];(null==e?void 0:e.data)&&(o=e.data.map((e=>at(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:o,hasNextPage:!!(null===(s=null===(a=e.params)||void 0===a?void 0:a.page)||void 0===s?void 0:s.next),loading:e.loading||!1})})(l)}),Be(ye,2e3))},n(!0),()=>{a(`getReachUsers(tmpid: ${i}) > dispose`),rt(o)}},get AmityUserSearchMatchType(){return Nd}});const Fd=async e=>{const t=Ye();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),a=t.cache&&Date.now();return t.cache&&Fn({files:[n]},{cachedAt:a}),{data:Kc(n),cachedAt:a}};Fd.locally=e=>{const t=Ye();if(t.log("file/getFile.locally",e),!t.cache)return;const n=at(["file","get",e]);return n?{data:Kc(n.data),cachedAt:n.cachedAt}:void 0};const _d=async(e,t,n)=>{const a=Ye();a.log("file/uploadVideo",e);const s=e.getAll("files");if(!s.length)throw new Error("The formData object must have a `files` key.");const o=Fi().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",s[0].name),t&&e.append("feedType",t);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:r}=await a.upload.post("/api/v4/videos",e,{headers:i,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=a.cache&&Date.now();return a.cache&&Fn({files:r},{cachedAt:c}),{data:r.map((e=>Kc(e))),cachedAt:c}},Bd=async(e,t,n)=>{const a=Ye();a.log("file/uploadImage",e);const s=e.getAll("files");if(null==s?void 0:s.length)console.warn("Deprecation Warning: `files` is deprecated, please use `file` instead."),e.append("preferredFilename",s[0].name);else{const t=e.get("file");if(!t)throw new Error("The formData object must have a `file` or `files` key");e.append("preferredFilename",t.name),n&&e.append("altText",n)}const o=Fi().getFileAccessType();e.append("accessType",o);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:r}=await a.upload.post("/api/v4/images",e,{headers:i,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),c=a.cache&&Date.now();return a.cache&&Fn({files:r},{cachedAt:c}),{data:r.map((e=>Kc(e))),cachedAt:c}};var $d=Object.freeze({__proto__:null,getFile:Fd,uploadFile:async(e,t)=>{const n=Ye();n.log("file/uploadFile",e);const a=e.getAll("files");if(!a.length)throw new Error("The formData object must have a `files` key.");const s=Fi().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",a[0].name);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await n.upload.post("/api/v4/files",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),r=n.cache&&Date.now();return n.cache&&Fn({files:i},{cachedAt:r}),{data:i,cachedAt:r}},deleteFile:async e=>{const t=Ye();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),rt(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:_d,uploadImage:Bd,updateAltText:async(e,t)=>{const n=Ye();n.log("file/updateAltText",t);const{data:a}=await n.http.put(`/api/v3/files/${e}`,{altText:t}),s=n.cache&&Date.now();return n.cache&&Fn({files:[a]},{cachedAt:s}),!0},uploadClip:async(e,t,n)=>{const a=Ye();a.log("file/uploadClip",e);const s=e.get("files");if(!s)throw new Error("The formData object must have a `files` key.");const o=Fi().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",s.name),t&&e.append("feedType",t);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:r}=await a.upload.post("/api/v4/clips",e,{headers:i,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=a.cache&&Date.now();return a.cache&&Fn({files:r},{cachedAt:c}),{data:r,cachedAt:c}},uploadAudio:async(e,t)=>{const n=Ye();n.log("file/uploadAudio",e);const a=e.getAll("file");if(0===a.length)throw new Error("The formData object must have a `file` key with audio file.");const s=a[0],o=Fi().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",s.name);const{data:i}=await n.upload.post("/api/v4/audios",e,{headers:{"content-type":"multipart/form-data"},onUploadProgress({loaded:e,total:n=100}){null==t||t(Math.round(100*e/n))}}),r=n.cache&&Date.now();return n.cache&&Fn({files:i},{cachedAt:r}),{data:i,cachedAt:r}}});const Ld=async e=>{const t=Ye();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:a=10,queryToken:s,displayName:o,sortBy:i}=n,r=Bn(n,["limit","queryToken","displayName","sortBy"]),c=s?{token:s}:a?{limit:a}:void 0,{data:d}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},r),{keyword:o,sortBy:i,options:c})}),{paging:l}=d,u=Bn(d,["paging"]),{roles:h}=u,m=t.cache&&Date.now();t.cache&&Fn(u,{cachedAt:m});const g=Me(l.next);return{data:h,cachedAt:m,prevPage:Me(l.previous),nextPage:g,paging:l}};Ld.locally=e=>{Ye().log("role/queryRoles.locally",e)};const Qd=async e=>{const t=Ye();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),a=t.cache&&Date.now();return t.cache&&Fn({roles:n},{cachedAt:a}),{data:n.find((t=>t.roleId===e)),cachedAt:a}};Qd.locally=e=>{const t=Ye();if(t.log("role/getRole.locally",e),!t.cache)return;const n=at(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Vd=async(e,t=!1)=>{const n=Ye();let a;n.log("message/getMessage",e),ea("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);a=await ha(t)}catch(t){throw Pe(null==t?void 0:t.code)&&_n("message",e),t}const s=n.cache&&Date.now();n.cache&&Fn(a,{cachedAt:s});const{messages:o}=a;return Nt("local.message.fetched",{messages:o}),{data:o.find((t=>t.messageId===e)),cachedAt:s}};Vd.locally=e=>{const t=Ye();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=at(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Jd{constructor(e,t,n){this.postId=e,this.latestCreatedAt=t,this.serverCommentCount=n}}class Hd{constructor(e,t,n){this.postId=e,this.commentId=t,this.createdAt=n}}class Gd{constructor(e,t){this.postId=e,this.commentId=t}}class zd{constructor(e,t){this.latestCommentCreatedAt=e,this.serverCommentCount=t,this.createdCommentIds=new Set,this.deletedCommentIds=new Set}}class Yd{constructor(){this.isProcessing=!1,this.tasks=[],this.commentChangeTracker=new Map}queueCommentChangeTask(e){this.tasks.push(e),this.isProcessing||this.processCommentChangeTask()}processCommentChangeTask(){if(this.isProcessing)return;if(this.isProcessing=!0,0===this.tasks.length)return void(this.isProcessing=!1);const e=this.tasks.splice(0,Yd.BATCH_SIZE),t=new Set;e.forEach((e=>{let n=!1;e instanceof Jd?n=this.processResetTaskInternal(e):e instanceof Hd?n=this.processCreateTaskInternal(e):e instanceof Gd&&(n=this.processDeleteTaskInternal(e)),n&&t.add(e.postId)})),t.forEach((e=>{const t=this.computeCommentCount(e);Yd.publishUpdate(e,t)})),this.isProcessing=!1,this.tasks.length>0&&this.processCommentChangeTask()}processResetTaskInternal(e){return this.commentChangeTracker.set(e.postId,new zd(e.latestCreatedAt,e.serverCommentCount)),!0}processCreateTaskInternal(e){const t=this.commentChangeTracker.get(e.postId);return!!t&&(!t.createdCommentIds.has(e.commentId)&&(!(e.createdAt<=t.latestCommentCreatedAt)&&(t.createdCommentIds.add(e.commentId),!0)))}processDeleteTaskInternal(e){const t=this.commentChangeTracker.get(e.postId);return!!t&&(!t.deletedCommentIds.has(e.commentId)&&(t.deletedCommentIds.add(e.commentId),!0))}computeCommentCount(e){const t=this.commentChangeTracker.get(e);if(!t)return 0;const n=t.serverCommentCount+t.createdCommentIds.size-t.deletedCommentIds.size;return Math.max(0,n)}static publishUpdate(e,t){var n;const a=["post","get",e];ot(a,{localCommentCount:t});const s=null===(n=at(a))||void 0===n?void 0:n.data;s&&Nt("local.post.updated",{posts:[s]})}}let Wd;Yd.BATCH_SIZE=50;var Xd=()=>(Wd||(Wd=new Yd),Wd);const Zd=e=>{const{posts:t,postChildren:n,videoStreamings:a}=e,s=Bn(e,["posts","postChildren","videoStreamings"]),o=Fr({communities:s.communities}),i=s.communityUsers.map((e=>{const t=s.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),r=Nr(o,i);let c=[];const d=t.map((t=>{var n,o,i,r;const d=null===(n=s.feeds.find((e=>e.feedId===t.feedId)))||void 0===n?void 0:n.feedType,l=e.postChildren.filter((e=>e.parentPostId===t.postId));var u,h,m;l.length>0&&wc(l[0])&&(u=a,h=null===(o=l[0].data)||void 0===o?void 0:o.streamId,m=t.postId,c=h?u.map((e=>e.streamId===h?Object.assign(Object.assign({},e),{referenceType:"post",referenceId:m,postId:m}):e)):u);const g=(e.comments||[]).filter((e=>"post"===e.referenceType&&e.referenceId===t.postId)),p=0===g.length?(new Date).toISOString():g.map((e=>e.createdAt)).sort().at(-1);return Xd().queueCommentChangeTask(new Jd(t.postId,p,null!==(i=t.commentsCount)&&void 0!==i?i:0)),Object.assign(Object.assign({},t),{childPosts:l,feedType:d,localCommentCount:null!==(r=t.localCommentCount)&&void 0!==r?r:t.commentsCount,pinnedProductId:null==t?void 0:t.pinnedProductId})}));return Object.assign(Object.assign({},s),{postChildren:n,videoStreamings:c,posts:d,communities:r,communityUsers:i})},el=e=>{var{searchResult:t,polls:n}=e,a=Bn(e,["searchResult","polls"]);const s=Zd(a);return Object.assign(Object.assign({},s),{polls:n})},tl=async e=>{const t=Ye();let n;t.log("post/getPost",e),ea("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("post",e),t}const a=Zd(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{posts:o}=a;return{data:o.find((t=>t.postId===e)),cachedAt:s}};tl.locally=e=>{const t=Ye();if(t.log("post/getPost.locally",e),!t.cache)return;const n=at(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const nl=async e=>{const t=Ye();let n;t.log("comment/getComment",e),ea("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("comment",e),t}const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{comments:s}=n;return{data:hd.comment(s.find((t=>t.commentId===e))),cachedAt:a}};nl.locally=e=>{const t=Ye();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=at(["comment","get",e]);return n?{data:hd.comment(n.data),cachedAt:n.cachedAt}:void 0};const al=(e,t)=>{var n,a;let s,o;if("post"===t)o="post",s=e.posts[0].postId;else if("comment"===t)o="comment",s=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");o="story",s=e.stories[0].referenceId}return(null===(a=null===(n=at([o,"get",s]))||void 0===n?void 0:n.data)||void 0===a?void 0:a.myReactions)||[]},sl=(e,t,n)=>{const[a]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},a),{myReactions:n})]})},ol=(e,t,n,a=[])=>{const s=e.split(".")[1];let o=a;if(Ye().userId===t)if(["addReaction","reactionAdded"].includes(s))o.includes(n)||o.push(n);else{if(!["removeReaction","reactionRemoved"].includes(s))throw new Error(`Unknown event type: ${s}`);o=o.filter((e=>e!==n))}return o},il=(e,t)=>{const n=e.split(".")[0],a=al(t,n),s=ol(e,t.reactor.userId,t.reactor.reactionName,a);return sl(t,`${n}s`,s)},rl=(e,t)=>{var n,a;const s=e.split(".")[0];let o=al(t,s);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(o=ol(e,null===(n=t.reactions[0])||void 0===n?void 0:n.userId,null===(a=t.reactions[0])||void 0===a?void 0:a.reactionName,o));const i=sl(t,"stories",o);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return i;const r=Nr(t.communities,t.communityUsers);return Object.assign(Object.assign({},i),{communities:r})},cl=async(e,t,n)=>{var a,s,o;const i=Ye();if(i.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ve("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:r}=await i.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0});if(i.cache){const c=at([e,"get",t]);if(!c||(null===(a=c.data.myReactions)||void 0===a?void 0:a.includes(n)))return!0;const d=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(s=c.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(o=c.data.reactions[n])&&void 0!==o?o:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return Nt("local.comment.addReaction",{comment:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0;if("post"===e)return Nt("local.post.addReaction",{post:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0;if("story"===e)return Nt("local.story.reactionAdded",{story:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0}return!0};cl.optimistically=(e,t,n)=>{var a,s,o,i,r;const c=Ye();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const d=at([e,"get",t]);if(!(null==d?void 0:d.data)||(null===(a=d.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const l=Object.assign(Object.assign({},d.data),{reactionsCount:d.data.reactionsCount+1,myReactions:[...null!==(s=d.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},d.data.reactions),{[n]:(null!==(o=d.data.reactions[n])&&void 0!==o?o:0)+1})});return it([e,"get",t],l,{cachedAt:be}),_c(e,l),null!==(r=null===(i=null==l?void 0:l.myReactions)||void 0===i?void 0:i.includes(n))&&void 0!==r&&r};const dl=async(e,t,n)=>{var a,s;const o=Ye();if(o.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ve("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await o.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}});if(o.cache){const r=at([e,"get",t]);if(!r)return!0;const c=Object.assign(Object.assign({},r.data),{reactionsCount:Math.max(0,r.data.reactionsCount-1),myReactions:(null!==(a=r.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:Math.max(0,(null!==(s=r.data.reactions[n])&&void 0!==s?s:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return Nt("local.comment.removeReaction",{comment:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("post"===e)return Nt("local.post.removeReaction",{post:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("story"===e)return Nt("local.story.reactionRemoved",{story:c,reactor:{userId:o.userId,reactionName:n,reactionId:i.removedId}}),!0}return!0};dl.optimistically=(e,t,n)=>{var a,s,o,i;const r=Ye();if(r.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!r.cache)return;const c=at([e,"get",t]);if(!(null==c?void 0:c.data)||!(null===(a=c.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const d=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(s=c.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:Math.max(0,(null!==(o=c.data.reactions[n])&&void 0!==o?o:0)-1)})});return it([e,"get",t],d,{cachedAt:be}),_c(e,d),!(null===(i=null==d?void 0:d.myReactions)||void 0===i?void 0:i.includes(n))};const ll=e=>{var t;const n=e.posts[0];if(n.parentId){const e=null===(t=at(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;if(!e)return;st(["post","get",e.postId],Object.assign(Object.assign({},e),{children:e.children.filter((e=>e!==n.postId))}))}else n.children.forEach((e=>ot(["post","get",e],{isDeleted:!0})))},ul=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{var s;if(n.cache){const o=Zd(a),{communities:i}=o;if(Fn(o,void 0,!1),(null==i?void 0:i[0])&&!["post.updated"].includes(e)&&Nt("community.updated",{communities:i,categories:[],communityUsers:o.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=a.posts[0];ll(a);try{ea("post",e)}catch(e){return}return s!==n.userId&&rt(["post","get",e]),t(a.posts[0])}const r=at(["post","get",a.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=nt(["post","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===r.data.targetId}));"post.declined"===e&&(t=null==t?void 0:t.filter((({key:e})=>{var t;return"reviewing"===(null===(t=e[2])||void 0===t?void 0:t.feedType)}))),null==t||t.map((({key:e,data:t})=>it(e,t,{cachedAt:-1})))}"post.created"===e&&(e=>{var t;const n=e.posts[0];if(!n.parentId)return;const a=null===(t=at(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;a&&st(["post","get",a.postId],Object.assign(Object.assign({},a),{children:[...new Set([n.postId,...a.children])]}))})(a),t(r.data)}else t(a.posts[0])}))},hl=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{if(n.cache){const{communities:n}=a;(null==n?void 0:n[0])&&!["local.post.updated"].includes(e)&&Nt("community.updated",{communities:n,categories:[],communityUsers:a.communityUsers,feeds:[],files:[],users:[]});const s=at(["post","get",a.posts[0].postId]);"local.post.deleted"===e&&ll(a),t(s.data)}else t(a.posts[0])}))},ml=e=>ul("post.created",e),gl=e=>ul("post.updated",e),pl=e=>ul("post.deleted",e),yl=e=>ul("post.approved",e),vl=e=>ul("post.declined",e),fl=e=>ul("post.flagged",e),bl=e=>ul("post.unflagged",e),Il=e=>{const t=Ye();return xt(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=Bn(il("post.addReaction",n),["reactor"]);Fn(t);const a=at(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},Cl=e=>{const t=Ye();return xt(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=Bn(il("post.removeReaction",n),["reactor"]);Fn(t);const a=at(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},wl=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{var s;if(n.cache){const n=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=al(e,"comment");return sl(e,"comments",t)})(a):a;Fn(n,void 0,!1);const{comments:o}=n;if(o.length>0){const n=at(["comment","get",o[0].commentId]);if(["comment.created"].includes(e)&&o[0].parentId){const e=at(["comment","get",o[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(o[0].commentId)||st(["comment","get",o[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,o[0].commentId])]})))}if(["comment.deleted"].includes(e)){if(o[0].parentId){const e=at(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==o[0].commentId))])]});st(["comment","get",o[0].parentId],t)}}const e=null===(s=nt(["comment","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>it(e,t,{cachedAt:-1})))}t(hd.comment(n.data))}}else t(hd.comment(a.comments[0]))}))},Sl=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{var s,o,i,r,c;if(n.cache){const n=a;Fn(n);const{comments:d}=n;if(d.length>0){const n=at(["comment","get",d[0].commentId]);if(["local.comment.created"].includes(e)){if(d[0].parentId){const e=at(["comment","get",d[0].parentId]);if((null==e?void 0:e.data)&&!e.data.children.includes(d[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,d[0].commentId])]});st(["comment","get",d[0].parentId],t),setTimeout((()=>{Nt("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",d[0].referenceId],t=null===(s=at(e))||void 0===s?void 0:s.data;if(t){const n=Object.assign(Object.assign({},t),{comments:[...t.comments,null===(o=d[0])||void 0===o?void 0:o.commentId]});st(e,n)}}const e=null===(i=nt(["comment","query"]))||void 0===i?void 0:i.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>it(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(d[0].parentId){const e=at(["comment","get",d[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(d[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==d[0].commentId))])]});st(["comment","get",d[0].parentId],t),setTimeout((()=>{Nt("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",d[0].referenceId],t=null===(r=at(e))||void 0===r?void 0:r.data;if(t){const n=Object.assign(Object.assign({},t),{comments:null==t?void 0:t.comments.filter((e=>{var t;return e!==(null===(t=d[0])||void 0===t?void 0:t.commentId)}))});st(e,n)}}const e=null===(c=nt(["comment","query"]))||void 0===c?void 0:c.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>it(e,t,{cachedAt:-1})))}t(hd.comment(n.data))}}else t(hd.comment(a.comments[0]))}))},Ol=e=>wl("comment.created",e),Tl=e=>wl("comment.updated",e),Al=e=>wl("comment.deleted",e),Rl=e=>wl("comment.flagged",e),Pl=e=>wl("comment.unflagged",e),Dl=e=>{const t=Ye();return xt(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=Bn(il("comment.addReaction",n),["reactor"]);Fn(t);const a=at(["comment","get",n.comments[0].commentId]);e(hd.comment(a.data))}else e(hd.comment(n.comments[0]))}))},Ul=e=>{const t=Ye();return xt(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=Bn(il("comment.removeReaction",n),["reactor"]);Fn(t);const a=at(["comment","get",n.comments[0].commentId]);e(hd.comment(a.data))}else e(hd.comment(n.comments[0]))}))},kl=(e,t,n)=>{const a=Ye(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e){return xt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await ha(e);t.reactions[0]&&(Fn(t),Fn({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return xt(a,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=Bn(e,["reactor"]);Fn(n),Fn({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return xt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Bn(e,["reactions"]);Fn(n),Fn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return xt(a,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=Bn(e,["reactor"]);Fn(n),Fn({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},jl=(e,t,n)=>{const a=Ye(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e){return xt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await ha(e);t.reactions[0]&&(Fn(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return xt(a,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=Bn(e,["reactor"]);Fn(n),Fn({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return xt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Bn(e,["reactions"]);Fn(n),Fn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return xt(a,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=Bn(e,["reactor"]);Fn(n),Fn({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))};class El extends Cr{async getRequest(e,t){const{limit:n=ge,referenceType:a}=e,s=Bn(e,["limit","referenceType"]),o=t?{token:t}:{limit:n};Ye().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(a))throw new Ve("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await this.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},s),{referenceType:a,referenceVersion:"message"===a?5:void 0,options:o})});return i}}class Ml extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){var t;const n=await this.preparePayload(e),a=Ye(),s=a.cache&&Date.now();if(a.cache){const{reactions:e}=n,a=Bn(n,["reactions"]);Fn(Object.assign(Object.assign({},a),{reactions:e,reactors:null===(t=e[0])||void 0===t?void 0:t.reactors}),{cachedAt:s})}}appendToQueryStream(e,t,n=!1){var a,s,o,i;const r=null!==(s=null===(a=e.reactions[0])||void 0===a?void 0:a.reactors)&&void 0!==s?s:[];if(n)st(this.cacheKey,{data:r.map(Ze("reactor"))});else{const e=null===(o=at(this.cacheKey))||void 0===o?void 0:o.data,t=null!==(i=null==e?void 0:e.data)&&void 0!==i?i:[];st(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...r.map(Ze("reactor"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&("onAdded"===e?a.data=[...new Set([t.reactionId,...a.data])]:"onRemoved"===e&&(a.data=a.data.filter((e=>e!==t.reactionId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ql extends Rr{constructor(e,t){const n=R.default(e),a=["reaction","collection",n];super(new El(e),n,a,t),this.query=e,this.queryStreamController=new Ml(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:e=>kl(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>jl(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const a=Ye(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e)return xt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await ha(e);t.reactions[0]&&(Fn(t),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return xt(a,"local.post.removeReaction","local.post.removeReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return xt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Bn(e,["reactions"]);Fn(n),Fn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return xt(a,"local.comment.removeReaction","local.comment.removeReaction",(e=>{s("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const a=Ye(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e)return xt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await ha(e);t.reactions[0]&&(Fn(t),Fn({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return xt(a,"local.post.addReaction","local.post.addReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return xt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Bn(e,["reactions"]);Fn(n),Fn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return xt(a,"local.comment.addReaction","local.comment.addReaction",(e=>{s("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["reactor","get",e]))).filter(Boolean).map((({data:e})=>hd.reactor(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var xl=Object.freeze({__proto__:null,addReaction:cl,removeReaction:dl,onReactionAdded:(e,t,n)=>{const a=a=>{Ze(e)(a)===t&&n(a)};if("message"===e){const e=Ye(),t=async e=>{var t;const n=await ha(e),s=at(["message","get",n.messages[0].messageId]),o=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Fn(n),o&&a(n.messages[0])};return xt(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?Il(a):Dl(a)},onReactionRemoved:(e,t,n)=>{const a=a=>{Ze(e)(a)===t&&n(a)};if("message"===e){const e=Ye(),t=async e=>{var t;const n=await ha(e),s=at(["message","get",n.messages[0].messageId]),o=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Fn(n),o&&a(n.messages[0])};return xt(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?Cl(a):Ul(a)},onReactorAdded:kl,onReactorRemoved:jl,getReactions:(e,t,n)=>{const{log:a,cache:s}=Ye(),o=Date.now();a(`getReactions(tmpid: ${o}) > listen`);const i=new ql(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getReactions(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});function Nl(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const Kl=async()=>{var e;const t=Ye();t.log("channel/getArchivedChannelIds");const{data:n}=await t.http.get("/api/v1/archives/channels"),a=null!==(e=n.archives)&&void 0!==e?e:[];return t.cache&&(rt(["archivedChannel","get"]),a.forEach((e=>{e.channelId&&st(["archivedChannel","get",e.channelId],e)}))),a.map((e=>e.channelId)).filter((e=>!!e))},Fl=e=>{const t=Ye(),n=[xt(t,"onMessageUpdated","message.updated",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])})),xt(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},_l=e=>{const t=Ye(),n=[xt(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])})),xt(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},Bl=e=>{const t=Ye(),n=[xt(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await fa(t);Fn(n),e(n.messageFeeds[0])})),xt(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function $l(e,t){st(["channel","get",e.channelId],Xn(e,t))}const Ll=e=>{const t=Ye();return xt(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},Ql=async(e,t=!1)=>{const n=Ye(),a=await ba(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const s=Object.assign(Object.assign({},a.data),{isDeleted:!0,updatedAt:tt(a.data.updatedAt)});return t?setTimeout((()=>{_n("subChannel",e)}),0):it(["subChannel","get",e],s),Nt("local.message-feed.deleted",{messageFeeds:[s]}),s},Vl=e=>xt(Ye(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),Jl=()=>`LOCAL_${kn()}`;let Hl;const Gl=async(e,t)=>{const n=Ye();n.log("message/updateMessage",t),console.warn("MessageRepository.updateMessage will be replaced with MessageRepository.editMessage");const{data:a}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,ma(t)),s=await ha(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{messages:i}=s;return Nt("local.message.updated",{messages:i}),{data:hd.message(i.find((t=>t.messageId===e))),cachedAt:o}};Gl.optimistically=(e,t)=>{const n=Ye();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const a=at(["message","get",e]);if(!a)return;const s=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return it(["message","get",e],s,{cachedAt:-1}),Nt("local.message.updated",{messages:[s]}),{data:hd.message(s),cachedAt:-1}};const zl=async(e,t)=>{const n=Ye();n.log("message/editMessage",t);const{data:a}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,ma(t)),s=await ha(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{messages:i}=s;return Nt("local.message.updated",{messages:i}),{data:hd.message(i.find((t=>t.messageId===e))),cachedAt:o}};zl.optimistically=(e,t)=>{const n=Ye();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const a=at(["message","get",e]);if(!a)return;const s=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return it(["message","get",e],s,{cachedAt:-1}),Nt("local.message.updated",{messages:[s]}),{data:hd.message(s),cachedAt:-1}};const Yl=async e=>{var t;const n=Ye();if(n.log("message/deleteMessage",e),e.includes("LOCAL_")){const n=null===(t=at(["message","get",e]))||void 0===t?void 0:t.data;if(!n)throw Error("messageId not found");const a=Object.assign(Object.assign({},n),{isDeleted:!0});return Nt("local.message.deleted",{messages:[a]}),hd.message(a)}const{data:a}=await n.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),s=await ha(a);return Nt("local.message.deleted",{messages:[s.messages[0]]}),hd.message(s.messages[0])};Yl.optimistically=e=>{Ye().log("message/deleteMessage.optimistically",e);const t=at(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return it(["message","get",e],n,{cachedAt:-1}),Nt("local.message.deleted",{messages:[n]}),{data:hd.message(n),cachedAt:-1}};const Wl=async e=>{const t=Ye();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await Vd(e);return Nt("local.message.deleted",{messages:[n.data]}),hd.message(n.data)};Wl.optimistically=e=>{Ye().log("message/softDeleteMessage.optimistically",e);const t=at(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return it(["message","get",e],n,{cachedAt:-1}),Nt("local.message.deleted",{messages:[n]}),{data:hd.message(n),cachedAt:-1}};const Xl=async e=>{const t=Ye();t.log("user/getReadUsers",e);const{page:n,messageId:a}=e,s=Bn(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${a}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:Ee(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:r,userFeedMarkers:c}=o,d=Bn(o,["paging","publicUserIds","userFeedMarkers"]),l=t.cache&&Date.now();if(t.cache){Fn(Object.assign(Object.assign({},d),{userFeedMarkers:Jn(c)}),{cachedAt:l});const e=["read-user","query",Object.assign(Object.assign({messageId:a},s),{options:Object.assign({},n)})];st(e,{users:r,paging:i})}let u=[];r.length>0&&({data:u}=await md(r));return{data:u,cachedAt:l,prevPage:Me(i.previous),nextPage:Me(i.next)}};Xl.locally=e=>{var t;const n=Ye();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:a}=e,s=Bn(e,["page"]),o=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},a)})],{data:i,cachedAt:r}=null!==(t=at(o))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=at(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:r,prevPage:Me(null==i?void 0:i.paging.previous),nextPage:Me(null==i?void 0:i.paging.next)}};const Zl=async e=>{const t=Ye();t.log("user/getDeliveredUsers",e);const{page:n,messageId:a}=e,s=Bn(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${a}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:Ee(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:r,userFeedMarkers:c}=o,d=Bn(o,["paging","publicUserIds","userFeedMarkers"]),l=t.cache&&Date.now();if(t.cache){Fn(Object.assign(Object.assign({},d),{userFeedMarkers:Jn(c)}),{cachedAt:l});const e=["delivered-user","query",Object.assign(Object.assign({messageId:a},s),{options:Object.assign({},n)})];st(e,{users:r,paging:i})}let u=[];r.length>0&&({data:u}=await md(r));return{data:u,cachedAt:l,prevPage:Me(i.previous),nextPage:Me(i.next)}};Zl.locally=e=>{var t;const n=Ye();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:a}=e,s=Bn(e,["page"]),o=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},a)})],{data:i,cachedAt:r}=null!==(t=at(o))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=at(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:r,prevPage:Me(null==i?void 0:i.paging.previous),nextPage:Me(null==i?void 0:i.paging.next)}};const eu=e=>{const t=Ye();return xt(t,"onMessageFlagged","message.flagged",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])}))},tu=e=>{const t=Ye();return xt(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])}))},nu=e=>{const t=Ye();return xt(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await ha(t);Fn(n),e(n.messages[0])}))},au=e=>{const t=Ye();return xt(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await ha(t,"message.reactionAdded");Fn(n),e(n.messages[0])}))},su=e=>{const t=Ye();return xt(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await ha(t,"message.reactionRemoved");Fn(n),e(n.messages[0])}))},ou=e=>{const t=Ye();return xt(t,"message/onMessageFetched","local.message.fetched",(t=>{Fn(t),e(t.messages[0])}))},iu=e=>{const t=Ye();return xt(t,"stream/onStreamViewerDidBan","video-streaming.viewerDidBan",(t=>{var n;const{list:a}=t;a.forEach((e=>{var t;ot(["stream","get",e.streamId],{watcherUrl:null});const n=null===(t=nt(["message","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.creatorId===e.userId));null==n||n.forEach((e=>{ot(e.key,{isDeleted:!0})}))}));const s=null===(n=at(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))};class ru extends Sr{constructor(e,t,n,a,s){super(e,t),this.notifyChange=n,this.preparePayload=a,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.messages.map(Ze("message")),query:this.query});else{const n=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,o=null!==(s=null==n?void 0:n.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...o,...e.messages.map(Ze("message"))])]:[...new Set([...e.messages.map(Ze("message")),...o])]}))}}reactor(e){return t=>{var n,a,s,o;if("onCreate"===e){const e=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:o}=t;if(!e)return;if(this.query.subChannelId!==(null==t?void 0:t.subChannelId)||!e)return;if(this.query.type&&this.query.type!==t.dataType)return;if(this.query.excludingTags&&(null===(a=this.query.excludingTags)||void 0===a?void 0:a.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;if(!!this.query.hasFlags!=!!t.flagCount)return;if(this.query.parentId&&this.query.parentId!==t.parentId)return;if(this.query.hasOwnProperty("includeDeleted")&&!this.query.includeDeleted&&t.isDeleted)return;if(this.query.includingTags&&!(null===(s=this.query.includingTags)||void 0===s?void 0:s.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;this.query.sortBy&&"segmentDesc"!==this.query.sortBy||this.paginationController.getPrevToken()||(e.data=[...new Set([null!=o?o:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=o?o:t.messageId])]),st(this.cacheKey,e)}if("onDelete"===e&&"error"===t.syncState){const e=null===(o=at(this.cacheKey))||void 0===o?void 0:o.data;if(!e)return;if(e.data.includes(t.messageId)){const n=e.data.filter((e=>e!==t.messageId));st(this.cacheKey,Object.assign(Object.assign({},e),{data:n}))}}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class cu extends Cr{async getRequest(e,t){const n=ga(e),{data:a}=await this.http.get("/api/v5/messages",{params:Object.assign(Object.assign({},n),{options:t?{token:t}:Object.assign({},n.options)})});return a}}class du extends Rr{constructor(e,t){const n=R.default(e),a=["message","collection",n];super(new cu(e),n,a,t),this.query=e,this.queryStreamController=new ru(this.query,this.cacheKey,this.notifyChange.bind(this),ha,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ii,action:"onCreate"},{fn:Ci,action:"onCreate"},{fn:_l,action:"onDelete"},{fn:Fl,action:"onUpdate"},{fn:eu,action:"onFlagged"},{fn:tu,action:"onUnflagged"},{fn:nu,action:"onFlagCleared"},{fn:au,action:"onReactionAdded"},{fn:su,action:"onReactionRemoved"},{fn:Pd(Zi,"contentId","message"),action:"onUpdate"},{fn:Pd(er,"contentId","message"),action:"onUpdate"},{fn:Pd(iu,"channelId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>sa(e))).filter(Boolean).map((e=>hd.message(e))))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=ct(t,"isDeleted",!1)),t=t.sort(((e,t)=>"segmentAsc"===this.query.sortBy?e.channelSegment-t.channelSegment:"segmentDesc"===this.query.sortBy?t.channelSegment-e.channelSegment:0)),t}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],query:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}}class lu extends Cr{async getRequest(e,t){const{query:n,exactMatch:a,channelId:s,messageFeedId:o,userIds:i,tags:r,types:c,sortBy:d,orderBy:l,limit:u=ge}=e,h=t?{token:t}:{limit:u,sortBy:d,orderBy:l},{data:m}=await this.http.get("/api/v2/search/messages",{params:{query:n,exactMatch:a,channelId:s,messageFeedId:o,userIds:i,tags:r,types:c,options:h}});return m}}class uu extends Sr{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){var t;const n=await ha(e),a=Ye(),s=a.cache&&Date.now();a.cache&&(Fn(n,{cachedAt:s}),(null===(t=e.channels)||void 0===t?void 0:t.length)&&e.channels.forEach((e=>{st(["channel","get",e.channelId],e,{cachedAt:s})})))}appendToQueryStream(e,t,n=!1){var a,s;if(n)return void st(this.cacheKey,{data:e.messages.map(Ze("message"))});const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,i=null!==(s=null==o?void 0:o.data)&&void 0!==s?s:[],r=e.messages.map(Ze("message"));st(this.cacheKey,Object.assign(Object.assign({},o),{data:"prev"===t?[...new Set([...r,...i])]:[...new Set([...i,...r])]}))}}class hu extends Rr{constructor(e,t){const n=R.default(e),a=["message","search",n];super(new lu(e),n,a,t),this.queryStreamController=new uu(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>sa(e))).filter(Pr).map((e=>hd.message(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}}var mu=Object.freeze({__proto__:null,createMessage:async e=>{const t=Ye();t.log("message/createMessage",e);const n=(e=>{var t,n;const a=Ye();if(!a.cache)return;Hl=e.referenceId||Jl();const s=Object.assign({messageId:Hl,uniqueId:Hl},e);a.log("message/createMessage.optimistically",s);const o=at(["subChannel","get",e.subChannelId]);if(o&&(it(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},o.data),{messageCount:o.data.messageCount+1})),o.data.channelId===o.data.subChannelId)){const e=at(["channel","get",o.data.channelId]);(null==e?void 0:e.data)&&it(["channel","get",o.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const i=(new Date).toISOString(),r=Object.assign({creatorId:a.userId,creatorPrivateId:Ut()._id,channelSegment:(null!==(n=null==o?void 0:o.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:i,updatedAt:i,syncState:"syncing",isDeleted:!1},s);return st(["message","get",r.messageId],r,{cachedAt:-5}),Nt("local.message.created",{messages:[r]}),r})(e),a=e.referenceId||Hl||Jl();Hl=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},ma(e)),{referenceId:a})),s=await ha(n),{messages:o}=s,i=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:i}),Nt("local.message.created",{messages:[Object.assign(Object.assign({},o[0]),{syncState:"synced"})]}),{data:hd.message(o[0]),cachedAt:i}}catch(e){throw Nt("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:Gl,editMessage:zl,deleteMessage:Yl,softDeleteMessage:Wl,markAsDelivered:async(e,t)=>{const n=Ye();n.log("message/markAsDelivered",e,t);const{data:a}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:s,userEntityMarkers:o,userFeedMarkers:i}=a,r=Bn(a,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Fn(Object.assign({userMarkers:s,userEntityMarkers:Vn(o),userFeedMarkers:Jn(i)},r),{cachedAt:c}),!0},getReadUsers:Xl,getDeliveredUsers:Zl,flagMessage:async(t,n)=>{const a=Ye();a.log("message/flag",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),o={reason:s?n:e.ContentFlagReasonEnum.Others,detail:s?"":n},{data:i}=await a.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`,o);if(a.cache){const e=await ha(i);Fn(e)}return Nt("message.flagged",i),!!i},unflagMessage:async e=>{const t=Ye();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await ha(n);Fn(e)}return Nt("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=Ye();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:Ii,onMessageCreatedLocal:Ci,onMessageUpdated:Fl,onMessageDeleted:_l,onMessageFlagged:eu,onMessageUnflagged:tu,onMessageFlagCleared:nu,onMessageReactionAdded:au,onMessageReactionRemoved:su,onMessageFetched:ou,getMessage:(e,t)=>qr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hd.message(e.data):n}))}),"messageId",Vd,[ou,Fl,_l,eu,tu,nu,au,su,Pd(Zi,"contentId","message"),Pd(er,"contentId","message"),Pd(iu,"channelId","message")]),getMessages:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMessages(tmpid: ${o}) > listen`);const i=new du(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getMessages(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchMessage:(e,t)=>{if(!e.query||0===e.query.trim().length)throw new Error("Query is required for message search");const{log:n,cache:a}=Ye();a||console.log(ve);const s=Date.now();n(`searchMessage(tmpid: ${s}) > listen`);const o=new hu(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{rt(r)})),()=>{n(`searchMessage(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},convertFromRaw:la,prepareMessagePayload:ha,convertParams:ma,convertQueryParams:ga});const gu=e=>{const t=Ye();return xt(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class pu extends Cr{async getRequest(e,t){var n;const{limit:a=ge}=e,s=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=Bn(e,["excludeDefaultSubChannel"]);const a=Object.assign({},n);return void 0!==t&&(a.excludeDefaultMessageFeed=t),a}(Bn(e,["limit"])))&&void 0!==n?n:{},{channelId:o,includeDeleted:i}=s,r=Bn(s,["channelId","includeDeleted"]),c=t?{token:t}:{limit:a},{data:d}=await this.http.get(`/api/v5/message-feeds/channel/${o}`,{params:Object.assign(Object.assign({},r),{isDeleted:oa(i),options:c})});return d}}class yu extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.messageFeeds.map((({messageFeedId:e})=>e))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(!Array.isArray(t)){if(this.query.channelId!==t.channelId)return;"onCreate"===e&&(a.data=[...new Set([t.subChannelId,...a.data])]),st(this.cacheKey,a)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class vu extends Rr{constructor(e,t){const n=R.default(e),a=["subChannel","collection",n];super(new pu(e),n,a,t),this.query=e,this.queryStreamController=new yu(this.query,this.cacheKey,this.notifyChange.bind(this),fa),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[]})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Vl,action:"onCreate"},{fn:wi,action:"onCreate"},{fn:Si,action:"onDelete"},{fn:e=>Bl((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=Ye();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=zn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Gn(t.updatedAt)>Gn(e.subChannelUpdatedAt)&&st(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:Pd((e=>Ii((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Ca(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pd((e=>Ci((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Ca(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>Wi((t=>{var n;const a=null!==(n=t.map((({feedId:e})=>at(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==a.length&&e(a)})),action:"onUpdate"},{fn:Pd(Yi,"feedId","subChannel"),action:"onUpdate"},{fn:Pd((e=>Fl((async t=>{var n;const a=Ye();if("no-message-preview"===await a.getMessagePreviewSetting(!1))return;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;s&&s.data.includes(t.subChannelId)&&(wa(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pd((e=>_l((async t=>{const n=Ye(),a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===a?await ba(t.subChannelId):await wa(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Pd(gu,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Yn))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=ct(e,"isDeleted",!1)),t.sort(At),t}isRelatedCollection(e){var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const fu={},bu=async e=>{const t=await(async e=>{const t=ba.locally(e);if(t)return t.data.channelId;const{data:n}=await ba(e);return n.channelId})(e),n=Gt({channelId:t,subChannelId:e});fu[e]=en(n)};var Iu=Object.freeze({__proto__:null,getSubChannelByIds:Ks,createSubChannel:async e=>{const t=Ye();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),a=await fa(n.data),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),Nt("message-feed.created",n.data),{data:a.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const n=Ye();n.log("channel/updateSubChannel",e,t);const a=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await fa(a.data),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),Nt("message-feed.updated",a.data),{data:s.messageFeeds[0],cachedAt:o}},deleteSubChannel:Ql,hardDeleteSubChannel:async e=>{Ye().log("channel/hardDeleteSubChannel",e);return await Ql(e,!0)},softDeleteSubChannel:async e=>{Ye().log("channel/softDeleteSubChannel",e);return await Ql(e,!1)},onSubChannelCreated:wi,onSubChannelUpdated:Bl,onSubChannelDeleted:Si,getSubChannel:(e,t)=>{const n=Ye();let a;return qr(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Yn(e.data)}),s=Bn(n,["origin"]);return Fa(a,s)?void 0:(a=s,t(n))}),"subChannelId",ba,[Vl,t=>Bl((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Ta(a),a.subChannelId===e&&t(a))})),Si,Pd(Yi,"feedId","subChannel"),t=>Wi((n=>{var a;if(!n.find((({feedId:t})=>t===e)))return;const s=null===(a=at(["subChannel","get",e]))||void 0===a?void 0:a.data;s&&t(s)})),Pd((t=>Ii((async n=>{n.subChannelId===e&&(await Ca(n),t(n))}))),"subChannelId","subChannel"),Pd((t=>Ci((async n=>{n.subChannelId===e&&(await Ca(n),t(n))}))),"subChannelId","subChannel"),Pd((t=>Fl((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&a.subChannelId===e&&(wa(a),t(a))}))),"subChannelId","subChannel"),Pd((t=>_l((async a=>{const s=await n.getMessagePreviewSetting(!1);"no-message-preview"!==s&&a.subChannelId===e&&("message-preview-include-deleted"===s&&await wa(a),"message-preview-not-include-deleted"===s&&await ba(a.subChannelId),t(a))}))),"subChannelId","subChannel"),Pd(gu,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:a,cache:s}=Ye(),o=Date.now();a(`getSubChannels(tmpid: ${o}) > listen`),s||console.log(ve);const i=new vu(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getSubChannels(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},markReadEngineOnLoginHandler:Ns,startMessageReceiptSync:async e=>(await bu(e),!0),stopMessageReceiptSync:e=>(fu[e]&&fu[e](),!0)});const Cu=e=>{const t=Ye();return xt(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},wu=e=>{const t=Ye();return xt(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class Su extends Cr{async getRequest(e,t){const{limit:n=ge,displayName:a,membership:s}=e,o=Bn(e,["limit","displayName","membership"]),i=t?{token:t}:{limit:n},{data:r}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},o),{keyword:a,filter:s,options:i})});return r}}class Ou extends Ar{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class Tu extends Sr{constructor(e,t,n,a,s){super(e,t),this.notifyChange=n,this.preparePayload=a,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.channels.map(Ze("channel"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(Ze("channel"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(this.paginationController instanceof Ou)return this.notifyChange({origin:"event",loading:!1});if(["onCreate","onJoin","onResolveChannel","onUnarchived"].includes(e)&&(Array.isArray(t)?a.data=[...new Set([...t.map(Ze("channel")),...a.data])]:a.data=[...new Set([t.channelInternalId,...a.data])]),"onArchived"===e){const e=Array.isArray(t)?t.map(Ze("channel")):[Ze("channel")(t)];a.data=a.data.filter((t=>!e.includes(t)))}st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Au=e=>{const t=Ye();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){Eo().resolve(e.channelId,"userMessageFeedMarker")}},Ru=e=>{const t=Ye();return xt(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))},Pu=e=>{const t=Ye();return xt(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))};class Du extends Rr{constructor(e,t){const n=R.default(e),a=["channel","collection",n],s=Du.getPaginationController(e);super(s,n,a,t),this.query=e,this.queryStreamController=new Tu(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=Ye();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ja(e)}catch(e){console.error("Error while preparing unread count info",e)}return Ua(e)}),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;let i=null!==(s=o.data.map((e=>at(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Us))&&void 0!==s?s:[];this.paginationController instanceof Su&&(i=this.applyFilter(i)),(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof Su?()=>this.loadPage({direction:"next"}):void 0,data:i,hasNextPage:this.paginationController instanceof Su&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ye();let n=e;switch(n=ct(n,"isDeleted",this.query.isDeleted),n=dt(n,"displayName",this.query.displayName),this.query.types&&(n=n.filter((e=>{var t;return null===(t=this.query.types)||void 0===t?void 0:t.includes(e.type)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.excludeTags&&(n=n.filter((e=>{var t;return!(null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.excludeTags)||void 0===t?void 0:t.includes(e)})))}))),this.query.membership&&t&&(n=ut(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(Ct);break;case"lastCreated":n=n.sort(St);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(bt);break;default:n=n.sort(At)}return n}shouldAbort(e){var t,n;const a=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;if(!a)return!0;return!(null===(n=null==a?void 0:a.data)||void 0===n?void 0:n.find((t=>t===e)))}static getMessagePreviewSetting(){return Ye().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Ou(e):new Su(e)}getSubscriptions(){const e=[{fn:Pd((e=>Ii((t=>{var n,a;const s=Eo();(null===(n=at(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||s.resolve(t.subChannelId,"userMessageFeedMarker");const o=null===(a=at(["channel","get",t.channelId]))||void 0===a?void 0:a.data;o?($l(o,{lastActivity:t.createdAt}),e(t)):s.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Ci((t=>{var n;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya,action:"onDelete"},{fn:Va,action:"onUpdate"},{fn:os,action:"onMute"},{fn:e=>Za((t=>{Au(t),e(t)})),action:"onJoin"},{fn:e=>ns(((t,n)=>{var a,s;const{userId:o}=Ye();if("member"===this.query.membership&&o===n.userId){const e=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;st(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(s=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==s?s:[]}))}return e(t)})),action:"onLeft"},{fn:cs,action:"onMemberAdded"},{fn:us,action:"onMemberRemoved"},{fn:e=>Os((t=>{const n=t.archives.map((e=>{var t;return null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>Ts((t=>{const n=t.archives.map((e=>{var t;return null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Pd(zi,"entityId","channel"),action:"onUpdate"},{fn:Pd(Ll,"entityId","channel"),action:"onUpdate"},{fn:Pd((e=>Ii((async t=>{var n;if("no-message-preview"===await Du.getMessagePreviewSetting())return;if(Sa(t),this.shouldAbort(t.channelId))return;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Ci((async t=>{var n;if("no-message-preview"===await Du.getMessagePreviewSetting())return;if(Sa(t),this.shouldAbort(t.channelId))return;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Fl((async t=>{"no-message-preview"!==await Du.getMessagePreviewSetting()&&(await Oa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>_l((async t=>{const n=await Du.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Oa(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await vc(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Si((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;a.data.find((e=>{const n=Hn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await vc(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Bl((async t=>{var n;if("no-message-preview"===await Du.getMessagePreviewSetting())return;(null===(n=at(this.cacheKey))||void 0===n?void 0:n.data)&&(await Ta(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd(wi,"channelId","channel"),action:"onUpdate"},{fn:Ru,action:"onResolveChannel"},{fn:e=>Pu((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=at(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Pd(Cu,"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>wu((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof Cr?[...e,{fn:e=>$a((t=>{Au(t),e(t)})),action:"onCreate"}]:e}}const Uu=()=>{var e;const t=Ye();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=nt(["channelUnread","get"]))||void 0===e?void 0:e.filter((({data:e})=>!e.isDeleted)))||[];return{data:(null==n?void 0:n.reduce(((e,{data:t})=>(e.unreadCount+=t.unreadCount,e.isMentioned=e.isMentioned||t.isMentioned,e)),{unreadCount:0,isMentioned:!1}))||{unreadCount:0,isMentioned:!1},cachedAt:t.cache&&Date.now()}};class ku extends Cr{async getRequest(e,t){var n,a;const s=null!==(n=e.limit)&&void 0!==n?n:ge,o=t?Number.parseInt(t,10):0;0===o&&await Kl();const i=(null!==(a=nt(["archivedChannel","get"]))&&void 0!==a?a:[]).map((e=>e.data)).slice().sort(((e,t)=>Number(new Date(t.archivedAt))-Number(new Date(e.archivedAt)))),r=o*s,c=r+s,d=i.slice(r,c),l=c<i.length;return d.length>0&&await ks(d.map((e=>e.channelId))),{archives:d,paging:{next:l?String(o+1):void 0,previous:void 0}}}}class ju extends Sr{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){}appendToQueryStream(e,t,n=!1){var a,s;const o=e.archives.map((e=>e.channelId));if(n)return void st(this.cacheKey,{data:o,params:{}});const i=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,r=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},i),{data:"prev"===t?[...new Set([...o,...r])]:[...new Set([...r,...o])]}))}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if("onArchived"===e){const e=a.data.filter((e=>!t.includes(e)));a.data=[...t,...e]}"onUnarchived"!==e&&"onDelete"!==e||(a.data=a.data.filter((e=>!t.includes(e)))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Eu extends Rr{constructor(e,t){const n=R.default(e),a=["archivedChannel","collection",n];super(new ku(e),n,a,t),this.queryStreamController=new ju(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:e=>Os((t=>e(t.archives.map((e=>e.channelId))))),action:"onArchived"},{fn:e=>Ts((t=>e(t.archives.map((e=>e.channelId))))),action:"onUnarchived"},{fn:e=>Va((t=>e([t.channelId]))),action:"onUpdate"},{fn:e=>Ya((t=>e([t.channelId]))),action:"onDelete"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["channel","get",e]))).filter((e=>Boolean(e))).map((({data:e})=>e)).map(Us))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Mu extends Cr{async getRequest(e,t){const{query:n,exactMatch:a,isMemberOnly:s,types:o,tags:i,sortBy:r,orderBy:c,limit:d=pe}=e,l=t?{token:t}:{limit:Math.min(100,Math.max(1,d))},{data:u}=await this.http.get("/api/v2/search/channels",{params:{query:n,exactMatch:a,isMemberOnly:s,types:o,tags:i,sortBy:r,orderBy:c,options:l}});return u}}class qu extends Sr{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){const t=await Ua(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)return void st(this.cacheKey,{data:e.channels.map(Ze("channel"))});const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,i=null!==(s=null==o?void 0:o.data)&&void 0!==s?s:[],r=e.channels.map(Ze("channel"));st(this.cacheKey,Object.assign(Object.assign({},o),{data:"prev"===t?[...new Set([...r,...i])]:[...new Set([...i,...r])]}))}reactor(){return()=>this.notifyChange({origin:"event",loading:!1})}subscribeRTE(e){return e.map((e=>e.fn(this.reactor())))}}const xu=()=>Ye().getMessagePreviewSetting(!1);class Nu extends Rr{constructor(e,t){const n=R.default(e),a=["channel","search",n];super(new Mu(e),n,a,t),this.queryStreamController=new qu(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["channel","get",e]))).filter(Boolean).map((e=>Us(e.data))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}shouldAbort(e){var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;return!n||!n.data.find((t=>t===e))}getSubscriptions(){return[{fn:Pd((e=>Ii((t=>{var n;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Ci((t=>{var n;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya,action:"onDelete"},{fn:Va,action:"onUpdate"},{fn:os,action:"onMute"},{fn:e=>Os((t=>{const n=t.archives.map((e=>{var t;return null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>Ts((t=>{const n=t.archives.map((e=>{var t;return null===(t=at(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Pd(zi,"entityId","channel"),action:"onUpdate"},{fn:Pd(Ll,"entityId","channel"),action:"onUpdate"},{fn:Pd((e=>Ii((async t=>{var n;if("no-message-preview"===await xu())return;if(Sa(t),this.shouldAbort(t.channelId))return;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Ci((async t=>{var n;if("no-message-preview"===await xu())return;if(Sa(t),this.shouldAbort(t.channelId))return;const a=null===(n=at(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&($l(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Fl((async t=>{"no-message-preview"!==await xu()&&(await Oa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>_l((async t=>{const n=await xu();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Oa(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await vc(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Si((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;a.data.find((e=>{const n=Hn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await vc(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>Bl((async t=>{var n;if("no-message-preview"===await xu())return;(null===(n=at(this.cacheKey))||void 0===n?void 0:n.data)&&(await Ta(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:e=>Pu((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=at(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Pd(Cu,"channelId","channel"),action:"onUpdate"},{fn:Pd((e=>wu((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}]}}class Ku extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a}=e,s=Bn(e,["limit","includeDeleted"]),o=t?{token:t}:{limit:n},i=!1!==a&&void 0,{data:r}=await this.http.get(`/api/v4/channels/${encodeURIComponent(s.channelId)}/users`,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:i})});return r}}class Fu extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>Ze("channelUsers")({channelId:e,userId:t})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>Ze("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;const s=Ze("channelUsers")({channelId:this.query.channelId,userId:t.userId}),o=this.query.memberships,i=!o||o.includes(t.membership);"none"!==t.membership&&i?a.data.includes(s)||(a.data=[s,...a.data]):a.data=a.data.filter((e=>e!==s)),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class _u extends Rr{constructor(e,t){const n=R.default(e),a=["channelUsers","collection",n];super(new Ku(e),n,a,t),this.query=e,this.queryStreamController=new Fu(this.query,this.cacheKey,this.notifyChange.bind(this),Ua),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Za,action:"onJoin"},{fn:ns,action:"onLeft"},{fn:cs,action:"onMemberAdded"},{fn:us,action:"onMemberRemoved"},{fn:gs,action:"onChannelMemberBanned"},{fn:vs,action:"onChannelMemberUnbanned"},{fn:Is,action:"onChannelMemberRoleAdded"},{fn:Ss,action:"onChannelMemberRoleRemoved"},{fn:Ps,action:"onChannelSetUserMuted"},{fn:(e=this.query.channelId,t=>{const n=Ye();return xt(n,"user.deleted","user.deleted",(n=>{var a,s;const o=eo(n);if(0===o.users.length)return;const i=o.users[0];Fn(o);const r=Ze("channelUsers")({channelId:e,userId:i.userId}),c=null===(a=at(["channelUsers","get",r]))||void 0===a?void 0:a.data;it(["channelUsers","get",r],Object.assign(Object.assign({},c),{user:i}));const d=null===(s=at(["channel","get",e]))||void 0===s?void 0:s.data;d&&t(d,c)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(hd.channelMember))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=lt(e,"roles",this.query.roles);this.query.memberships&&(t=t.filter((e=>{var t,n;return!(!(null===(t=this.query.memberships)||void 0===t?void 0:t.includes("muted"))||!e.isMuted)||"none"!==e.membership&&(null===(n=this.query.memberships)||void 0===n?void 0:n.includes(e.membership))}))),!1===this.query.includeDeleted&&(t=t.filter((e=>{var t;return!0!==(null===(t=e.user)||void 0===t?void 0:t.isDeleted)})));const n=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===n?St:Ct),t}}const Bu=(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new _u(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}};var $u=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ye();n.log("channel/addMembers",e,t);const{data:a}=await n.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users`,{channelId:e,userIds:t});t.forEach((e=>Nt("channel.membersAdded",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const s=await Ua(a);n.cache&&Fn(s);const{channelUsers:o}=s;return!!o.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=Ye();n.log("channel/removeMembers",e,t);const{data:a}=await n.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users`,{data:{channelId:e,userIds:t}});t.forEach((e=>Nt("channel.membersRemoved",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const s=await Ua(a);n.cache&&Fn(s);const{channelUsers:o}=s;return!!o.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=lt(e,"roles",t.roles);t.memberships&&(n=n.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership))));const a=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===a?St:Ct),n},getMembers:Bu,searchMembers:(e,t,n)=>Bu(e,t)});var Lu=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const a=Ye();a.log("channel/addRole",e,t,n);const{data:s}=await a.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),o=await Ua(s);a.cache&&Fn(o),Nt("local.channel-moderator.role-added",o);const{channelUsers:i}=o;return!!i.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const a=Ye();a.log("channel/removeRole",e,t,n);const{data:s}=await a.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),o=await Ua(s);a.cache&&Fn(o),Nt("local.channel-moderator.role-removed",o);const{channelUsers:i}=o;return!!i.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=Ye();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:a}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),s=await Ua(a),{channelUsers:o}=s,i=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:i}),Nt("channel.banned",a),{data:null==o?void 0:o.filter((e=>"banned"===e.membership)),cachedAt:i}},unbanMembers:async(e,t)=>{const n=Ye();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:a}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),s=await Ua(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o}),Nt("channel.unbanned",a);const{channelUsers:i}=s;return{data:null==i?void 0:i.filter((e=>"member"===e.membership)),cachedAt:o}},muteMembers:async(e,t,n=-1)=>{var a;const s=Ye();s.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:o}=await s.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:i}=o,r=-1===n?new Date("9999-12-31T23:59:59.999Z").toISOString():new Date(Date.now()+1e3*n).toISOString();return Nt("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:r,actor:null!==(a=s.userId)&&void 0!==a?a:""}),i},unmuteMembers:async(e,t)=>{var n;const a=Ye();a.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:s}=await a.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:o}=s;return Nt("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:new Date(0).toISOString(),actor:null!==(n=a.userId)&&void 0!==n?n:""}),o}}),Qu=Object.freeze({__proto__:null,Membership:$u,Moderation:Lu,getChannelByIds:ks,createChannel:yc,updateChannel:async(e,t)=>{const n=Ye();n.log("channel/updateChannel",e,t);const{data:a}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await Ua(a),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{channels:i}=s;return{data:xa(i.find((t=>t.channelId===e))),cachedAt:o}},deleteChannel:async e=>{const t=Ye();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await vc(e);return xa(n.data)},joinChannel:async e=>{const t=Ye();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),a=await Ua(n);t.cache&&Fn(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=Ye();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),a=await Ua(n);t.cache&&Fn(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=Ye();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new Qe("Mute Period can only be positive numbers or -1(mute forever)",800110,"error");const{data:a}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:t}),{success:s}=a;return s},unmuteChannel:async e=>{const t=Ye();t.log("channel/unmuteChannel",e);const{data:n}=await t.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:0}),{success:a}=n;return a},archiveChannel:async e=>{const t=Ye();t.log("channel/archiveChannel",e),await t.http.post(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const n={channelId:e,archivedAt:(new Date).toISOString()};t.cache&&st(["archivedChannel","get",Ze("archivedChannel")(n)],n),Nt("local.channel.archived",{archives:[n]})},unarchiveChannel:async e=>{var t;const n=Ye();n.log("channel/unarchiveChannel",e),await n.http.delete(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const a=null===(t=at(["archivedChannel","get",e]))||void 0===t?void 0:t.data,s=null!=a?a:{channelId:e,archivedAt:(new Date).toISOString()};n.cache&&rt(["archivedChannel","get",e],!0),Nt("local.channel.unarchived",{archives:[s]})},getArchivedChannelIds:Kl,onChannelCreated:$a,onChannelUpdated:Va,onChannelDeleted:Ya,onChannelJoined:Za,onChannelLeft:ns,onChannelSetMuted:os,onChannelMemberAdded:cs,onChannelMemberRemoved:us,onChannelMemberBanned:gs,onChannelMemberUnbanned:vs,onChannelMemberRoleAdded:Is,onChannelMemberRoleRemoved:Ss,onChannelArchived:Os,onChannelUnarchived:Ts,getChannel:(e,t)=>{const n=Ye();let a;return qr(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Us(e.data)}),s=Bn(n,["origin"]);return Fa(a,s)?void 0:(a=s,t(n))}),"channelId",vc,[Va,Ya,Za,ns,cs,us,gs,vs,os,Pd(zi,"entityId","channel"),Pd(Ll,"entityId","channel"),Pd((t=>Ii((async a=>{await(async a=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Sa(a),a.channelId!==e)return;const o=null===(s=at(["channel","get",e]))||void 0===s?void 0:s.data;o&&($l(o,{messagePreviewId:a.messageId}),t(a))})(a),t(a)}))),"channelId","channel"),Pd((t=>Ci((async a=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Sa(a),a.channelId!==e)return;const o=null===(s=at(["channel","get",e]))||void 0===s?void 0:s.data;o&&($l(o,{messagePreviewId:a.messageId}),t(a))}))),"channelId","channel"),Pd((t=>Fl((async a=>{var s;const o=null===(s=at(["channel","get",e]))||void 0===s?void 0:s.data;if(!o||o.messagePreviewId!==a.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await Oa(a),t(a))}))),"channelId","channel"),Pd((t=>_l((async a=>{var s;const o=null===(s=at(["channel","get",e]))||void 0===s?void 0:s.data;if(!o||o.messagePreviewId!==a.messageId)return;const i=await n.getMessagePreviewSetting(!1);"no-message-preview"!==i&&("message-preview-not-include-deleted"===i?(rt(["messagePreviewChannel","get",e]),await vc(a.channelId)):await Oa(a),t(a))}))),"channelId","channel"),Pd((e=>Si((async t=>{var a,s;const{channelId:o,subChannelId:i}=t,r=null===(a=at(["messagePreviewChannel","get",o]))||void 0===a?void 0:a.data;if(!r||r.subChannelId!==i)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await vc(o);(null===(s=at(["channel","get",o]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),Pd((t=>Bl((async a=>{var s,o;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Ta(a);const i=null===(s=at(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!i||i.subChannelId!==a.subChannelId)return;(null===(o=at(["channel","get",e]))||void 0===o?void 0:o.data)&&t(a)}))),"channelId","channel"),Pd(wi,"channelId","channel"),Pd(Cu,"channelId","channel"),Pd((e=>wu((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getChannels(tmpid: ${i}) > listen`);const r=new Du(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{rt(d)})),()=>{a(`getChannels(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=Ut();if(!t)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=Ye();a||console.log("For using Live Object feature you need to enable Cache!");n(`liveTotalChannelsUnread(tmpid: ${Date.now()}) > listen`);const s=[];let o,i=!1;const r=t=>{const{data:n}=t,a=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;o=a?nr(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return s.push(wu((e=>{const{data:t}=Uu();Fa(o,t)||r({loading:!1,data:t})}))),(()=>{const e=_e((async()=>Uu()));$e(e,(({error:e,data:t,loading:n,origin:a,cachedAt:o})=>{o===be?(r({data:t,origin:a,loading:!1,error:new Ve(fe,800800,"error")}),i=!0,s.forEach((e=>e()))):i||r({loading:n,data:t,origin:a,error:e}),e&&s.forEach((e=>e()))}))})(),()=>{s.forEach((e=>e()))}},getArchivedChannels:(e,t)=>{const{log:n,cache:a}=Ye();a||console.log(ve);const s=Date.now();n(`getArchivedChannels(tmpid: ${s}) > listen`);const o=new Eu(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{rt(r)})),()=>{n(`getArchivedChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchChannels:(e,t)=>{const{log:n,cache:a}=Ye();a||console.log(ve);const s=Date.now();n(`searchChannels(tmpid: ${s}) > listen`);const o=new Nu(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{rt(r)})),()=>{n(`searchChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Aa,isUnreadCountSupport:Ra,convertFromRaw:Pa,preUpdateChannelCache:Da,prepareChannelPayload:Ua});const Vu=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));st(["communityUsers","collection",e],n)}))},Ju=async(e,t)=>{const n=Ye();n.log("community/getCommunities",e);const a=e.map((e=>encodeURIComponent(e))),{data:s}=await n.http.get("/api/v3/communities/list",{params:{communityIds:a,includeDiscoverablePrivateCommunity:null==t||t}}),o=_r(s),i=n.cache&&Date.now();return n.cache&&(Fn(o,{cachedAt:i}),Vu(o.communities,o.communityUsers)),{data:o.communities.map((e=>hd.community(e))),cachedAt:i}};Ju.locally=e=>{const t=Ye();if(t.log("community/getCommunities.locally",e),!t.cache)return;const n=e.map((e=>at(["community","get",e]))).filter(Boolean),a=n.map((({data:e})=>e)),s=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1))[0];return n.length<e.length?void 0:{data:a,cachedAt:s.cachedAt}};const Hu=async e=>{const t=Ye();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),a=_r(n),s=t.cache&&Date.now();t.cache&&(Fn(a,{cachedAt:s}),Vu(a.communities,a.communityUsers));const{communities:o}=a;return{data:o.find((t=>t.communityId===e)),cachedAt:s}};Hu.locally=e=>{const t=Ye();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=at(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Gu=(e,t)=>{const n=Ye();return xt(n,e,e,(e=>{const a=_r(e);if(n.cache){Fn(a);const e=at(["community","get",a.communities[0].communityId]);t(e.data)}else t(a.communities[0])}))},zu=e=>Gu("community.created",e),Yu=e=>Gu("community.updated",e),Wu=e=>Gu("community.deleted",e);class Xu extends Cr{async getRequest(e,t){var n;const{limit:a=ge}=e,s=Bn(e,["limit"]),o=t?{token:t}:{limit:a},{data:i}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:oa(s.includeDeleted),keyword:s.displayName,filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return i}}class Zu extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communities.map(Ze("community"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ze("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var eh,th;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(eh||(eh={})),function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned",e.OnMemberCountChanged="OnMemberCountChanged",e.OnCommunityUserAdded="OnCommunityUserAdded",e.onCommunityUserRemoved="onCommunityUserRemoved",e.OnUserDeleted="OnUserDeleted",e.OnLocalCommunityJoin="OnLocalCommunityJoin"}(th||(th={}));class nh extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a,excludingRoles:s}=e,o=Bn(e,["limit","includeDeleted","excludingRoles"]),i=t?{token:t}:{limit:n},r=!1!==a&&void 0,{data:c}=await this.http.get(`/api/v3/communities/${o.communityId}/users`,{params:Object.assign(Object.assign({},o),{options:i,isDeleted:r})});return c}}class ah extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Ze("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Ze("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{var t;const n=Ze("communityUsers")({communityId:this.query.communityId,userId:e.userId});if("none"===e.communityMembership)a.data=a.data.filter((e=>e!==n));else if(!a.data.includes(n)){if(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length){if((e.roles||[]).some((e=>this.query.excludingRoles.includes(e))))return}a.data=[n,...a.data]}})),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function sh(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function oh(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers:"community.userRemoved"===e||"local.community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership)):"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership)):"community.userUnbanned"===e?t.communityUsers.filter((e=>!sh(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!sh(e,t,"ADD_COMMUNITY_USER")))}const ih=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{const s=_r(a),{communities:o,communityUsers:i}=s,r=Nr(o,i);if(s.communities=r,n.cache){Fn(s,void 0,!1);const n=at(["community","get",s.communities[0].communityId]),a=oh(e,s).map((e=>{const t=at(["communityUsers","get",Ze("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Pr);t(n.data,a)}else t(s.communities[0],oh(e,s))}))},rh=(e,t)=>{const n=Ye();return xt(n,e,e,(a=>{const s=_r(a),{communities:o,communityUsers:i}=s,r=Nr(o,i);if(s.communities=r,n.cache){Fn(s,void 0,!1);const n=at(["community","get",s.communities[0].communityId]),a=oh(e,s).map((e=>{const t=at(["communityUsers","get",Ze("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Pr);t(n.data,a)}else t(s.communities[0],oh(e,s))}))},ch=e=>ih("community.userBanned",e),dh=e=>ih("community.userChanged",e),lh=e=>ih("community.userUnbanned",e),uh=e=>ih("community.roleAdded",e),hh=e=>ih("community.roleRemoved",e),mh=e=>rh("local.community.userAdded",e),gh=e=>rh("local.community.userRemoved",e),ph=e=>ih("community.joined",e),yh=e=>ih("community.left",e),vh=e=>rh("local.community.joined",e),fh=e=>rh("local.community.left",e),bh=e=>{const t=Ye(),n=[xt(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},Ih=e=>{const t=Ye();return xt(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:a}=t;e(n[0],a.filter((e=>"member"===e.communityMembership)))}))},Ch=e=>{const t=Ye();return xt(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:a}=t;e(n[0],a.filter((e=>"member"===e.communityMembership)))}))},wh=e=>t=>{const n=Ye();return xt(n,"user.deleted","user.deleted",(n=>{var a,s;const o=eo(n);if(0===o.users.length)return;const i=o.users[0];Fn(o);const r=Ze("communityUsers")({communityId:e,userId:i.userId}),c=null===(a=at(["communityUsers","get",r]))||void 0===a?void 0:a.data;st(["communityUsers","get",r],Object.assign(Object.assign({},c),{user:i}));const d=null===(s=at(["community","get",e]))||void 0===s?void 0:s.data;t(d,[Object.assign(Object.assign({},c),{user:i})])}))};class Sh extends Rr{constructor(e,t){const n=R.default(e),a=["communityUsers","collection",n];super(new nh(e),n,a,t),this.query=e,this.queryStreamController=new ah(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ph,action:th.OnCommunityJoined},{fn:vh,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:fh,action:th.OnCommunityLeft},{fn:ch,action:th.OnCommunityUserBanned},{fn:dh,action:th.OnCommunityUserChanged},{fn:uh,action:th.OnCommunityUserRoleAdded},{fn:hh,action:th.OnCommunityUserRoleRemoved},{fn:Ch,action:th.OnCommunityUserRoleAdded},{fn:Ih,action:th.OnCommunityUserRoleRemoved},{fn:lh,action:th.OnCommunityUserUnbanned},{fn:mh,action:th.OnCommunityUserAdded},{fn:gh,action:th.onCommunityUserRemoved},{fn:wh(this.query.communityId),action:th.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["communityUsers","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=lt(e,"roles",this.query.roles);if(this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length)&&(n=n.filter((e=>!(e.roles||[]).some((e=>this.query.excludingRoles.includes(e)))))),!1===this.query.includeDeleted&&(n=n.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),"firstCreated"===this.query.sortBy)n=n.sort(Ct);else n=n.sort(St);return n}}class Oh extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a,excludingRoles:s}=e,o=Bn(e,["limit","includeDeleted","excludingRoles"]),i=t?{token:t}:{limit:n},r=!1!==a&&void 0,{data:c}=await this.http.get(`/api/v3/communities/${o.communityId}/users`,{params:Object.assign(Object.assign({},o),{options:i,isDeleted:r})});return c}}class Th extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Ze("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Ze("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{const t=Ze("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(a.data=a.data.filter((e=>e!==t)))})),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Ah;!function(e){e.OnCommunityJoined="onCommunityJoined",e.OnLocalCommunityJoin="onLocalCommunityJoin",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned"}(Ah||(Ah={}));class Rh extends Rr{constructor(e,t){const n=R.default(e),a=["communityUsers","collection",n];super(new Oh(e),n,a,t),this.query=e,this.queryStreamController=new Th(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ph,action:Ah.OnCommunityJoined},{fn:vh,action:Ah.OnCommunityJoined},{fn:yh,action:Ah.OnCommunityLeft},{fn:fh,action:Ah.OnCommunityLeft},{fn:ch,action:Ah.OnCommunityUserBanned},{fn:dh,action:Ah.OnCommunityUserChanged},{fn:Ih,action:Ah.OnCommunityUserRoleRemoved},{fn:hh,action:Ah.OnCommunityUserRoleRemoved},{fn:lh,action:Ah.OnCommunityUserUnbanned},{fn:wh(this.query.communityId),action:Ah.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["communityUsers","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=lt(e,"roles",this.query.roles);return this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(n=pt(n,this.query.search)),(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length)&&(n=n.filter((e=>!(e.roles||[]).some((e=>this.query.excludingRoles.includes(e)))))),!1===this.query.includeDeleted&&(n=n.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),n}}var Ph=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ye();n.log("community/moderation/addMembers",e,t);const{data:a}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});Nt("local.community.userAdded",a);const s=Ln(a,"communityUsers");n.cache&&Fn(s);const{communityUsers:o}=s;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=Ye();n.log("community/moderation/removeMembers",e,t);const{data:a}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});Nt("local.community.userRemoved",a);const s=Ln(a,"communityUsers");n.cache&&Fn(s);const{communityUsers:o}=s;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{var n;let a=lt(e,"roles",t.roles);t.memberships&&(a=a.filter((({communityMembership:e})=>t.memberships.includes(e)))),(null===(n=t.excludingRoles)||void 0===n?void 0:n.length)&&(a=a.filter((e=>!(e.roles||[]).some((e=>t.excludingRoles.includes(e))))));const s=t.sortBy?t.sortBy:"lastCreated";return a=a.sort("lastCreated"===s?St:Ct),a},getMembers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new Sh(e,(e=>{t(e)})),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new Rh(e,(e=>{t(e)})),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},onCommunityUserAdded:e=>ih("community.userAdded",e),onCommunityUserRemoved:e=>ih("community.userRemoved",e),onCommunityUserBanned:ch,onCommunityUserChanged:dh,onCommunityUserUnbanned:lh,onCommunityUserRoleAdded:uh,onCommunityUserRoleRemoved:hh,onLocalCommunityUserAdded:mh,onLocalCommunityUserRemoved:gh,onCommunityJoined:ph,onCommunityLeft:yh,onLocalCommunityJoined:vh,onLocalCommunityLeft:fh,onLocalCommunityJoin:bh});class Dh extends Rr{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Xu(e),n,a,t),this.query=e,this.queryStreamController=new Zu(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Wu,action:eh.OnCommunityDeleted},{fn:Yu,action:eh.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:eh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["community","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ye();let n=e;return this.query.includeDeleted||(n=ct(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.membership&&t&&(n=mt(n,this.query.membership,t)),n}}class Uh extends Cr{async getRequest(e,t){var n;const{limit:a=ge}=e,s=Bn(e,["limit"]),o=t?{token:t}:{limit:a},{data:i}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:oa(s.includeDeleted),filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return i}}class kh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&(Fn(t,{cachedAt:a}),Vu(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communities.map(Ze("community"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ze("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var jh;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(jh||(jh={}));class Eh extends Rr{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Uh(e),n,a,t),this.query=e,this.queryStreamController=new kh(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:zu,action:jh.OnCommunityCreated},{fn:Wu,action:jh.OnCommunityDeleted},{fn:Yu,action:jh.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:jh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["community","get",e]))).filter(Pr).map((({data:e})=>mc(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ye();let n=e;this.query.includeDeleted||(n=ct(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.membership&&t&&(n=mt(n,this.query.membership,t));const a=(()=>"firstCreated"===this.query.sortBy?Ct:St)();return n=n.sort(a),n}}class Mh extends Cr{async getRequest(e,t){const{limit:n=ge,includeDiscoverablePrivateCommunity:a}=e,s=Bn(e,["limit","includeDiscoverablePrivateCommunity"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},s),{options:o,includeDiscoverablePrivateCommunity:null==a||a})});return i}}class qh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&(Fn(t,{cachedAt:a}),Vu(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communities.map(Ze("community"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ze("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var xh;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(xh||(xh={}));class Nh extends Rr{constructor(e,t){const n=R.default(e),a=["trendingCommunity","collection",n];super(new Mh(e),n,a,t),this.query=e,this.queryStreamController=new qh(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Wu,action:xh.OnCommunityDeleted},{fn:Yu,action:xh.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:xh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["community","get",e]))).filter(Pr).map((({data:e})=>mc(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Kh extends Cr{async getRequest(e,t){const{limit:n=ge,includeDiscoverablePrivateCommunity:a}=e,s=Bn(e,["limit","includeDiscoverablePrivateCommunity"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},s),{options:o,includeDiscoverablePrivateCommunity:null==a||a})});return i}}class Fh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&(Fn(t,{cachedAt:a}),Vu(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.communities.map(Ze("community"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ze("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var _h;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(_h||(_h={}));class Bh extends Rr{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Kh(e),n,a,t),this.query=e,this.queryStreamController=new Fh(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Wu,action:_h.OnCommunityDeleted},{fn:Yu,action:_h.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:_h.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["community","get",e]))).filter(Pr).map((({data:e})=>mc(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class $h extends Cr{async getRequest(e,t){var n;const{limit:a=ge,communityMembershipStatus:s}=e,o=Bn(e,["limit","communityMembershipStatus"]),i={type:e.limit?"pagination":void 0},r=t?Object.assign(Object.assign({},i),{token:t}):Object.assign(Object.assign({},i),{limit:a}),{data:c}=await this.http.get("/api/v1/semantic-search/communities",{params:Object.assign(Object.assign({},o),{filter:null!=s?s:"all",options:r,includeDiscoverablePrivateCommunity:null===(n=o.includeDiscoverablePrivateCommunity)||void 0===n||n})});return c}}function Lh(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class Qh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:Lh(e)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Lh(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Vh;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Vh||(Vh={}));class Jh extends Rr{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new $h(e),n,a,t),this.query=e,this.queryStreamController=new Qh(this.query,this.cacheKey,this.notifyChange.bind(this),Qr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:zu,action:Vh.OnCommunityCreated},{fn:Wu,action:Vh.OnCommunityDeleted},{fn:Yu,action:Vh.OnCommunityUpdated},{fn:ph,action:th.OnCommunityJoined},{fn:yh,action:th.OnCommunityLeft},{fn:dh,action:th.OnMemberCountChanged},{fn:vh,action:th.OnCommunityJoined},{fn:fh,action:th.OnCommunityLeft},{fn:Pd(bh,"targetId","community"),action:Vh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>{const[t,n]=e.split(":");return{communityId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({communityId:e})=>at(["community","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ye();let n=e;return this.query.categoryIds&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.some((e=>!this.query.categoryIds||(0===this.query.categoryIds.length||this.query.categoryIds.includes(e))))}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.communityMembershipStatus&&t&&(n=mt(n,this.query.communityMembershipStatus,t)),n}}class Hh extends Cr{async getRequest(e,t){const{limit:n=ge,communityIds:a}=e,s=Bn(e,["limit","communityIds"]),o=t?{token:t}:{limit:n},i=a.map((e=>encodeURIComponent(e))),{data:r}=await this.http.get("/api/v4/communities/join/requests",{params:Object.assign(Object.assign({},s),{options:o,communityIds:i})});return r}}var Gh;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Gh||(Gh={}));class zh extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.joinRequests.map((e=>Ze("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Ze("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;const s=(Array.isArray(t)?t:[t]).map((e=>e.joinRequestId));if(e===Gh.OnLocalJoinRequestUpdated){if(!a.data.find((e=>s.includes(e))))return}e===Gh.OnLocalJoinRequestCreated&&(a.data=[...new Set([...s,...a.data])]),e===Gh.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>!s.includes(e)))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Yh extends Rr{constructor(e,t){const n=R.default(e),a=["joinRequestList","collection",n];super(new Hh(e),n,a,t),this.query=e,this.queryStreamController=new zh(this.query,this.cacheKey,this.notifyChange.bind(this),Br),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const a=e;this.queryStreamController.appendToQueryStream(a,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:zr,action:Gh.OnLocalJoinRequestCreated},{fn:Yr,action:Gh.OnLocalJoinRequestUpdated},{fn:Wr,action:Gh.OnLocalJoinRequestUpdated},{fn:bh,action:Gh.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(s.data.map((e=>at(["joinRequest","get",e]))).filter(Pr).map((({data:e})=>e)).map(Vr));(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.communityIds&&this.query.communityIds.length>0&&(t=t.filter((e=>this.query.communityIds.some((t=>t===e.targetId)))));const n=(()=>"firstCreated"===this.query.sortBy?Ct:St)();return t=t.sort(n),t}}var Wh;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(Wh||(Wh={}));var Xh=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const a=Ye();a.log("community/moderation/addRoles",e,t,n);const{data:s}=await a.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),o=$r(s);a.cache&&Fn(o),Nt("local.community.roleAdded",o);const{communityUsers:i}=o;return!!i.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const a=Ye();a.log("community/moderation/removeRoles",e,t,n);const{data:s}=await a.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),o=$r(s);a.cache&&Fn(o),Nt("local.community.roleRemoved",o);const{communityUsers:i}=o;return!!i.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=Ye();n.log("community/banMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=Ln(a,"communityUsers"),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{communityUsers:i}=s;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:o}},unbanMembers:async(e,t)=>{const n=Ye();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=Ln(a,"communityUsers"),o=n.cache&&Date.now();n.cache&&Fn(s,{cachedAt:o});const{communityUsers:i}=s;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:o}}}),Zh=Object.freeze({__proto__:null,Moderation:Xh,Membership:Ph,getCommunityByIds:Ju,createCommunity:async e=>{const t=Ye();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",Lr(e));Nt("community.created",n);const a=_r(n),s=t.cache&&Date.now();t.cache&&(Fn(a,{cachedAt:s}),Vu(a.communities,a.communityUsers));const{communities:o}=a;return{data:hd.community(o[0]),cachedAt:s}},updateCommunity:async(e,t)=>{const n=Ye();n.log("community/updateCommunity",e,t);const{data:a}=await n.http.put(`/api/v3/communities/${e}`,Lr(t));Nt("community.updated",a);const s=_r(a),o=n.cache&&Date.now();n.cache&&(Fn(s,{cachedAt:o}),Vu(s.communities,s.communityUsers));const{communities:i}=s;return{data:hd.community(i.find((t=>t.communityId===e))),cachedAt:o}},deleteCommunity:async e=>{const t=Ye();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await Hu(e);return Nt("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),hd.community(n.data)},joinCommunity:async e=>{const t=Ye();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);Nt("local.community.joined",n);const a=_r(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=Ye();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);Nt("local.community.left",n);const a=_r(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:zu,onCommunityUpdated:Yu,onCommunityDeleted:Wu,searchCommunities:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`searchCommunities(tmpid: ${o}) > listen`);const i=new Dh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`searchCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCommunities(tmpid: ${o}) > listen`);const i=new Eh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunity:(e,t)=>qr(e,t,"communityId",Hu,[Yu,Wu,ph,yh,vh,fh,ch,lh,dh,Pd(bh,"targetId","community")],{callbackDataSelector:e=>e?hd.community(e):e}),getTrendingCommunities:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getTrendingCommunities(tmpid: ${i}) > listen`);const r=new Nh(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>rt(d))),()=>{a(`getTrendingCommunities(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getRecommendedCommunities(tmpid: ${i}) > listen`);const r=new Bh(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>rt(d))),()=>{a(`getRecommendedCommunities(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`semanticSearchCommunities(tmpid: ${o}) > listen`);const i=new Jh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`semanticSearchCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getJoinRequestList: (tmpid: ${o}) > listen`);const i=new Yh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getJoinRequestList (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return Wh}});const em=async e=>{const t=Ye();t.log("category/getCategory",e);const{data:n}=await t.http.get(`/api/v3/community-categories/${encodeURIComponent(e)}`),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{categories:s}=n;return{data:hd.category((null!=s?s:[]).find((t=>t.categoryId===e))),cachedAt:a}};em.locally=e=>{const t=Ye();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=at(["category","get",e]);return n?{data:hd.category(n.data),cachedAt:n.cachedAt}:void 0};const tm=async e=>{const t=Ye();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:a,limit:s,includeDeleted:o}=n,i=Bn(n,["page","limit","includeDeleted"]),r=a?{token:a}:s?{limit:s}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},i),{isDeleted:oa(o),options:r})}),{paging:d}=c,l=Bn(c,["paging"]),{categories:u}=l,h=t.cache&&Date.now();if(t.cache){Fn(l,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},i),{includeDeleted:o,options:r})];st(e,{categories:null==u?void 0:u.map(Ze("category")),paging:d})}return{data:null!=u?u:[],cachedAt:h,paging:d}};tm.locally=e=>{var t,n;const a=Ye();if(a.log("category/queryCategories.locally",e),!a.cache)return;const s=null!=e?e:{},{page:o,limit:i=10}=s,r=Bn(s,["page","limit"]),c=o?{token:o}:i?{limit:i}:void 0,d=["category","query",Object.assign(Object.assign({},r),{options:c})],{data:l,cachedAt:u}=null!==(t=at(d))&&void 0!==t?t:{};if(!(null==l?void 0:l.categories.length))return;const h=l.categories.map((e=>at(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:m}=l;return h.length===(null===(n=null==l?void 0:l.categories)||void 0===n?void 0:n.length)?{data:h,cachedAt:u,paging:m}:void 0};var nm=Object.freeze({__proto__:null,getCategory:em,getCategories:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCategories(tmpid: ${o}) > listen`);const{limit:i}=e,r=Bn(e,["limit"]),c=null!=i?i:ge,{policy:d=ye}=null!=n?n:{},l=[],u=["category","collection",{}],h=(n=!1)=>{var a,s;const o=null===(a=at(u))||void 0===a?void 0:a.data,i=null!==(s=null==o?void 0:o.data)&&void 0!==s?s:[];if(!n&&i.length>0&&!(null==o?void 0:o.params.page))return;const l=_e(tm,Object.assign(Object.assign({},r),{limit:n?c:void 0,page:n||null==o?void 0:o.params.page}));$e(l,(({data:n,error:a,loading:s,paging:o})=>{const r={loading:s,error:a,params:{page:null==o?void 0:o.next},data:i};n&&(r.data=[...new Set([...i,...n.map(Ze("category"))])]),st(u,r),(n=>{var a,s;let o=null!==(a=n.data.map((e=>at(["category","get",e]))).filter(Boolean).map((({data:e})=>hd.category(e))))&&void 0!==a?a:[];switch(e.includeDeleted||(o=ct(o,"isDeleted",!1)),e.sortBy){case"firstCreated":o=o.sort(Ct);break;case"lastCreated":o=o.sort(St);break;default:o=o.sort(It)}t({onNextPage:h,data:o,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})})(r)}),Be(d))};return l.push((()=>{})),h(!0),()=>{a(`getCategories(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}}});const am=async e=>{const t=Ye();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:a,dataTypes:s}=n,o=Bn(n,["queryToken","dataTypes"]),i=(()=>{if(a)return{token:a}})(),{data:r}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},o),{dataTypes:s,resolveParent:!!(s&&s.length>0)||void 0,options:i})}),{paging:c}=r,d=Bn(r,["paging"]),l=Ln(d,"communityUsers"),{posts:u}=l,{communities:h}=_r(l),m=t.cache&&Date.now();if(t.cache){Fn(Object.assign(Object.assign({},l),{communitis:h}));const e=["globalFeed","query",Object.assign(Object.assign({},o),{options:i})];st(e,{posts:u.map(Ze("post")),paging:c})}return{data:u.map(hd.post),cachedAt:m,paging:c}};am.locally=e=>{var t;const n=Ye();if(n.log("post/queryGlobalFeed.locally",e),!n.cache)return;const a=Bn(null!=e?e:{},[]),s=["globalFeed","query",Object.assign({},a)],{data:o,cachedAt:i}=null!==(t=at(s))&&void 0!==t?t:{};if(!(null==o?void 0:o.posts.length))return;const r=o.posts.map((e=>at(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(hd.post),{paging:c}=o;return r.length===o.posts.length?{data:r,cachedAt:i,paging:c}:void 0};class sm extends Cr{async getRequest(e,t){const{limit:n}=e,a=Bn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},a),{options:s})});return o}}var om;!function(e){e.OnPostCreated="onPostCreated",e.OnPostUpdated="onPostUpdated",e.OnPostDeleted="onPostDeleted",e.OnPostFlagged="onPostFlagged",e.OnPostUnflagged="onPostUnflagged",e.OnPostReactionAdded="onPostReactionAdded",e.OnPostReactionRemoved="onPostReactionRemoved",e.OnPostApproved="onPostApproved",e.OnPostDeclined="onPostDeclined",e.OnPostPinProduct="onPostPinProduct",e.OnPostUnpinProduct="onPostUnpinProduct",e.OnPostUpdateProductTags="onPostUpdateProductTags"}(om||(om={}));class im extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.posts.map(Ze("post"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ze("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===om.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===om.OnPostCreated||e===om.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;a.data=[...new Set([t.postId,...a.data])]}e===om.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const rm=async e=>{const t=Ye();t.log("comment/getCommentByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/comments/list",{params:{commentIds:n}})).data}catch(t){throw e.forEach((e=>{Pe(null==t?void 0:t.code)&&_n("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.comments.map((e=>hd.comment(e))),cachedAt:s}};rm.locally=e=>{var t;const n=Ye();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const a=e.map((e=>at(["comment","get",e]))).filter(Boolean),s=a.map((({data:e})=>e)),o=null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==a?void 0:a.length)<e.length?void 0:{data:s.map((e=>hd.comment(e))),cachedAt:o.cachedAt}};const cm=e=>{const t=Ye();if(!t.cache)return;const n=kn();t.log("comment/createComment.optimistically",Object.assign({commentId:n},e));const a=(new Date).toISOString(),s={commentId:n,userId:t.userId,parentId:e.parentId,rootId:e.parentId||n,childrenNumber:0,children:[],segmentNumber:0,editedAt:a,referenceId:e.referenceId,referenceType:e.referenceType,data:e.data,metadata:e.metadata,mentionees:e.mentionees,attachments:e.attachments,links:e.links,createdAt:a,updatedAt:a,isDeleted:!1,flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,myReactions:[],path:"",targetId:"",targetType:"community",dataType:"text",syncState:"syncing"};return st(["comment","get",s.commentId],s,{cachedAt:-5}),Nt("local.comment.created",{comments:[s],commentChildren:[],users:[],files:[],communityUsers:[]}),s},dm=(e,t=!1)=>{const{stories:n}=e,a=n.map((e=>((e,t=!1)=>{const{storyId:n,referenceId:a}=e;return!t&&a?Object.assign(Object.assign({},e),{syncState:"synced"}):Object.assign(Object.assign({},e),{syncState:"synced",referenceId:n})})(e,t)));return Object.assign(Object.assign({},e),{stories:a})},lm=async e=>{const t=Ye();t.log("story/getStoryByStoryId",e);const n=at(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;ea("story",e)}let a;try{const n=await t.http.get(`/api/v4/stories/${e}`);a=dm(n.data)}catch(t){throw Pe(null==t?void 0:t.code)&&_n("story",e),t}const s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.stories[0],cachedAt:s}};lm.locally=e=>{const t=Ye();t.log("story/getStorybyStoryId",e);const n=at(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;ea("story",e)}const a=t.cache&&Date.now(),s=at(["story","get",e]);if(s)return{data:s.data,cachedAt:a}};const um=async(e,t=!1)=>{var n,a,s;const o=Ye(),i=null===(n=at(["comment","get",e]))||void 0===n?void 0:n.data;if("error"===(null==i?void 0:i.syncState)){const t=Object.assign(Object.assign({},i),{isDeleted:!0});return rt(["comment","get",e]),Nt("local.comment.deleted",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]}),t}const r=await nl(e);await o.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const c=Object.assign(Object.assign({},r.data),{isDeleted:!0});if(t?Mt((()=>_n("comment",e))):it(["comment","get",e],{isDeleted:!0}),"story"===r.data.referenceType){const e=await lm(r.data.referenceId);Nt("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const t=null===(a=at(["post","get",r.data.referenceId]))||void 0===a?void 0:a.data;if(t){const n=Xd();n.queueCommentChangeTask(new Gd(t.postId,e)),!c.parentId&&(null===(s=c.children)||void 0===s?void 0:s.length)>0&&c.children.forEach((e=>{n.queueCommentChangeTask(new Gd(t.postId,e))}))}}return Nt("local.comment.deleted",{comments:[c],commentChildren:[],files:[],users:[],communityUsers:[]}),c},hm=async e=>{const t=Ye();let n;t.log("comment/getComment",e),ea("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("comment",e),t}const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{comments:s}=n;return{data:s.find((t=>t.commentId===e)),cachedAt:a}};hm.locally=e=>{const t=Ye();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=at(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const mm=e=>Sl("local.comment.deleted",e),gm=e=>{const t=Ye();return xt(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(it(["comment","get",n.commentId],n),e(Ic(n))):e(n)}))},pm=e=>{const t=Ye();return xt(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(it(["comment","get",n.commentId],n),e(Ic(n))):e(n)}))};class ym extends Cr{async getRequest(e,t){var n;const{pageSize:a,limit:s,includeDeleted:o}=e,i=Bn(e,["pageSize","limit","includeDeleted"]),r=null!==(n=null!=a?a:s)&&void 0!==n?n:ge,c={type:i.sortBy||e.limit||e.pageSize?"pagination":void 0},d=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{pageSize:r,limit:r}),{data:l}=await this.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},i),{isDeleted:oa(o),options:d})});return l}}var vm;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(vm||(vm={}));class fm extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.comments.map(Ze("comment"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(Ze("comment"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;this.query.referenceId===t.referenceId&&this.query.referenceType===t.referenceType&&a&&(this.query.parentId&&this.query.parentId!==t.parentId||!this.query.parentId&&t.parentId||(e===vm.OnCommentCreated&&(a.data=[...new Set([t.commentId,...a.data])]),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const bm=e=>Sl("local.comment.created",e);class Im extends Rr{constructor(e,t){const n=R.default(e),a=["comments","collection",n];super(new ym(e),n,a,t),this.query=e,this.queryStreamController=new fm(this.query,this.cacheKey,this.notifyChange.bind(this),Nl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){const e=this.queryStreamController.subscribeRTE([{fn:bm,action:vm.OnCommentCreated},{fn:mm,action:vm.OnCommentDeleted},{fn:Ol,action:vm.OnCommentCreated},{fn:Tl,action:vm.OnCommentUpdated},{fn:Al,action:vm.OnCommentDeleted},{fn:Rl,action:vm.OnCommentFlagged},{fn:Pl,action:vm.OnCommentUnflagged},{fn:Dl,action:vm.OnCommentReactionAdded},{fn:Ul,action:vm.OnCommentReactionRemoved},{fn:gm,action:vm.OnCommentReactionAdded},{fn:pm,action:vm.OnCommentReactionRemoved}]);if(this.query.excludeBlockUserComments){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Yo(t),Wo(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["comment","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.comment);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=ct(t,"isDeleted",!1)),this.query.parentId&&(t=t.filter((e=>e.parentId===this.query.parentId))),"boolean"==typeof this.query.hasFlag&&(t=this.query.hasFlag?t.filter((e=>null!=e.hashFlag)):t.filter((e=>null==e.hashFlag))),this.query.dataTypes&&("exact"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t,n;const a=(null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.sort())||[],s=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return s.length===a.length&&a.every(((e,t)=>e===s[t]))}))),"any"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t;return null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.some((t=>{var n;return null===(n=e.dataTypes)||void 0===n?void 0:n.includes(t)}))})))),this.query.excludeBlockUserComments&&(t=ft(t)),"firstCreated"===this.query.sortBy)t=t.sort(Ct);else t=t.sort(St);return t}}var Cm=Object.freeze({__proto__:null,getCommentByIds:rm,createComment:async e=>{const t=Ye();t.log("comment/createComment",e);const n=cm(e),a=null==n?void 0:n.commentId;try{const{data:n}=await t.http.post("/api/v3/comments",Object.assign(Object.assign({},e),{commentId:a})),{comments:s}=n;if(0===s.length)throw new Error("Comment not created");const o=t.cache&&Date.now();if(t.cache&&Fn(n,{cachedAt:o}),["post","content"].includes(e.referenceType))Xd().queueCommentChangeTask(new Hd(e.referenceId,s[0].commentId,n.comments[0].createdAt));else if("story"===e.referenceType){const t=at(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=at(["story","get",t.data]);(null==e?void 0:e.data)&&Nt("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,s[0].commentId])]})],categories:[],comments:s,communities:[],communityUsers:n.communityUsers,files:n.files,users:n.users})}}return Nt("local.comment.created",{comments:[Object.assign(Object.assign({},s[0]),{syncState:"synced"})],commentChildren:n.commentChildren,users:n.users,files:n.files,communityUsers:n.communityUsers}),{data:hd.comment(s[0]),cachedAt:o}}catch(e){throw n&&Nt("local.comment.created",{comments:[Object.assign(Object.assign({},n),{syncState:"error"})],commentChildren:[],users:[],files:[],communityUsers:[]}),e}},updateComment:async(e,t)=>{const n=Ye();n.log("user/updateComment",t);const{data:a}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),s=n.cache&&Date.now();n.cache&&Fn(a,{cachedAt:s}),Nt("comment.updated",a);const{comments:o}=a;return{data:hd.comment(o.find((t=>t.commentId===e))),cachedAt:s}},deleteComment:um,softDeleteComment:async e=>{Ye().log("comment/softDeleteComment",e);return um(e)},hardDeleteComment:async e=>{Ye().log("comment/hardDeleteComment",e);return um(e,!0)},flagComment:async(t,n)=>{const a=Ye();a.log("comment/flagComment",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),o={reason:n&&s?n:e.ContentFlagReasonEnum.Others,detail:n&&!s?n:""},{data:i}=await a.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`,o);return a.cache&&Fn(i),Nt("comment.flagged",i),!!i},unflagComment:async e=>{const t=Ye();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Fn(n),Nt("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=Ye();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:Ol,onCommentUpdated:Tl,onCommentDeleted:Al,onCommentFlagged:Rl,onCommentUnflagged:Pl,onCommentReactionAdded:Dl,onCommentReactionRemoved:Ul,getComment:(e,t)=>qr(e,t,"commentId",hm,[mm,Al,Rl,Dl,Ul,Pl,Tl,gm,pm]),getComments:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();a(`getComments(tmpid: ${o}) > listen`);const i=new Im(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getComments(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});const wm=e=>hl("local.post.deleted",e),Sm=e=>{const t=Ye();return xt(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(it(["post","get",n.postId],n),e(n)):e(n)}))},Om=e=>{const t=Ye();return xt(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(it(["post","get",n.postId],n),e(n)):e(n)}))},Tm=e=>hl("local.post.updated",e),Am=e=>[Ol,Al,bm,mm].map((t=>({fn:Pd((n=>((e,t,n)=>t((async t=>{var a;const s=null===(a=at(n))||void 0===a?void 0:a.data;s&&s.data.includes(t.referenceId)&&e(t)})))(n,t,e)),"referenceId","post"),action:om.OnPostUpdated}))),Rm=e=>[{fn:ml,action:om.OnPostCreated},{fn:gl,action:om.OnPostUpdated},{fn:Tm,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Sm,action:om.OnPostReactionAdded},{fn:Om,action:om.OnPostReactionRemoved},{fn:wm,action:om.OnPostDeleted},...Am(e)];class Pm extends Rr{constructor(e,t){const n=R.default(e),a=["customRankingGlobalFeed","collection",n];super(new sm(e),n,a,t),this.query=e,this.queryStreamController=new im(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(Rm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Dm extends Cr{async getRequest(e,t){const{limit:n,dataTypes:a}=e,s=Bn(e,["limit","dataTypes"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},s),{dataTypes:a,resolveParent:!!(a&&a.length>0)||void 0,options:o})});return i}}class Um extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.posts.map(Ze("post"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ze("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===om.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===om.OnPostCreated||e===om.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;a.data=[...new Set([t.postId,...a.data])]}e===om.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class km extends Rr{constructor(e,t){const n=R.default(e),a=["globalFeed","collection",n];super(new Dm(e),n,a,t),this.query=e,this.queryStreamController=new Um(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(Rm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class jm extends Cr{async getRequest(e,t){const{userId:n,feedSources:a,dataTypes:s,includeDeleted:o,matchingOnlyParentPost:i,limit:r=ge,untilAt:c}=e,d=Bn(e,["userId","feedSources","dataTypes","includeDeleted","matchingOnlyParentPost","limit","untilAt"]),l=t?{token:t}:{limit:r},{data:u}=await this.http.get(`/api/v4/user-feeds/${n}`,{params:Object.assign(Object.assign({},d),{options:l,dataTypes:(null==s?void 0:s.length)?s:void 0,includePostedFeed:a,isDeleted:oa(o),matchingOnlyParentPost:null!=i?i:!(null==s?void 0:s.length)})});return u}}class Em extends Sr{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?Rt(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;let o=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated",t=o.filter((t=>!Pt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)st(this.cacheKey,{data:o.map(Ze("post"))});else{const e=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Ze("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(s&&(this.query.dataTypes&&0!==this.query.dataTypes.length||s.data.includes(t.parentPostId?t.parentPostId:t.postId))){if(void 0!==this.validatedUntilAt&&(e===om.OnPostCreated||e===om.OnPostApproved||e===om.OnPostUpdated)){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Pt(t.createdAt,this.validatedUntilAt,e))return}if(e===om.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=at(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),st(["post","get",e.postId],e)}if(e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e===om.OnPostCreated||e===om.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;s.data=[...new Set([t.postId,...s.data])]}st(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const Mm=async e=>{const t=Ye();let n;t.log("post/getPost",e),ea("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("post",e),t}const a=Ln(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{posts:o}=a;return{data:o.find((t=>t.postId===e)),cachedAt:s}};Mm.locally=e=>{const t=Ye();if(t.log("post/getPost.locally",e),!t.cache)return;const n=at(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class qm extends Rr{constructor(e,t){const n=R.default(e),a=["userFeed","collection",n];super(new jm(e),n,a,t),this.query=e,this.queryStreamController=new Em(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ml,action:om.OnPostCreated},{fn:gl,action:om.OnPostUpdated},{fn:Tm,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Sm,action:om.OnPostReactionAdded},{fn:Om,action:om.OnPostReactionRemoved},{fn:wm,action:om.OnPostDeleted},{fn:Pd((e=>Ol((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Mm(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated},{fn:Pd((e=>Al((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Mm(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[],r=this.applyFilter(i).map(hd.post);if(!this.shouldNotify(r)&&"event"===e)return;const c=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:r,hasNextPage:c,loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=ct(n,"isDeleted",!1)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=gt(n,this.query.dataTypes)),this.query.untilAt){const e=Rt(this.query.untilAt),t="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";n=n.filter((n=>!Pt(n.createdAt,e,t)))}if("firstCreated"===this.query.sortBy)n=n.sort(Ct);else n=n.sort(St);return n}}class xm extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a,communityId:s,untilAt:o}=e,i=Bn(e,["limit","includeDeleted","communityId","untilAt"]),r=t?{token:t}:{limit:n},{data:c}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},i),{targetId:s,targetType:"community",isDeleted:oa(a),matchingOnlyParentPost:!0,options:r})});return c}}class Nm extends Sr{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?Rt(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;let o=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated",t=o.filter((t=>!Pt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)st(this.cacheKey,{data:o.map(Ze("post"))});else{const e=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Ze("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===om.OnPostCreated||e===om.OnPostApproved)&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Pt(t.createdAt,this.validatedUntilAt,e))return}if(e===om.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=at(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),st(["post","get",e.postId],e)}e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==om.OnPostCreated&&e!==om.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),st(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const Km=({cacheKey:e,resolveId:t})=>[Ol,Al,bm,mm].map((n=>({fn:Pd((a=>((e,t,n,a)=>t((async t=>{var s;const o=null===(s=at(n))||void 0===s?void 0:s.data;o&&o.data.includes(a?a(t.referenceId):t.referenceId)&&e(t)})))(a,n,e,t)),"referenceId","post"),action:om.OnPostUpdated}))),Fm=e=>[{fn:ml,action:om.OnPostCreated},{fn:gl,action:om.OnPostUpdated},{fn:Tm,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Sm,action:om.OnPostReactionAdded},{fn:Om,action:om.OnPostReactionRemoved},{fn:wm,action:om.OnPostDeleted},...Km({cacheKey:e})],_m=(e,t)=>{var n;return null!==(n=e.map((e=>{const n=t.find((t=>t.postId===e.referenceId));return n?Ze("post")({postId:null==n?void 0:n.postId}):void 0})).filter(Pr))&&void 0!==n?n:[]};class Bm extends Rr{constructor(e,t){const n=R.default(e),a=["communityFeed","collection",n];super(new xm(e),n,a,t),this.query=e,this.queryStreamController=new Nm(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(Fm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);if(!this.shouldNotify(i)&&"event"===e)return;const r=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:r,loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=ct(t,"isDeleted",!1)),this.query.tags&&(t=t.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.untilAt&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e=Rt(this.query.untilAt),n="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";t=t.filter((t=>!Pt(t.createdAt,e,n)))}switch(this.query.sortBy){case"firstCreated":t=t.sort(Ct);break;case"firstUpdated":t=t.sort(Ot);break;case"lastUpdated":t=t.sort(Tt);break;default:t=t.sort(St)}return t}}class $m extends Ve{constructor(e="For You feed is not enabled for this network"){super(e,400400,"error"),this.type="AmityForYouFeedDisabledError"}}class Lm extends Cr{constructor(e){super(e),this.checkedDisk=!1,this.hasDeliveredPost=!1,this.cursor=Xo.current()}async getRequest(e,t){var n,a,s,o,i;const r=void 0===t;let c=null;if(r&&!this.checkedDisk&&this.cursor&&(this.checkedDisk=!0,c=await this.cursor.get(),c&&Xo.isExpired(c.expiredAt)&&(await this.cursor.clear(),c=null)),r&&(null==c?void 0:c.reachedEndOfFeed)){const e=await this.fetch(),t=Date.parse(null!==(a=null===(n=e.paging)||void 0===n?void 0:n.expiredAt)&&void 0!==a?a:"");return!Number.isNaN(t)&&t!==c.expiredAt?(await this.persistCursor(e),e.posts.length>0&&(this.hasDeliveredPost=!0),e):Object.assign(Object.assign({},e),{posts:[],paging:{}})}const d=r&&c?c.cursor:t,l=await this.fetch(d);if(l.posts.length>0&&(this.hasDeliveredPost=!0),null===(s=l.paging)||void 0===s?void 0:s.next)await this.persistCursor(l);else if(this.hasDeliveredPost&&this.cursor){const e=Date.parse(null!==(i=null===(o=l.paging)||void 0===o?void 0:o.expiredAt)&&void 0!==i?i:"");Number.isNaN(e)||await this.cursor.markReachedEndOfFeed(e)}return l}async fetch(e){const t={limit:pe};e&&(t.token=e);try{const{data:e}=await this.http.get(we,{params:{options:t}});return e}catch(t){if(t instanceof Ve&&400300===t.code)throw new $m;if(t instanceof Ve&&400322===t.code&&void 0!==e){this.cursor&&await this.cursor.clear();const{data:e}=await this.http.get(we,{params:{options:{limit:pe}}});return e}throw t}}async persistCursor(e){var t,n;if(!this.cursor)return;const a=null===(t=e.paging)||void 0===t?void 0:t.next,s=null===(n=e.paging)||void 0===n?void 0:n.expiredAt;if(!a||!s)return;const o=Date.parse(s);Number.isNaN(o)||await this.cursor.set({cursor:a,expiredAt:o})}}class Qm extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.posts.map(Ze("post"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ze("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.parentPostId&&!a.data.includes(t.parentPostId)||(e!==om.OnPostDeleted&&e!==om.OnPostDeclined||(a.data=a.data.filter((e=>e!==t.postId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Vm=["forYouFeed","collection"];class Jm extends Rr{constructor(e){const t=`for-you-feed-${Ye().userId}`,n={};super(new Lm(n),t,Vm,e),this.queryStreamController=new Qm(n,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(Rm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Hm=Object.freeze({__proto__:null,queryGlobalFeed:am,getCustomRankingGlobalFeed:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCustomRankingGlobalFeed(tmpid: ${o}) > listen`);const i=new Pm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getCustomRankingGlobalFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getGlobalFeed:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getGlobalFeed(tmpid: ${o}) > listen`);const i=new km(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getGlobalFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getUserFeed:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getUserFeed(tmpid: ${o}) > listen`);const i=new qm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getUserFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunityFeed:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCommunityFeed(tmpid: ${o}) > listen`);const i=new Bm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getCommunityFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getForYouFeed:e=>{const{log:t,cache:n}=Ye();n||console.log(ve);const a=Date.now();t(`getForYouFeed(tmpid: ${a}) > listen`);const s=new Jm(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>rt(i))),()=>{t(`getForYouFeed(tmpid: ${a}) > dispose`),o.forEach((e=>e()))}},AmityForYouFeedDisabledError:$m});const Gm=async e=>{const t=Ye();t.log("post/getPostByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/posts/list",{params:{postIds:n}})).data}catch(t){throw e.forEach((e=>{Pe(null==t?void 0:t.code)&&_n("post",e)})),t}const s=Ln(a,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Fn(s,{cachedAt:o}),{data:s.posts.map(hd.post),cachedAt:o}};Gm.locally=e=>{var t;const n=Ye();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const a=e.map((e=>at(["post","get",e]))).filter(Boolean),s=a.map((({data:e})=>e)),o=null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==a?void 0:a.length)<e.length?void 0:{data:s.map(hd.post),cachedAt:o.cachedAt}};const zm=async(e,t=!1)=>{var n;const a=Ye(),s=await tl(e);if(await a.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await Hu(s.data.targetId),t=(null!==(n=nt(["communityUsers","get"]))&&void 0!==n?n:[]).filter((({key:t})=>"communityUsers"===t[0]&&("get"===t[1]&&("string"==typeof t[2]&&t[2].includes(e.data.communityId))))).map((({data:e})=>e));Nt("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const o=Object.assign(Object.assign({},s.data),{isDeleted:!0});return t?setTimeout((()=>{_n("post",e)}),0):it(["post","get",e],{isDeleted:!0}),Nt("local.post.deleted",{posts:[o],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),hd.post(o)};class Ym extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a,matchingOnlyParentPost:s,untilAt:o}=e,i=Bn(e,["limit","includeDeleted","matchingOnlyParentPost","untilAt"]),{dataTypes:r}=i,c={type:i.sortBy||e.limit?"pagination":void 0},d=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{limit:n}),{data:l}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},i),{isDeleted:oa(a),matchingOnlyParentPost:null!=s?s:!(null==r?void 0:r.length),options:d})});return l}}class Wm extends Sr{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?Rt(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;let o=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e=this.query.sortBy||"lastCreated",t=o.filter((t=>!Pt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)st(this.cacheKey,{data:o.map(Ze("post"))});else{const e=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Ze("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===om.OnPostCreated||e===om.OnPostApproved)){const e=this.query.sortBy||"lastCreated";if(Pt(t.createdAt,this.validatedUntilAt,e))return}if(t.parentPostId&&t.isDeleted){const e=null===(a=at(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),st(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==om.OnPostCreated&&e!==om.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),st(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}class Xm extends Rr{constructor(e,t){const n=R.default(e),a=["posts","collection",n];super(new Ym(e),n,a,t),this.query=e,this.queryStreamController=new Wm(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){const e=this.queryStreamController.subscribeRTE(Fm(this.cacheKey));if(this.query.excludeBlockUserPosts){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Yo(t),Wo(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);if(!this.shouldNotify(i)&&"event"===e)return;const r=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:r,loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=ct(n,"isDeleted",!1)),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),"community"===this.query.targetType&&this.query.feedType&&(n=ht(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=gt(n,this.query.dataTypes)),this.query.untilAt){const e=Rt(this.query.untilAt),t=this.query.sortBy||"lastCreated";n=n.filter((n=>!Pt(n.createdAt,e,t)))}if(this.query.excludeBlockUserPosts&&(n=vt(n)),"firstCreated"===this.query.sortBy)n=n.sort(Ct);else n=n.sort(St);return n}}class Zm extends Cr{async getRequest(e,t){const n=Bn(e,["limit"]),{communityId:a,placement:s}=n,o=Bn(n,["communityId","placement"]),i=s?`/api/v1/pinned-posts/communities/${a}/${s}`:`/api/v1/pinned-posts/communities/${a}`,{data:r}=await this.http.get(i,{params:Object.assign({},o)});return r}}class eg extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(pa):[]});Fn(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.pins.map(Ze("pin"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Ze("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===om.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class tg extends Rr{constructor(e,t){const n=R.default(e),a=["pinnedPosts","collection",n];super(new Zm(e),n,a,t),this.query=e,this.queryStreamController=new eg(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(Km({cacheKey:this.cacheKey,resolveId:e=>`${this.query.placement}#${e}`}))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;let i=(null!==(s=o.data.map((e=>at(["pin","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.pinnedPost);i=this.applyFilter(i),(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>St({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class ng extends Cr{async getRequest(e,t){const n=Bn(e,["limit"]),{data:a}=await this.http.get("/api/v1/pinned-posts/global",{params:Object.assign({},n)});return a}}class ag extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(pa)});Fn(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.pins.map(Ze("pin"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Ze("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===om.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class sg extends Rr{constructor(e,t){const n=R.default(e),a=["pinnedPosts","collection",n];super(new ng(e),n,a,t),this.query=e,this.queryStreamController=new ag(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:wm,action:om.OnPostDeleted},{fn:pl,action:om.OnPostDeleted},...Km({cacheKey:this.cacheKey,resolveId:e=>`global#${e}`})])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["pin","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.pinnedPost);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}}class og extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(e,["limit"]),s={type:e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:n}),{data:i}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},a),{options:o})});return i}}function ig(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function rg(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class cg extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:ig(e)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...ig(e)])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(a=at(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),st(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==om.OnPostCreated&&e!==om.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),st(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class dg extends Rr{constructor(e,t){const n=Object.assign(Object.assign({},e),{matchingOnlyParentPost:null==e.matchingOnlyParentPost||e.matchingOnlyParentPost,dataTypes:null==e.dataTypes?["text","image"]:e.dataTypes}),a=R.default(n),s=["posts","collection",a];super(new og(n),a,s,t),this.query=n,this.queryStreamController=new cg(this.query,this.cacheKey,this.notifyChange.bind(this),el),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:gl,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Pd((e=>Ol((async t=>{const n=at(this.cacheKey);rg(null==n?void 0:n.data).includes(t.referenceId)||(await tl(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated},{fn:Pd((e=>Al((async t=>{const n=at(this.cacheKey);rg(null==n?void 0:n.data).includes(t.referenceId)||(await tl(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>{const[t,n]=e.split(":");return{postId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({postId:e})=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.dataTypes&&this.query.dataTypes.length>0&&(t=gt(t,this.query.dataTypes)),t}}class lg extends Cr{async getRequest(e,t){const{limit:n=ge,matchingOnlyParentPost:a,hashtags:s,dataTypes:o,targetType:i="all"}=e,r=Bn(e,["limit","matchingOnlyParentPost","hashtags","dataTypes","targetType"]),c={type:r.sortBy||e.limit?"pagination":void 0},d=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{limit:n}),{data:l}=await this.http.get("/api/v1/search/posts",{params:Object.assign(Object.assign({},r),{hashtags:s,dataTypes:o,targetType:i,matchingOnlyParentPost:null!=a?a:!(null==o?void 0:o.length),options:d})});return l}}class ug extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.posts.map(Ze("post"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ze("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(a=at(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),st(["post","get",e.postId],e)}e===om.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==om.OnPostCreated&&e!==om.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),st(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class hg extends Rr{constructor(e,t){const n=R.default(e),a=["posts","collection",n];super(new lg(e),n,a,t),this.query=e,this.queryStreamController=new ug(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ml,action:om.OnPostCreated},{fn:gl,action:om.OnPostUpdated},{fn:Tm,action:om.OnPostUpdated},{fn:pl,action:om.OnPostDeleted},{fn:fl,action:om.OnPostFlagged},{fn:bl,action:om.OnPostUnflagged},{fn:yl,action:om.OnPostApproved},{fn:vl,action:om.OnPostDeclined},{fn:Il,action:om.OnPostReactionAdded},{fn:Cl,action:om.OnPostReactionRemoved},{fn:Sm,action:om.OnPostReactionAdded},{fn:Om,action:om.OnPostReactionRemoved},{fn:wm,action:om.OnPostDeleted},{fn:Pd((e=>Ol((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Mm(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated},{fn:Pd((e=>Al((async t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Mm(t.referenceId),e(t))}))),"referenceId","post"),action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if((null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=gt(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(Ct);else n=n.sort(St);return n}}class mg extends Ar{async getRequest(e){const{limit:t=100}=e,{data:n}=await this.http.get("/api/v1/rooms/lives",{params:{targetTypes:["all"],options:{limit:t,sortBy:"lastCreated"}}});return n}}class gg extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:_m(e.rooms,e.posts)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,..._m(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&st(this.cacheKey,Object.assign(Object.assign({},n),{data:n.data.filter((t=>e.referenceId!==t))})),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const pg=e=>{const t=Ye();return xt(t,"room/onRoomStartBroadcasting","room.startBroadcasting",(t=>{Fn(t),e(t.rooms[0])}))},yg=e=>{const t=Ye();return xt(t,"room/onRoomWaitingReconnect","room.waitingReconnect",(t=>{Fn(t),e(t.rooms[0])}))},vg=e=>{const t=Ye();return xt(t,"room/onRoomEndBroadcasting","room.endBroadcasting",(t=>{Fn(t),e(t.rooms[0])}))},fg=e=>{const t=Ye();return xt(t,"room/onRoomRecordedAvailable","room.recordedAvailable",(t=>{Fn(t),e(t.rooms[0])}))},bg=e=>{const t=Ye();return xt(t,"room/onRoomCoHostInvited","room.didCohostInvite",(t=>{const n=nc(t);Fn(n),e(n.invitations)}))},Ig=async e=>{const t=Ye();let n;t.log("room/getRoomById",e),ea("room",e);try{n=(await t.http.get(`/api/v1/rooms/${e}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("room",e),t}const a=t.cache&&Date.now();return t.cache&&Fn(n,{cachedAt:a}),{data:n.rooms[0],cachedAt:a}};Ig.locally=e=>{const t=Ye();t.log("room/getRoomById.locally",e),ea("room",e);const n=t.cache&&Date.now(),a=at(["room","get",e]);if(a)return{data:a.data,cachedAt:n}};const Cg=e=>{const t=Ye();return xt(t,"room/onRoomCoHostInviteAccepted","room.didCohostInviteAccept",(async t=>{var n;const a=nc(t);await Ig(null===(n=a.invitations)||void 0===n?void 0:n[0].targetId),Fn(a),e(a.invitations[0])}))},wg=e=>{const t=Ye();return xt(t,"room/onRoomCoHostInviteRejected","room.didCohostInviteReject",(t=>{const n=nc(t);Fn(n),e(n.invitations)}))},Sg=e=>{const t=Ye();return xt(t,"room/onRoomCoHostInviteCanceled","room.didCohostInviteCancel",(t=>{const n=nc(t);Fn(n),e(n.invitations)}))},Og=e=>{const t=Ye();return xt(t,"room/onRoomParticipantJoined","room.participantJoined",(t=>{const{rooms:n,users:a}=t;Fn({rooms:n,users:a}),e({room:qc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Tg=e=>{const t=Ye();return xt(t,"room/onRoomParticipantLeft","room.participantLeft",(t=>{var n;const{rooms:a,users:s}=t;Fn({rooms:a,users:s});const o=t.eventActor.userInternalId;e({room:qc(a[0]),actorInternalId:o,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===o)))||void 0===n?void 0:n.userId})}))},Ag=e=>{const t=Ye();return xt(t,"room/onRoomParticipantStageJoined","room.participantStageJoined",(t=>{const{rooms:n,users:a}=t;Fn({rooms:n,users:a}),e({room:qc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Rg=e=>{const t=Ye();return xt(t,"room/onRoomTerminated","room.terminated",(t=>{Fn(t),e(t.rooms[0])}))},Pg=e=>{const t=Ye();return xt(t,"room/onRoomDidUpdate","local.room.didUpdate",(t=>{Fn(t),e(t.rooms[0])}))},Dg=e=>{const t=Ye();return xt(t,"room/onRoomParticipantRemoved","room.participantRemoved",(t=>{var n;const{rooms:a,users:s}=t;Fn({rooms:a,users:s});const o=t.eventActor.userInternalId;e({room:qc(a[0]),actorInternalId:o,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===o)))||void 0===n?void 0:n.userId})}))},Ug=e=>{const t=Ye();return xt(t,"room/onLocalRoomDidUpdate","room.didUpdate",(t=>{Fn(t),e(t.rooms[0])}))},kg=e=>{const t=Ye();return xt(t,"room/onRoomParticipantRemoved","local.room.participantRemoved",(t=>{Fn(t),e(t.rooms[0])}))};var jg;!function(e){e.OnRoomCreated="OnRoomCreated",e.OnRoomUpdated="OnRoomUpdated",e.OnRoomDeleted="OnRoomDeleted",e.OnRoomStartBroadcasting="OnRoomStartBroadcasting",e.OnRoomEndBroadcasting="OnRoomEndBroadcasting",e.OnRoomParticipantJoined="OnRoomParticipantJoined",e.OnRoomParticipantLeft="OnRoomParticipantLeft",e.OnRoomDidUpdate="OnRoomDidUpdate"}(jg||(jg={}));const Eg=e=>t=>e((e=>{t(e.room)}));class Mg extends Cr{async getRequest(e,t){const{limit:n=ge,includeDeleted:a}=e,s=Bn(e,["limit","includeDeleted"]),o={type:s.sortBy||e.limit?"pagination":void 0},i=t?Object.assign(Object.assign({},o),{token:t}):Object.assign(Object.assign({},o),{limit:n}),{data:r}=await this.http.get("/api/v1/rooms",{params:Object.assign(Object.assign({},s),{isDeleted:oa(a),options:i})});return r}}class qg extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.rooms.map(Ze("room"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.rooms.map(Ze("room"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===jg.OnRoomDeleted&&(a.data=a.data.filter((e=>e!==t._id))),e===jg.OnRoomCreated&&(a.data=[...new Set([t._id,...a.data])]),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class xg extends Rr{constructor(e,t){const n=R.default(e),a=["rooms","collection",n];super(new Mg(e),n,a,t),this.query=e,this.queryStreamController=new qg(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:pg,action:jg.OnRoomStartBroadcasting},{fn:vg,action:jg.OnRoomEndBroadcasting},{fn:fg,action:jg.OnRoomUpdated},{fn:yg,action:jg.OnRoomUpdated},{fn:Rg,action:jg.OnRoomUpdated},{fn:Eg(Og),action:jg.OnRoomUpdated},{fn:Eg(Tg),action:jg.OnRoomUpdated},{fn:Eg(Dg),action:jg.OnRoomUpdated},{fn:kg,action:jg.OnRoomUpdated},{fn:Eg(Ag),action:jg.OnRoomUpdated},{fn:Pd(Cg,"targetId","room"),action:jg.OnRoomUpdated},{fn:Pg,action:jg.OnRoomDidUpdate},{fn:Ug,action:jg.OnRoomDidUpdate}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["room","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(qc);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=ct(t,"isDeleted",!1)),this.query.statuses&&this.query.statuses.length>0&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.type&&(t=ct(t,"type",this.query.type)),"firstCreated"===this.query.sortBy)t=t.sort(Ct);else t=t.sort(St);return t}}var Ng=Object.freeze({__proto__:null,createRoom:async e=>{const t=Ye();t.log("room/createRoom",e);const{data:n}=await t.http.post("/api/v1/rooms",e);Nt("local.room.created",n);const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{rooms:s}=n;return{data:qc(s[0]),cachedAt:a}},updateRoom:async(e,t)=>{const n=Ye();n.log("room/updateRoom",{roomId:e,bundle:t});const{data:a}=await n.http.put(`/api/v1/rooms/${e}`,t);Nt("local.room.updated",a);const s=n.cache&&Date.now();n.cache&&Fn(a,{cachedAt:s});const{rooms:o}=a;return{data:qc(o[0]),cachedAt:s}},deleteRoom:async e=>{const t=Ye();t.log("room/deleteRoom",{roomId:e}),await t.http.delete(`/api/v1/rooms/${e}`),Nt("local.room.deleted",{rooms:[{_id:e}]})},stopRoom:async e=>{const t=Ye();t.log("room/stopRoom",{roomId:e});const{data:n}=await t.http.post(`/api/v1/rooms/${e}/stop`);Nt("local.room.stopped",n);const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{rooms:s}=n;return{data:s[0],cachedAt:a}},getBroadcasterData:async e=>{const t=Ye();t.log("room/getBroadcasterData",{roomId:e});const{data:n}=await t.http.get(`/api/v1/rooms/${e}/token`);return n},getRecordedUrl:async e=>{const t=Ye();t.log("room/getRecordedUrl",{roomId:e});const{data:n}=await t.http.get(`/api/v1/rooms/${e}/recorded`);return n},removeParticipant:async(e,t)=>{const n=Ye();n.log("room/removeParticipant",{roomId:e,participantUserId:t}),await n.http.delete(`/api/v1/rooms/${e}/participants/${t}`),Nt("local.room.participantRemoved",{rooms:[{_id:e}],users:[{_id:t}]})},leaveRoom:async e=>{const t=Ye();t.log("room/leaveRoom",{roomId:e}),await t.http.post(`/api/v1/rooms/${e}/leave`),Nt("local.room.left",{rooms:[{_id:e}]})},AmityRoomAnalytics:Mc,WatchSessionStorage:Sc,getWatchSessionStorage:Tc,syncWatchSessions:jc,updateCohostPermission:async(e,t,n)=>{const a=Ye();a.log("room/updatedCoHostPermission",{roomId:e,cohostId:t,canManageProductTags:n});const{data:s}=await a.http.put(`/api/v1/rooms/${e}/participants/${t}`,{canManageProductTags:n});Nt("local.room.didUpdate",s);const o=a.cache&&Date.now();a.cache&&Fn(s,{cachedAt:o});const{rooms:i}=s;return{data:qc(i[0]),cachedAt:o}},onRoomStartBroadcasting:pg,onRoomWaitingReconnect:yg,onRoomEndBroadcasting:vg,onRoomRecordedAvailable:fg,onRoomCoHostInvited:bg,onRoomCoHostInviteAccepted:Cg,onRoomCoHostInviteRejected:wg,onRoomCoHostInviteCanceled:Sg,onRoomParticipantJoined:Og,onRoomParticipantLeft:Tg,onRoomParticipantStageLeft:e=>{const t=Ye();return xt(t,"room/onRoomParticipantStageLeft","room.participantStageLeft",(t=>{const{rooms:n,users:a}=t;Fn({rooms:n,users:a}),e({room:qc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},onRoomParticipantStageJoined:Ag,onRoomTerminated:Rg,onRoomDidUpdate:Pg,onRoomCreated:e=>{const t=Ye();return xt(t,"room/onRoomCreated","local.room.created",(t=>{Fn(t),e(t.rooms[0])}))},onRoomUpdated:e=>{const t=Ye();return xt(t,"room/onRoomUpdated","local.room.updated",(t=>{Fn(t),e(t.rooms[0])}))},onRoomDeleted:e=>{const t=Ye();return xt(t,"room/onRoomDeleted","local.room.deleted",(t=>{Fn(t),e(t.rooms[0])}))},onRoomStopped:e=>{const t=Ye();return xt(t,"room/onRoomStopped","local.room.stopped",(t=>{Fn(t),e(t.rooms[0])}))},onRoomParticipantRemoved:Dg,onRoomLeft:e=>{const t=Ye();return xt(t,"room/onRoomLeft","local.room.left",(t=>{Fn(t),e(t.rooms[0])}))},onLocalRoomDidUpdate:Ug,getRoom:(e,t)=>qr(e,t,"_id",Ig,[vg,pg,yg,Rg,fg,Eg(Og),Eg(Tg),Eg(Dg),kg,Eg(Ag),Pd(Cg,"targetId","room"),Pg,Ug],{callbackDataSelector:e=>e?hd.room(e):e}),getRooms:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getRooms(tmpid: ${o}) > listen`);const i=new xg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getRooms(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});class Kg extends Rr{constructor(e){const t={limit:100},n=R.default(t),a=["liveRoomPosts","collection",n];super(new mg(t),n,a,e),this.query=t,this.queryStreamController=new gg(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:vg,action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){return e}}class Fg extends Ar{async getRequest(e){const{limit:t=100,communityIds:n}=e,{data:a}=await this.http.get("/api/v1/rooms/lives",{params:{targetTypes:["community"],targetIds:n,options:{limit:t,sortBy:"lastCreated"}}});return a}}class _g extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:_m(e.rooms,e.posts)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,..._m(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&st(this.cacheKey,Object.assign(Object.assign({},n),{data:n.data.filter((t=>e.referenceId!==t))})),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Bg extends Rr{constructor(e,t){const n=R.default(e),a=["communityLiveRoomPosts","collection",n];super(new Fg(e),n,a,t),this.query=e,this.queryStreamController=new _g(this.query,this.cacheKey,this.notifyChange.bind(this),Zd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:vg,action:om.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["post","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){return e}}var $g=Object.freeze({__proto__:null,getPostByIds:Gm,createPost:async e=>{const t=Ye();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{attachments:n,attachmentProductTags:a}=e,s=Bn(e,["attachments","attachmentProductTags"]),o=n&&n.length>0&&e.attachmentProductTags?n.map((t=>{var n;const a=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return a?Object.assign(Object.assign({},t),{productTags:a}):t})):n,{data:i}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:o}));Nt("post.created",i);const r=Zd(i),c=t.cache&&Date.now();t.cache&&Fn(r,{cachedAt:c});const{posts:d}=r;return{data:hd.post(d[0]),cachedAt:c}},editPost:async(e,t)=>{const n=Ye();n.log("user/editPost",t);const{attachments:a}=t,s=a&&a.length>0&&t.attachmentProductTags?a.map((e=>{var n;const a=null===(n=t.attachmentProductTags)||void 0===n?void 0:n.get(e.fileId);return a?Object.assign(Object.assign({},e),{productTags:a}):e})):a,{data:o}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,Object.assign(Object.assign({},t),{attachments:s})),i=Ln(o,"communityUsers"),r=n.cache&&Date.now();n.cache&&Fn(i,{cachedAt:r}),Nt("local.post.updated",i);const{posts:c}=i;return{data:hd.post(c.find((t=>t.postId===e))),cachedAt:r}},deletePost:zm,softDeletePost:async e=>{Ye().log("post/softDeletePost",e);const t=await zm(e,!1);return hd.post(t)},hardDeletePost:async e=>{Ye().log("post/hardDeletePost",e);const t=await zm(e,!0);return hd.post(t)},approvePost:async e=>{const t=Ye();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);Nt("post.approved",n),"community"===n.posts[0].targetType&&Nt("community.updated",n);const a=Ln(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:hd.post(a.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=Ye();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&Nt("community.updated",n),Nt("post.declined",n);const a=Ln(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:hd.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async(t,n)=>{const a=Ye();a.log("post/flagPost",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),o={reason:n&&s?n:e.ContentFlagReasonEnum.Others,detail:n&&!s?n:""},{data:i}=await a.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`,o);return a.cache&&Fn(Ln(i,"communityUsers")),Nt("post.flagged",i),!!i},unflagPost:async e=>{const t=Ye();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Fn(Ln(n,"communityUsers")),Nt("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=Ye();t.log("post/isPostFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return n},createClipPost:async e=>{const t=Ye();t.log("post/createPost",e);const{attachments:n,attachmentProductTags:a}=e,s=Bn(e,["attachments","attachmentProductTags"]),o=n&&n.length>0&&e.attachmentProductTags?n.map((t=>{var n;const a=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return a?Object.assign(Object.assign({},t),{productTags:a}):t})):n,{data:i}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:o}));Nt("post.created",i);const r=Ln(i,"communityUsers"),c=t.cache&&Date.now();t.cache&&Fn(r,{cachedAt:c});const{posts:d}=r;return{data:hd.post(d[0]),cachedAt:c}},createAudioPost:async e=>{const t=Ye();t.log("post/createAudioPost",e);const{attachments:n,attachmentProductTags:a}=e,s=Bn(e,["attachments","attachmentProductTags"]),o=n&&n.length>0&&a?n.map((e=>{const t=null==a?void 0:a.get(e.fileId);return t?Object.assign(Object.assign({},e),{productTags:t}):e})):n,{data:i}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:o}));Nt("post.created",i);const r=Zd(i),c=t.cache&&Date.now();return t.cache&&Fn(r,{cachedAt:c}),{data:Fc(null==r?void 0:r.posts[0]),cachedAt:c}},createMixedMediaPost:async e=>{var t;const n=Ye();n.log("post/createMixedMediaPost",e);const{attachments:a,attachmentProductTags:s}=e,o=Bn(e,["attachments","attachmentProductTags"]),i=a&&a.length>0&&e.attachmentProductTags?a.map((t=>{var n;const a=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return a?Object.assign(Object.assign({},t),{productTags:a}):t})):a,{data:r}=await n.http.post("/api/v4/posts",Object.assign(Object.assign({},o),{attachments:i}));Nt("post.created",r);const c=Zd(r),d=n.cache&&Date.now();return n.cache&&Fn(c,{cachedAt:d}),{data:Fc(null===(t=null==c?void 0:c.posts)||void 0===t?void 0:t[0]),cachedAt:d}},createRoomPost:async e=>{const t=Ye();t.log("post/createRoomPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"room"}));Nt("post.created",n);const a=Zd(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{posts:o}=a;return{data:hd.post(o[0]),cachedAt:s}},createEventPost:async e=>{const t=Ye();t.log("post/createEventPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"event"}));Nt("post.created",n);const a=Zd(n),s=t.cache&&Date.now();t.cache&&Fn(a,{cachedAt:s});const{posts:o}=a;return{data:hd.post(o[0]),cachedAt:s}},pinProduct:async(e,t)=>{const n=Ye();n.log("post/pinProduct",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:t}),s=Zd(a),o=n.cache&&Date.now();return n.cache&&Fn(a,{cachedAt:o}),Nt("local.post.updated",a),{data:Fc(null==s?void 0:s.posts[0]),cachedAt:o}},unpinProduct:async e=>{const t=Ye();t.log("post/unpinProduct",e);const{data:n}=await t.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:null}),a=Zd(n),s=t.cache&&Date.now();return t.cache&&Fn(n,{cachedAt:s}),Nt("local.post.updated",n),{data:Fc(null==a?void 0:a.posts[0]),cachedAt:s}},updateProductTags:async(e,t)=>{const n=Ye();n.log("post/updateProductTags",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{productTags:t}),s=Zd(a),o=n.cache&&Date.now();return n.cache&&Fn(a,{cachedAt:o}),Nt("local.post.updated",a),{data:Fc(null==s?void 0:s.posts[0]),cachedAt:o}},onPostCreated:ml,onPostUpdated:gl,onPostDeleted:pl,onPostApproved:yl,onPostDeclined:vl,onPostFlagged:fl,onPostUnflagged:bl,onPostReactionAdded:Il,onPostReactionRemoved:Cl,getPost:(e,t)=>qr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hd.post(e.data):n}))}),"postId",tl,[yl,vl,Sm,Om,t=>pl((n=>{var a;let s=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(a=at(["post","get",n.parentPostId]))||void 0===a?void 0:a.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),st(["post","get",e.postId],e),s=e)}t(s)})),fl,e=>Il((t=>{e(t)})),e=>Cl((t=>{e(t)})),bl,gl,Tm,wm,Pd((t=>Ol((async n=>{n.referenceId===e&&(await tl(e),t(n))}))),"referenceId","post"),Pd((t=>Al((async n=>{n.referenceId===e&&(await tl(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getPosts(tmpid: ${o}) > listen`);const i=new Xm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getPinnedPosts(tmpid: ${o}) > listen`);const i=new tg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getPinnedPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:a,cache:s}=Ye(),o=Date.now();a(`getGlobalPinnedPosts(tmpid: ${o}) > listen`);const i=new sg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getGlobalPinnedPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`semanticSearchPosts(tmpid: ${o}) > listen`);const i=new dg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`semanticSearchPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchPostsByHashtag:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`searchPostsByHashtag(tmpid: ${o}) > listen`);const i=new hg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`searchPostsByHashtag(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getLiveRoomPosts:e=>{const{log:t,cache:n}=Ye();n||console.log(ve);const a=Date.now();t(`getLiveRoomPosts(tmpid: ${a}) > listen`);const s=new Kg(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>rt(i))),()=>{t(`getLiveRoomPosts(tmpid: ${a}) > dispose`),o.forEach((e=>e()))}},getCommunityLiveRoomPosts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getCommunityLiveRoomPosts(tmpid: ${o}) > listen`);const i=new Bg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getCommunityLiveRoomPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});const Lg=async e=>{const t=Ye();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:a}};Lg.locally=e=>{const t=Ye();if(t.log("stream/getStream",e),!t.cache)return;const n=at(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Qg=e=>{const t=Ye();return xt(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Fn(t),e(t.videoStreamings[0])}))},Vg=e=>{const t=Ye();return xt(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Fn(t),e(t.videoStreamings[0])}))},Jg=e=>{const t=Ye();return xt(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Fn(t),e(t.videoStreamings[0])}))},Hg=e=>{const t=Ye();return xt(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Fn(t),e(t.videoStreamings[0])}))},Gg=e=>{const t=Ye();return xt(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Fn(t),e(t.videoStreamings[0])}))},zg=(e,t)=>qr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hd.stream(e.data):n}))}),"streamId",Lg,[Jg,Qg,Vg,Hg,Gg,iu]);zg.locally=e=>{const t=Ye();if(t.log("stream/getStreamById",e),!t.cache)return;const n=at(["stream","get",e]);return n?{data:hd.stream(n.data),cachedAt:n.cachedAt}:void 0};const Yg=async e=>{const t=Ye();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:a,limit:s}=n,o=Bn(n,["page","limit"]),i=a?{token:a}:s?{limit:s}:void 0,{data:r}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},o),{options:i})}),{paging:c,results:d}=r,{videoStreamings:l}=d,u=t.cache&&Date.now();return t.cache&&Fn(d,{cachedAt:u}),{data:l,cachedAt:u,paging:c}};var Wg=Object.freeze({__proto__:null,createStream:async e=>{const t=Ye();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:hd.stream(s[0]),cachedAt:a}},updateStream:async(e,t)=>{const n=Ye();n.log("stream/updateStream",e,t);const{data:a}=await n.http.put(`/api/v3/video-streaming/${e}`,t),s=n.cache&&Date.now();n.cache&&Fn(a,{cachedAt:s});const{videoStreamings:o}=a;return{data:hd.stream(o.find((t=>t.streamId===e))),cachedAt:s}},deleteStream:async e=>{const t=Ye();t.log("stream/deleteStream",e);const n=await Lg(e),{data:a}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:s}=a,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return it(["stream","get",e],o),s},disposeStream:async e=>{const t=Ye();t.log("stream/disposeStream",e);const{data:n}=await t.http.delete(`/api/v3/video-streaming/${e}/streaming-url`),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:a}},editStream:async(e,t)=>{const n=Ye();n.log("stream/updateStream",e,t);const{data:a}=await n.http.put(`/api/v3/video-streaming/${e}`,t),s=n.cache&&Date.now();n.cache&&Fn(a,{cachedAt:s});const{videoStreamings:o}=a;return{data:hd.stream(o.find((t=>t.streamId===e))),cachedAt:s}},onStreamStarted:Qg,onStreamStopped:Vg,onStreamRecorded:Jg,onStreamFlagged:Hg,onStreamTerminated:Gg,onStreamViewerBanned:iu,onStreamViewerUnbanned:e=>{const t=Ye();return xt(t,"stream/onStreamViewerDidUnban","video-streaming.viewerDidUnban",(async t=>{var n;const{list:a}=t;await Promise.all(a.map((({streamId:e})=>Lg(e))));const s=null===(n=at(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))},getStreamById:zg,getStreams:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getStreams(tmpid: ${o}) > listen`);const{limit:i}=e,r=Bn(e,["limit"]),c=null!=i?i:ge,{policy:d=ye}=null!=n?n:{},l=[],u=["streams","collection",e],h=t=>{let n=ct(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?St:Ct),n},m=(e,n=!1)=>{var a,s;const o=null!==(a=e.data.map((e=>at(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==a?a:[];t({onNextPage:p,data:n?h(o):o,hasNextPage:!!(null===(s=e.params)||void 0===s?void 0:s.page),loading:e.loading,error:e.error})},g=e=>e=>{var t;const n=null===(t=at(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],st(u,n),m(n,!0))},p=(e=!1)=>{var t,n;const a=null===(t=at(u))||void 0===t?void 0:t.data,s=null!==(n=null==a?void 0:a.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==a?void 0:a.params.page))return;const o=_e(Yg,Object.assign(Object.assign({},r),{limit:e?c:void 0,page:e||null==a?void 0:a.params.page}));$e(o,(({data:e,error:t,loading:n,paging:a})=>{const o={loading:n,error:t,params:{page:null==a?void 0:a.next},data:s};e&&(o.data=[...new Set([...s,...e.map(Ze("stream"))])]),st(u,o),m(o)}),Be(d))};return l.push(Jg(g()),Qg(g()),Vg(g())),p(!0),()=>{a(`getStreams(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}}});const Xg=async()=>{const e=Ye();e.log("presence/getPresenceSetting");const{data:t}=await e.http.get("/api/v1/presence/settings");return st(["get","presenceSetting"],t),t};class Zg{constructor(e){this.isEnabled=!1,this.config={heartbeatInterval:3e4},this.roomId=e,this.initializeConfig().catch((e=>{console.error("Failed to initialize RoomPresenceSyncEngine config in constructor:",e)}))}async initializeConfig(){try{const e=await Zg.getPresenceSettingWithRetry();e?this.config={heartbeatInterval:60*(e.network.heartbeatInterval||5)*1e3}:this.config.heartbeatInterval=3e5}catch(e){console.error("Failed to initialize RoomPresenceSyncEngine config:",e),this.config.heartbeatInterval=3e5}}static async getPresenceSettingWithRetry(e=5){for(let t=0;t<e;t+=1)try{return await Xg()}catch(n){if(t>=e-1)return console.error(`Failed to get presence setting after ${e} attempts:`,n),null;const a=2e4+5e3*Math.random();console.warn(`Failed to get presence setting (attempt ${t+1}/${e}), retrying in ${Math.round(a/1e3)}s:`,n),await new Promise((e=>{setTimeout(e,a)}))}return null}start(){this.isEnabled||(this.isEnabled=!0,this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>{this.sendHeartbeat()}),this.config.heartbeatInterval))}stop(){this.isEnabled=!1,this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async sendHeartbeat(){try{const e=Ye();await e.http.post(`/api/v1/presence/rooms/${this.roomId}/heartbeat`)}catch(e){console.error(`Heartbeat failed for room ${this.roomId}:`,e)}}getRoomId(){return this.roomId}isActive(){return this.isEnabled}destroy(){this.stop()}onSessionDestroyed(){this.destroy()}onTokenExpired(){this.stop()}}const ep=new Map,tp=e=>{let t=ep.get(e);return t||(t=new Zg(e),ep.set(e,t)),t};var np=Object.freeze({__proto__:null,getRoomOnlineUsers:async e=>{var t,n,a;const s=Ye();s.log("room/getWatchingUsers",{roomId:e});const{data:o}=await s.http.get(`/api/v1/presence/rooms/${e}/users`),i=null!==(t=null==o?void 0:o.viewers.map((e=>e.userId)))&&void 0!==t?t:[],r=[];for(let e=0;e<i.length;e+=100)r.push(i.slice(e,e+100));const c=await Promise.all(r.map((e=>md(e)))),d=[];return c.forEach((e=>{e.data&&d.push(...e.data)})),{data:d,cachedAt:null!==(a=null===(n=c[0])||void 0===n?void 0:n.cachedAt)&&void 0!==a?a:Date.now()}},getRoomUserCount:async e=>{const t=Ye();t.log("roomPresence/getRoomUserCount",{roomId:e});const{data:n}=await t.http.get(`/api/v1/presence/rooms/${e}/users/count`);return st(["get","watchingCount",e],n),n},startHeartbeat:e=>{tp(e).start()},stopHeartbeat:e=>{tp(e).stop(),(e=>{const t=ep.get(e);t&&(t.destroy(),ep.delete(e))})(e)}});const ap=async e=>{const t=Ye();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{polls:s}=n,o=s.find((t=>t.pollId===e));return{data:xc(o),cachedAt:a}};ap.locally=e=>{const t=Ye();if(t.log("poll/getPoll",e),!t.cache)return;const n=at(["poll","get",e]);return n?{data:xc(n.data),cachedAt:n.cachedAt}:void 0};const sp=e=>{const t=Ye();return xt(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Fn(n),e(n.polls[0])}))},op=e=>{const t=Ye();return xt(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Fn(n),e(n.polls[0])}))};var ip=Object.freeze({__proto__:null,createPoll:async e=>{const t=Ye();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{polls:s}=n;return{data:xc(s[0]),cachedAt:a}},closePoll:async e=>{const t=Ye();t.log("user/closePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}`,{status:"closed"}),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a}),Nt("poll.updated",n);const{polls:s}=n,o=s.find((t=>t.pollId===e));return{data:xc(o),cachedAt:a}},deletePoll:async e=>{const t=Ye();t.log("poll/deletePoll",e);const n=await ap(e),{data:a}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=a,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return it(["poll","get",e],o),Nt("poll.deleted",{polls:[o],users:[]}),s},votePoll:async(e,t)=>{const n=Ye();n.log("user/votePoll",e);const{data:a}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),s=n.cache&&Date.now();n.cache&&Fn(a,{cachedAt:s});const{polls:o}=a,i=o.find((t=>t.pollId===e));return Nt("poll.updated",a),{data:xc(i),cachedAt:s}},unvotePoll:async e=>{const t=Ye();t.log("user/unvotePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:[]}),a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a}),Nt("poll.updated",n)},onPollUpdated:sp,onPollDeleted:op,getPoll:(e,t)=>qr(e,t,"pollId",ap,[sp,op])});class rp{constructor(){this._unsyncedData=[],this._syncBuffer=[],this._activeStreams=[],this._startInterval(),this._syncInterval=null}registerStream(e){this._activeStreams.push(e)}getActiveStreams(){return this._activeStreams}unregisterStream(e){this._activeStreams=this._activeStreams.filter((t=>t!==e))}updateUsage(e){this._unsyncedData.push(e)}bufferCurrentUsage(){const e=this._unsyncedData;return this._unsyncedData=[],e}dispose(){this._syncInterval&&clearInterval(this._syncInterval)}_startInterval(){this._syncInterval=setInterval((()=>{!async function({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:a}){const s=e();if(s.length)try{const n=(new Date).toISOString(),o=await kc({timestamp:n,streams:s});if(!o||!o.signature)throw new Error("Signature is undefined");const i={signature:o.signature,nonceStr:o.nonceStr,timestamp:n,streams:s},r=Ye();await r.http.post("/api/v3/user-event/video-streaming",i),t().length||e().length||a()}catch(e){return s.forEach((e=>n(e))),!1}}({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let cp=null;class dp{constructor(e,t,n){this._SDKUnsubscribers=[],this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=cp||(cp=new rp,cp),this._usageCollector.registerStream(e.id),this._sessionId=String(T.default.v4()),this._controller=new AbortController,this._observer=new MutationObserver((t=>{t.forEach((t=>{t.removedNodes.forEach((t=>{t===e&&(this._unregisterEvents(),this._SDKUnsubscribers.forEach((e=>null==e?void 0:e())))}))}))})),this._SDKUnsubscribers.push(iu((e=>{e.watcherUrl||(this.player.pause(),this.player.removeAttribute("src"),this.player.load(),this.player.remove())})))}_resetStartTime(){this._startTime=Date.now()}_shouldUpdateCollector(){return!!this._startTime&&Date.now()-this._startTime>2e4}_sendUsageToCollector(){if(!this._startTime)return;const e=Date.now(),t=e-this._startTime,n=Math.round(t/1e3);n&&this._usageCollector.updateUsage({streamId:this.player.id,sessionId:this._sessionId,startTime:this._startTime?new Date(this._startTime).toISOString():null,endTime:new Date(e).toISOString(),watchSeconds:n,resolution:this.resolution})}registerEvents(){this.player.addEventListener("play",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("playing",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("timeupdate",(()=>{this._shouldUpdateCollector()&&(this._sendUsageToCollector(),this._resetStartTime())}),{signal:this._controller.signal}),this.player.addEventListener("pause",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal}),this.player.addEventListener("ended",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal})}_unregisterEvents(){this._usageCollector.unregisterStream(this.player.id),this._controller.abort(),this._observer.disconnect()}}var lp=Object.freeze({__proto__:null,getPlayer:async e=>{const{streamId:t}=e;if(!document)throw new Error("This method can be invoked within the browser enviornment only");if(!P.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await Lg(t),{watcherUrl:a,status:s,recordings:o=[],resolution:i}=n;if(!a.hls)throw new Error("This stream does not support hls. Unable to play");const r=document.createElement("video");r.id=t,r.controls=!0;const c=new P.default;if(c.attachMedia(r),"recorded"!==s){let{url:e}=a.hls;e=e.replace("http:","https:"),c.loadSource(e)}else{const e=o.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");r.src=e.mp4.url}return new dp(r,i,t).registerEvents(),r}});const up=e=>{const t=(e=>{var t;const n=Ye(),a=new Date,s=a.getTime()+31536e6,o=new Date(s).toISOString();let i=null===(t=at(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return i||(i={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:o,targetPublicId:e.targetId,targetUpdatedAt:a.toISOString()},Fn({storyTargets:[i]})),{stories:[Object.assign({createdAt:a.toISOString(),updatedAt:a.toISOString(),flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,storyId:e.referenceId,path:"",creatorId:n.userId||"",creatorPublicId:n.userId||"",targetPublicId:e.targetId,comments:[],commentsCount:0,isDeleted:!1,hasFlaggedComment:!1,mentionedUsers:[],impression:0,reach:0,expiresAt:new Date(s).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Fn(t),t},hp=({payload:e,formData:t,isVideo:n=!1},a)=>{if(t){const s=t.getAll("files")[0]||void 0;if(!s)return;const o=Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:s.uri})});return n&&(o.data.videoFileId={original:void 0}),a(up(o))}return a(up(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},mp=async e=>{const t=Ye();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),a=dm(n.data);t.cache&&Fn(a),st(["story-sync-state",e.targetId],"synced"),Nt("local.story.created",a);const s=t.cache&&Date.now();return{data:a.stories.length>0?a.stories[0]:void 0,cachedAt:s}},gp=async({targetId:e,targetType:t})=>{var n,a;if(!at(["storyTarget","get",e])){let s={targetId:e,targetType:t};if("community"===t){const t=await Hu(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.communityId,targetUpdatedAt:null!==(n=t.data.updatedAt)&&void 0!==n?n:(new Date).toISOString()})}if("user"===t){const t=await Id(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(a=t.data.updatedAt)&&void 0!==a?a:(new Date).toISOString()})}st(["storyTarget","get",e],s)}},pp=e=>e?at(["story","get",e]):{data:void 0,cachedAt:void 0},yp=async(e,t=!1)=>{var n,a,s;const o=Ye();let i;if(o.log("story/deleteStory",e),o.cache&&(i=pp(e),null==i?void 0:i.data)){const{data:o}=i;if(Nt("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},o),{isDeleted:!0})]}),"synced"!==o.syncState){t?rt(["story","get",e]):st(["story","get",e],Object.assign(Object.assign({},i.data),{isDeleted:!0}));const a=null===(n=nt(["story","get"]))||void 0===n?void 0:n.filter((e=>"synced"!==e.data.syncState&&e.data.targetId===o.targetId&&!0!==e.data.isDeleted));if(a&&a.length>0){const e=a.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0));st(["story-expire",i.data.targetId],e.toISOString())}else rt(["story-expire",i.data.targetId]);return!0}const r=null===(a=at(["storyTarget","get",o.targetId]))||void 0===a?void 0:a.data,c=null===(s=nt(["story","get"]))||void 0===s?void 0:s.filter((e=>"synced"===e.data.syncState&&e.data.targetId===o.targetId&&!0!==e.data.isDeleted));let d;c&&c.length>0&&(d=null==c?void 0:c.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0))),r&&st(["storyTarget","get",o.targetId],Object.assign(Object.assign({},r),{lastStoryExpiresAt:d}))}return(await o.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},vp=e=>{const t=Ye(),n=[xt(t,"onStoryUpdated","story.updated",(async t=>{const n=dm(t);Fn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},fp=e=>{const t=Ye(),n=[xt(t,"onStoryUpdated","local.story.updated",(async t=>{Fn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},bp=e=>{const t=Ye(),n=[xt(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,a=Bn(t,["reactions"]),s=dm(a),o=rl("story.reactionAdded",Object.assign(Object.assign({},s),{reactions:n}));Fn(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},Ip=e=>{const t=Ye(),n=[xt(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Fn({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Cp=e=>{const t=Ye(),n=[xt(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,a=Bn(t,["reactions"]),s=dm(a),o=rl("story.reactionRemoved",Object.assign(Object.assign({},s),{reactions:n}));Fn(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},wp=e=>{const t=Ye(),n=[xt(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Fn({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Sp=e=>{e.forEach((e=>{const t=at(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||st(["story-expire",e.targetId],n.toISOString())}))},Op=e=>{e.forEach((e=>{st(["story-reference",e.storyId],e.referenceId)}))},Tp=async({targetType:e,targetId:t,options:n})=>{const a=Ye();a.log("story/getActiveStoriesByTarget");const s=a.cache&&Date.now(),o=await a.http.get("/api/v4/stories",{params:{targetType:e,targetId:t,options:{sortBy:(null==n?void 0:n.sortBy)||"createdAt",orderBy:(null==n?void 0:n.orderBy)||"desc"}}}),i=dm(o.data);return a.cache&&(Fn(i),Sp(i.stories),Op(i.stories)),{data:i.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},Ap=e=>{const t=Ye(),n=[xt(t,"onStoryCreated","story.created",(async t=>{const n=dm(t,!0);Fn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Rp=e=>{const t=Ye(),n=[xt(t,"onStoryCreated","local.story.created",(async t=>{Fn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Pp=e=>{const t=Ye(),n=[xt(t,"onStoryDeleted","story.deleted",(async t=>{const n=dm(t);Fn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Dp=e=>{const t=Ye(),n=[xt(t,"onStoryDeleted","local.story.deleted",(async t=>{Fn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Up=e=>{const t=Ye();return xt(t,"onStoryError","local.story.error",(async t=>{Fn(t),e(t.stories)}))},kp=e=>t=>e((e=>t(e[0]))),jp=async e=>{const t=Ye();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:a}=n;return t.cache&&Fn(n.data),{data:a.storyTargets,cachedAt:Date.now()}};class Ep extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.paginationController=a}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now(),a=dm(e);t.cache&&(Fn(a,{cachedAt:n}),Sp(a.stories),Op(a.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.stories.map(this.getStoryReferenceIds)])]}))}}reactor(e){return e=>{var t;const n=null===(t=at(this.cacheKey))||void 0===t?void 0:t.data;if(!n)return;const a=e.map((({referenceId:e})=>e));n.data=[...new Set([...a,...n.data])],st(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Mp extends Ar{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class qp extends Rr{constructor(e,t){const n=R.default(e),a=["story-target-ids","collection",n],s=new Mp(e);super(s,n,a,t),this.query=e,this.queryStreamController=new Ep(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;let o=s.data.map((e=>at(["story","get",e]))).filter(Boolean).map((e=>hd.story(e.data)));(this.shouldNotify(o)||"event"!==e)&&(o=this.applyFilter(o),this.callback({onNextPage:void 0,data:o,hasNextPage:!1,loading:t,error:n}))}applyFilter(e){var t,n;const a=e;return"asc"===((null===(n=null===(t=this.query)||void 0===t?void 0:t.options)||void 0===n?void 0:n.orderBy)||"desc")?a.sort(Ct):a.sort(St)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ap,action:"onCreate"},{fn:vp,action:"onUpdate"},{fn:Pp,action:"onDelete"},{fn:Up,action:"onError"}])}}const xp=(e,t)=>{var n,a;const s=null===(n=at(e))||void 0===n?void 0:n.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[];st(e,Object.assign(Object.assign({},s),{data:[...new Set([...o,...t])]}))};class Np extends Sr{constructor(e,t,n,a,s){super(e,t),this.notifyChange=n,this.paginationController=a,this.preparePayload=s}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now(),a=this.preparePayload(e);t.cache&&Fn(a,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?st(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):xp(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&xp(this.cacheKey,t.map((({targetId:e})=>e))),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Kp extends Cr{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:a=10,seenState:s="unseen"}=e,o=await this.createRequest({seenState:"smart"===s?this.smartFilterState:s,limit:a,token:t});if(null===(n=o.paging)||void 0===n?void 0:n.next)return o;if("smart"!==s)return o;if("seen"===this.smartFilterState)return o;this.smartFilterState="seen";const i=await this.createRequest({seenState:this.smartFilterState,limit:a});return c=i,{categories:(r=o).categories.concat(c.categories),communities:r.communities.concat(c.communities),communityUsers:r.communityUsers.concat(c.communityUsers),files:r.files.concat(c.files),storyTargets:r.storyTargets.concat(c.storyTargets),users:r.users.concat(c.users),paging:c.paging};var r,c}async createRequest(e){const{data:t}=await this.http.get("/api/v5/me/global-story-targets",{params:e});return n=t,a=e.seenState,Object.assign(Object.assign({},n),{storyTargets:n.storyTargets.map((e=>Object.assign(Object.assign({},e),{localFilter:a})))||[]});var n,a}}class Fp extends Rr{constructor(e,t){const n=R.default(e),a=["story-global-feed","collection",n],s=new Kp(e);super(s,n,a,t),this.query=e,this.queryStreamController=new Np(this.query,this.cacheKey,this.notifyChange.bind(this),s,(e=>{const t=Bn(_r(Object.assign(Object.assign({},e),{feeds:[]})),["feeds"]);return Object.assign(Object.assign({},e),t)})),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=s.data,i=nt(["storyTarget"]);i&&(null==i?void 0:i.length)>0&&(null==i||i.forEach((({key:e})=>{s.data.includes(e[2])||o.push(e[2])})));let r=o.map((e=>at(["storyTarget","get",e]))).filter(Boolean).map((e=>hd.storyTarget(e.data)));(this.shouldNotify(r)||"event"!==e)&&(r=this.applyFilter(r).filter((({localSortingDate:e})=>!!e)).map((e=>Bn(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:r,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n}))}applyFilter(e){if("smart"!==this.query.seenState)return e.filter((({hasUnseen:e})=>"all"===this.query.seenState||("seen"===this.query.seenState&&!e||"unseen"===this.query.seenState&&e))).sort(wt);const t=e.reduce(((e,t)=>("unseen"===t.localFilter?e.unseen.push(t):"seen"===t.localFilter?e.seen.push(t):e.unknown.push(t),e)),{unseen:[],seen:[],unknown:[]}),n=t.unknown.sort(wt)||[],a=t.unseen.sort(wt)||[],s=t.seen.sort(wt)||[];return n.concat(a,s)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ap,action:"onCreate"},{fn:vp,action:"onUpdate"},{fn:Pp,action:"onDelete"},{fn:Rp,action:"onCreate"},{fn:fp,action:"onUpdate"},{fn:Dp,action:"onDelete"},{fn:Up,action:"onError"}])}}var _p=Object.freeze({__proto__:null,createImageStory:async(e,t,n,a={},s="fit",o=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let i={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:s},syncState:"syncing",referenceId:kn(),dataType:"image",items:o,targetType:e,targetId:t,metadata:a};const r=new Date;st(["story-sync-state",t],"syncing"),st(["story-expire",t],new Date(r.setFullYear(r.getFullYear()+1))),hp({payload:i,formData:n},(e=>{Nt("local.story.created",e)}));try{const{data:a}=await Bd(n);if(0===a.length)throw new Error("Failed to upload image");const{fileId:s}=a[0];i=Object.assign(Object.assign({},i),{data:Object.assign(Object.assign({},i.data),{fileId:s})}),gp({targetId:t,targetType:e}),hp({payload:i,formData:n},(e=>{Nt("local.story.created",e)}));const o=await mp(i);return o.data?Object.assign(Object.assign({},o),{data:hd.story(o.data)}):o}catch(e){throw st(["story-sync-state",t],"error"),hp({payload:Object.assign(Object.assign({},i),{syncState:"error"}),formData:n},(e=>{Nt("local.story.error",e)})),e}},createVideoStory:async(e,t,n,a={},s=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let o={data:{text:"",fileId:void 0,fileData:null},syncState:"syncing",referenceId:kn(),dataType:"video",items:s,targetType:e,targetId:t,metadata:a};const i=new Date;st(["story-sync-state",t],"syncing"),st(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),gp({targetId:t,targetType:e}),hp({payload:o,formData:n,isVideo:!0},(e=>{Nt("local.story.created",e)}));try{const{data:e}=await _d(n,F.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];o=Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{fileId:t,videoFileId:{original:t}})}),hp({payload:o,formData:n,isVideo:!0},(e=>{Nt("local.story.created",e)}));const a=await mp(o);return a.data?Object.assign(Object.assign({},a),{data:hd.story(a.data)}):a}catch(e){throw st(["story-sync-state",t],"error"),hp({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n,isVideo:!0},(e=>{Nt("local.story.error",e)})),e}},hardDeleteStory:async e=>await yp(e,!0),softDeleteStory:async e=>await yp(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:a}=Ye(),s=[],o=["story-target","collection",e],i=Date.now();n(`getActiveStoriesByTarget(tmpid: ${i}) > listen`),a||console.log(ve);const r=t=>{var n,a;const s=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",o=(null===(a=e.options)||void 0===a?void 0:a.orderBy)||"desc";return 0===t.length?[]:"createdAt"===s?"asc"===o?t.sort(Ct):t.sort(St):"asc"===o?t.sort(Ot):t.sort(Tt)},c=e=>{var n;const a=e.data.map((e=>{const t=pp(e);if(null==t?void 0:t.data)return hd.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),s=[];if(a.length>0){const e=a.reduce(((e,t)=>{if(!t)return e;const{syncState:n}=t;if(!n)return e;let a=e.get(n);return a||(a=[]),a.push(t),e.set(n,a),e}),new Map);if(e.has("error")){const t=r(e.get("error")||[]);s.push(...t)}if(e.has("syncing")){const t=r(e.get("syncing")||[]);s.push(...t)}if(e.has("synced")){const t=r(e.get("synced")||[]);s.push(...t)}}t({onNextPage:()=>!1,data:s||a,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},d=(t,n,a=!1,s=!1,i=!1)=>{var r;const d=at(o),l={loading:s,error:i,params:{page:void 0},data:(null==d?void 0:d.data)||[]};if(t)if("onDelete"===n){const e=t.map((({referenceId:e})=>e));l.data=l.data.filter((t=>!e.includes(t)))||[]}else l.data=a?t.map(Ze("story")):[...new Set([...l.data,...t.map(Ze("story"))])];const u=null===(r=nt(["story","get"]))||void 0===r?void 0:r.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>Ze("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{l.data.includes(e)||l.data.push(e)})),st(o,l.data),c(l)},l=e=>t=>{d(t,e)};return(t=>{const n=_e(Tp,e);$e(n,(({data:e,error:n,loading:a})=>{d(e,"fetch",t,a,n)}))})(!0),s.push(Ap(l("onCreate")),vp(l("onUpdate")),Pp(l("onDelete")),bp(l("onReactionAdded")),Cp(l("onReactionRemoved")),Up(l("onError")),Rp(l("onCreate")),fp(l("onUpdate")),Dp(l("onDelete")),Ip(l("onReactionAdded")),wp(l("onReactionRemoved")),(e=>{const t=Ye();return xt(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=at(o);if(!t)return;if(0===e.referenceIds.length||0===(null==t?void 0:t.data.length))return;if(!(null==t?void 0:t.data.find((t=>e.referenceIds.includes(t)))))return;const n={loading:!1,error:!1,params:{page:void 0},data:(null==t?void 0:t.data)||[]};c(n)})),(()=>rt(o))),()=>{n(`getActiveStoriesByTarget(tmpid: ${i}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>qr(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:hd.story(e.data)})):t(e)}),"storyId",lm,[kp(vp),kp(Pp),kp(bp),kp(Cp),kp(Up),kp(fp),kp(Dp),kp(Ip),kp(wp)]),getTargetById:(e,t)=>qr(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:hd.storyTarget(e.data[0])})):t(e)}),"query",(e=>jp([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:a}=Ye(),s=[],o=["storyTargets","collection",e],i=Date.now();n(`getTargetsByTargetIds(tmpid: ${i}) > listen`),a||console.log(ve);const r=(e,n=!1,a=!1,s=!1)=>{const i=at(o),r={loading:a,error:s,params:{page:void 0},data:[]};e&&(r.data=n?e.map(Ze("storyTarget")):[...new Set([...(null==i?void 0:i.data)||[],...e.map(Ze("storyTarget"))])]),st(o,r.data),(e=>{var n;const a=e.data.map((e=>{const t=at(["storyTarget","get",e]);if(null==t?void 0:t.data)return hd.storyTarget(t.data)})).filter(Boolean);t({onNextPage:void 0,data:a,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})})(r)};return(t=>{const n=_e(jp,e);$e(n,(({data:e,error:n,loading:a})=>{r(e,t,a,n)}))})(!0),s.push((()=>rt(o))),()=>{n(`getTargetsByTargetIds(tmpid: ${i}) > dispose`),s.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getStoriesByTargetIds(tmpid: ${i}) > listen`);const r=new qp(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{rt(d)})),()=>{a(`getStoriesByTargetIds(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ye();s||console.log(ve);const i=Date.now();a(`getGlobalStoryTarget(tmpid: ${i}) > listen`);const r=new Fp(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{rt(d)})),()=>{a(`getGlobalStoryTarget(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}}});const Bp=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),$p=e=>Object.assign({},e);var Lp=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=Ye(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(Bp),a=t.advertisers.map($p);return Fn({ads:n,advertisers:a,files:t.files}),st(["ad","setting"],t.settings),{ads:n.map(hd.ad),settings:t.settings}}});const Qp=async()=>{const e=Ye();e.log("notificationTray/getNotificationTraySeen",{});const{data:t}=await e.http.get("api/v1/notification-tray/tray/seen"),n=e.cache&&Date.now();if(e.cache){const n=["notificationTraySeen","get",e.userId];st(n,{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccuredAt:t.lastTrayOccurredAt})}return{data:{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccurredAt:t.lastTrayOccurredAt,isSeen:t.lastTraySeenAt>t.lastTrayOccurredAt},cachedAt:n}};Qp.locally=()=>{var e;const t=Ye();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:a}=null!==(e=at(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:a}:void 0};const Vp=e=>{const t=Ye(),n=[xt(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Jp extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/notification-tray",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class Hp extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.notificationTrayItems.map(Ze("notificationTrayItem"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(Ze("notificationTrayItem"))])]}))}}}const Gp=e=>{const t=e.users.map(pa);return Object.assign(Object.assign({},e),{users:t})};class zp extends Rr{constructor(e,t){const n=R.default(e),a=["notificationTrayItem","collection",n];super(new Jp(e),n,a,t),this.query=e,this.queryStreamController=new Hp(this.query,this.cacheKey,this.notifyChange.bind(this),Gp),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["notificationTrayItem","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.notificationTray);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Yp=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=Ut();return qr(t,e,"userId",Qp,[Vp],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Gn(e.lastTraySeenAt)>Gn(e.lastTrayOccurredAt)),{lastTrayOccurredAt:null==e?void 0:e.lastTrayOccurredAt,lastTraySeenAt:null==e?void 0:e.lastTraySeenAt,isSeen:t}}})},getNotificationTrayItems:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getNotificationTrayItems(tmpid: ${o}) > listen`);const i=new zp(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getNotificationTrayItems(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},markItemsSeen:async e=>{const t=Ye();t.log("notificationTray/markItemsSeen",{});const{data:n}=await t.http.post("api/v1/notification-tray/items/seen",{trayItems:e.map((e=>({id:e.id,lastSeenAt:e.lastSeenAt})))}),a=n.trayItems.map((e=>{var n;const a=null===(n=at(["notificationTrayItem","get",e.id]))||void 0===n?void 0:n.data;if(!a)return;const s=Object.assign(Object.assign({},a),{lastSeenAt:e.lastSeenAt});if(t.cache){const e=Date.now();st(["notificationTrayItem","get"],s,{cachedAt:e})}return s})).filter(Boolean);Nt("local.notificationTrayItem.updated",{notificationTrayItems:a})},markTraySeen:async e=>{var t;const n=Ye();n.log("notificationTray/markTraySeen",{});const{data:a}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),s=null===(t=at(["notificationTraySeen","get"]))||void 0===t?void 0:t.data,o={userId:n.userId,lastTraySeenAt:a.lastSeenAt},i=Object.assign(Object.assign({},s),o),r=n.cache&&Date.now();return n.cache&&st(["notificationTraySeen","get",n.userId],i,{cachedAt:r}),Nt("local.notificationTraySeen.updated",o),{data:a,cachedAt:r}},onNotificationTraySeenUpdated:Vp});class Wp extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/invitations/me",{params:Object.assign(Object.assign({},a),{options:s})}),i=o.invitations.filter((e=>"community"===e.targetType&&!!e.communityId)).map((e=>e.communityId));return(null==i?void 0:i.length)>0&&await Ju(i),o}}class Xp extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.invitations.map(Ze("invitation"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Ze("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===oc.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}if(e===oc.OnLocalInvitationCreated){const e=Ye(),n=t.filter((t=>t.invitedUserId===e.userId));a.data=[...new Set([...n.map((e=>e.invitationId)),...a.data])]}e===oc.OnLocalInvitationCanceled&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Zp extends Rr{constructor(e,t){const n=R.default(e),a=["invitation","collection",n];super(new Wp(e),n,a,t),this.query=e,this.queryStreamController=new Xp(this.query,this.cacheKey,this.notifyChange.bind(this),nc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:cc,action:oc.OnLocalInvitationCreated},{fn:dc,action:oc.OnLocalInvitationUpdated},{fn:lc,action:oc.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>at(["invitation","get",e]))).filter(Pr).map((({data:e})=>ac(e))))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?Ct:St)();return t=t.sort(n),t}}var ey=Object.freeze({__proto__:null,cancelInvitation:async e=>{var t;const n=Ye();n.log("invitation/cancelInvitation",e);const{data:a}=await n.http.delete(`/api/v1/invitations/${e}`),s=null===(t=at(["invitation","get",e]))||void 0===t?void 0:t.data;return _n("invitation",e),s&&Nt("local.invitation.canceled",[s]),a.success},onLocalInvitationCreated:cc,onLocalInvitationUpdated:dc,onLocalInvitationCanceled:lc,getMyCommunityInvitations:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMyCommunityInvitations: (tmpid: ${o}) > listen`);const i=new Zp(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{rt(c)})),()=>{a(`getInvitations (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getInvitations:(e,t)=>{const{_id:n}=$t();if(!n)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=Ye(),{targetId:s,targetType:o}=e,i=Date.now();a(`observeInvitations(tmpid: ${i}) > listen for ${o}: ${s}`);const r=[],c=n=>{const a=(Array.isArray(n)?n:[n]).filter((({targetId:t,targetType:n})=>t===e.targetId&&n===e.targetType));(e=>{t(e.map(hd.invitation))})(a)};return"room"===o&&(r.push(bg(c)),r.push(Cg(c)),r.push(wg(c)),r.push(Sg(c))),()=>{a(`getInvitations(tmpid: ${i}) > dispose for ${o}: ${s}`),r.forEach((e=>e()))}}});const ty=e=>{const t=Ye();return xt(t,"live_reaction/onLiveReactionCreated","liveReaction.created",(n=>{if(n.reactions.length>0){const a=n.reactions.filter((({userId:e})=>e!==t.userId));e(a)}}))};var ny=Object.freeze({__proto__:null,createReaction:async({referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:s})=>{const o=Ye();if(o.log("live_reaction/createReaction",{referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:s}),!a&&!s)throw new Qe("You have to specify either streamId or roomId",800110,"error");const i=No(),r={reactionName:n,referencePublicId:e,referenceType:t,roomId:s,streamId:a,occurredAt:(new Date).toISOString()};return i.createLiveReaction(r),Nt("local.liveReaction.created",[Object.assign(Object.assign({},r),{userId:o.userId,referenceId:e})]),!0},onLiveReactionCreated:ty,getReactions:(e,t)=>{const{_id:n}=Ut();if(!n)throw new Qe("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=Ye();a(`getReactions(tmpid: ${Date.now()}) > listen`);const s=[],o=n=>{(e=>{t(e)})(n.filter((({referenceId:t})=>t===e)))};return s.push(ty(o)),s.push((e=>{const t=Ye();return xt(t,"live_reaction/onLiveReactionCreated","local.liveReaction.created",e)})(o)),()=>{s.forEach((e=>e()))}}});const ay=async e=>{const t=Ye();t.log("event/getEvent",e);try{const{data:n}=await t.http.get(`/api/v1/events/${e}`),a=Jc(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:a.events.find((t=>t.eventId===e)),cachedAt:s}}catch(n){if(Pe(null==n?void 0:n.code)){const a=ay.locally(e);if(!a)throw n;const s=Object.assign(Object.assign({},null==a?void 0:a.data),{isDeleted:!0});it(["event","get",e],s);return{data:s,cachedAt:t.cache&&Date.now()}}throw n}};ay.locally=e=>{const t=Ye();if(t.log("event/getEvent.locally",e),!t.cache)return;const n=at(["event","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class sy extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/events",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class oy extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.events.map(Ze("event"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(Ze("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Yc.OnEventCreated&&(a.data=[...new Set([t.eventId,...a.data])]),e===Yc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class iy extends Rr{constructor(e,t){const n=R.default(e),a=["event","collection",n];super(new sy(e),n,a,t),this.query=e,this.queryStreamController=new oy(this.query,this.cacheKey,this.notifyChange.bind(this),Jc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Zc,action:Yc.OnEventCreated},{fn:ed,action:Yc.OnEventUpdated},{fn:td,action:Yc.OnEventDeleted},{fn:nd,action:Yc.OnEventCreated},{fn:ad,action:Yc.OnEventUpdated},{fn:sd,action:Yc.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["event","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.event);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}class ry extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/events/me/rsvps",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class cy extends Sr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ye(),a=n.cache&&Date.now();n.cache&&Fn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.events.map(Ze("event"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(Ze("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=at(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Yc.OnEventCreated){if(Ye().userId!==t.userId)return;a.data=[...new Set([t.eventId,...a.data])]}e===Yc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),st(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class dy extends Rr{constructor(e,t){const n=R.default(e),a=["event","collection",n];super(new ry(e),n,a,t),this.query=e,this.queryStreamController=new cy(this.query,this.cacheKey,this.notifyChange.bind(this),Jc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Zc,action:Yc.OnEventCreated},{fn:ed,action:Yc.OnEventUpdated},{fn:td,action:Yc.OnEventDeleted},{fn:nd,action:Yc.OnEventCreated},{fn:ad,action:Yc.OnEventUpdated},{fn:sd,action:Yc.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>at(["event","get",e]))).filter(Pr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(hd.event);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}var ly=Object.freeze({__proto__:null,createEvent:async e=>{const t=Ye();t.log("event/createEvent",e);const{data:n}=await t.http.post("/api/v1/events",e);Nt("local.event.created",n);const a=Jc(n),s=t.cache&&Date.now();return t.cache&&Fn(a,{cachedAt:s}),{data:ud(a.events[0]),cachedAt:s}},updateEvent:async(e,t)=>{const n=Ye();n.log("event/updateEvent",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}`,t);Nt("local.event.updated",a);const s=Jc(a),o=n.cache&&Date.now();return n.cache&&Fn(s,{cachedAt:o}),{data:ud(s.events.find((t=>t.eventId===e))),cachedAt:o}},deleteEvent:async e=>{const t=Ye();t.log("event/deleteEvent",e);const n=await ay(e);await t.http.delete(`/api/v1/events/${e}`);const a=Object.assign(Object.assign({},n.data),{isDeleted:!0});it(["event","get",e],a),Nt("local.event.deleted",{users:[],files:[],communities:[],posts:[],rooms:[],events:[a]})},onEventCreated:Zc,onEventUpdated:ed,onEventDeleted:td,onLocalEventCreated:nd,onLocalEventUpdated:ad,onLocalEventDeleted:sd,onRSVPCreated:od,onRSVPUpdated:id,onLocalRSVPCreated:rd,onLocalRSVPUpdated:cd,getEvent:(e,t)=>qr(e,t,"eventId",ay,[ed,td,ad,sd],{callbackDataSelector:e=>e?ud(e):e}),getEvents:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getEvents: (tmpid: ${o}) > listen`);const i=new iy(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getEvents (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getMyEvents:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`getMyEvents: (tmpid: ${o}) > listen`);const i=new dy(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`getMyEvents (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getRSVPs:ld});const uy=async e=>{const t=Ye();let n;t.log("product/getProduct",e),ea("product",e);try{n=(await t.http.get(`/api/v1/products/${encodeURIComponent(e)}`)).data}catch(t){throw Pe(null==t?void 0:t.code)&&_n("product",e),t}const a=t.cache&&Date.now();t.cache&&Fn(n,{cachedAt:a});const{products:s}=n;return{data:s.find((t=>t.productId===e)),cachedAt:a}};uy.locally=e=>{const t=Ye();if(t.log("product/getProduct.locally",e),!t.cache)return;const n=at(["product","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class hy extends Cr{async getRequest(e,t){const{limit:n=ge}=e,a=Bn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/products/search",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class my extends Sr{constructor(e,t,n){super(e,t),this.notifyChange=n}saveToMainDB(e){const t=Ye(),n=t.cache&&Date.now();t.cache&&Fn(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var a,s;if(n)st(this.cacheKey,{data:e.products.map(Ze("product"))});else{const t=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];st(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.products.map(Ze("product"))])]}))}}}class gy extends Rr{constructor(e,t){const n=R.default(e),a=["products","collection",n];super(new hy(e),n,a,t),this.query=e,this.queryStreamController=new my(this.query,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=at(this.cacheKey))||void 0===e?void 0:e.data)||st(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=at(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>at(["product","get",e]))).filter(Pr).map((({data:e})=>e)).map(hd.product))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var py=Object.freeze({__proto__:null,getProduct:(e,t)=>qr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hd.product(n):n}))}),"productId",uy,[]),searchProducts:(e,t,n)=>{const{log:a,cache:s}=Ye();s||console.log(ve);const o=Date.now();a(`searchProducts(tmpid: ${o}) > listen`);const i=new gy(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>rt(c))),()=>{a(`searchProducts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});return e.API_REGIONS=on,e.AdRepository=Lp,e.AmityAttachmentProductTags=class{constructor(){this.map=new Map}get(e){return this.map.get(e)||[]}set(e,t){this.map.set(e,t)}},e.CategoryRepository=nm,e.ChannelRepository=Qu,e.Client=sr,e.CommentRepository=Cm,e.CommunityPostSettingMaps=x,e.CommunityPostSettings=q,e.CommunityRepository=Zh,e.ContentFeedType=F,e.DefaultCommunityPostSetting=N,e.EventRepository=ly,e.FeedRepository=Hm,e.FileRepository=$d,e.FileType=D,e.GET_WATCHER_URLS=fc,e.InvitationRepository=ey,e.LiveReactionRepository=ny,e.LiveStreamPlayer=lp,e.MessageContentType=B,e.MessageRepository=mu,e.PollRepository=ip,e.PostContentType=$,e.PostRepository=$g,e.PostStructureType=L,e.ProductRepository=py,e.ReactionRepository=xl,e.RoomPresenceRepository=np,e.RoomRepository=Ng,e.StoryRepository=_p,e.StreamRepository=Wg,e.SubChannelRepository=Iu,e.UserRepository=Kd,e.VERSION=me,e.VideoResolution=U,e.VideoSize=j,e.VideoTranscodingStatus=k,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:a,userId:s}=Ye();if(!a)return!1;n("cache/api/backupCache",{storageKey:e});const o=Object.fromEntries(Object.entries(a.data).filter((([e,n])=>t(n))));return!!Object.keys(o).length&&(localStorage&&await localStorage.setItem(`${e}#${s}`,JSON.stringify(o)),!0)},e.createQuery=_e,e.createReport=async(e,t,n)=>{const a=Ye();return a.log("report/createReport",{referenceType:e,referenceId:t,options:n}),"user"===e?(async({referenceId:e,options:t})=>!!await gd(e,t))({referenceId:t,options:n}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await ha(n);Fn(e)}return Nt("message.flagged",n),!!n})({client:a,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await Zd(n);Fn(e)}return Nt("post.flagged",n),!!n})({client:a,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await Nl(n);Fn(e)}return Nt("comment.flagged",n),!!n})({client:a,referenceId:t})},e.createUserToken=async(e,t,n)=>{const a=await En(),s=Mn(),o=yn(cn("http",t)),{data:i}=await o.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:a,deviceInfo:Object.assign(Object.assign({},s),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:i.accessToken}},e.deleteReport=async(e,t)=>{const n=Ye();return n.log("report/deleteReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await eo(n);Fn(e)}return Nt("user.unflagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await ha(n);Fn(e)}return Nt("message.unflagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/posts/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await Zd(n);Fn(e)}return Nt("post.unflagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/comments/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await Nl(n);Fn(e)}return Nt("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=Ye();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=rt,e.enableCache=(e={},t)=>{const n=Ye();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.exceedsUntilAtBoundary=Pt,e.filterByChannelMembership=ut,e.filterByCommunityMembership=mt,e.filterByFeedType=ht,e.filterByPostDataTypes=gt,e.filterByPropEquality=ct,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=lt,e.filterBySearchTerm=pt,e.filterByStringComparePartially=dt,e.filterByUntilAt=(e,t,n)=>{const a=new Date(t).valueOf();return"firstCreated"===n?e.filter((e=>new Date(e.createdAt).valueOf()<a)):e.filter((e=>new Date(e.createdAt).valueOf()>a))},e.filterCommentsByBlockUsers=ft,e.filterPostsByBlockUsers=vt,e.getBlockUsersId=yt,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=Ut();return`${Vt(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>Qt(t,n),e.getLiveReactionTopic=e=>`${e.path}/liveReaction`,e.getLiveStreamTopic=Zt,e.getMarkedMessageTopic=Gt,e.getMarkerUserFeedTopic=()=>{const e=Ut();return`${Vt(e)}/marker/user/${e._id}`},e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=Jt,e.getMyFollowingsTopic=Ht,e.getNetworkId=Vt,e.getNetworkTopic=zt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Qd,e.getRoomStreamerTopic=e=>{const t=$t();return`${Vt(t)}/room/${e.roomId}/streamer`},e.getRoomWatcherTopic=e=>{const t=$t();return`${Vt(t)}/room/${e._id}`},e.getSmartFeedChannelTopic=Yt,e.getSmartFeedMessageTopic=Xt,e.getSmartFeedSubChannelTopic=Wt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const a=Ut();return`${Vt(a)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=({path:t},n=e.SubscriptionLevels.USER)=>Qt(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),e.isAfterBefore=Ue,e.isAfterBeforeRaw=ke,e.isCachable=Ke,e.isFetcher=qe,e.isFresh=Fe,e.isLocal=e=>Ke(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=xe,e.isOffline=Ne,e.isPaged=je,e.isReportedByMe=async(e,t)=>{const n=Ye();return n.log("report/isReportedByMe",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/users/${t}/isflagbyme`),{result:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`),{result:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/posts/${t}/isflagbyme`),{result:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/comments/${t}/isflagbyme`),{result:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=De,e.mergeInCache=ot,e.notificationTray=Yp,e.onChannelMarkerFetched=zi,e.onFeedMarkerFetched=e=>{const t=Ye();return xt(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=Ye();return xt(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Fn(t),e(t.feedMarkers[0])}))},e.onMessageMarked=er,e.onMessageMarkerFetched=Zi,e.onSubChannelMarkerFetched=Yi,e.onSubChannelMarkerUpdated=Wi,e.onUserMarkerFetched=Xi,e.onUserMarkerFetchedLegacy=e=>{const t=Ye();return xt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=at,e.pushToCache=st,e.queryCache=nt,e.queryOptions=Be,e.queryRoles=Ld,e.restoreCache=async(e="amitySdk")=>{var t;const n=Ye();if(!n.cache)return!1;n.log("cache/api/restoreCache",{storageKey:e});const a=localStorage&&null!==(t=await localStorage.getItem(`${e}#${n.userId}`))&&void 0!==t?t:"{}";let s={};try{s=JSON.parse(a)}catch(e){}return n.cache.data=Object.assign(Object.assign({},s),n.cache.data),!0},e.runQuery=$e,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=bt,e.sortByFirstCreated=Ct,e.sortByFirstUpdated=Ot,e.sortByLastActivity=At,e.sortByLastCreated=St,e.sortByLastUpdated=Tt,e.sortByLocalSortingDate=wt,e.sortByName=It,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=en,e.toPage=Me,e.toPageRaw=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return ke(n)?n:void 0},e.toToken=Ee,e.upsertInCache=it,e.validateUntilAt=Rt,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:a}=Ye();return!!n&&(t("cache/api/wipeCache",{storageKey:e}),n.data={},localStorage&&await localStorage.setItem(`${e}#${a}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({},jsBase64,mitt,debug,axios,HttpAgent,mqtt,AsyncStorage,uuid$1,jwtDecode,reactNative,hash,Hls);
1
+ var Amity=function(e,t,n,a,s,o,i,r,c,d,l,u,h,m){"use strict";function g(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p,y,v,f,b,I=g(n),C=g(a),w=g(s),S=g(o),O=g(i),A=g(r),T=g(d),R=g(l),P=g(h),k=g(m);e.MembershipAcceptanceTypeEnum=void 0,(p=e.MembershipAcceptanceTypeEnum||(e.MembershipAcceptanceTypeEnum={})).AUTOMATIC="automatic",p.INVITATION="invitation",e.AmityAutoSubscription=void 0,(y=e.AmityAutoSubscription||(e.AmityAutoSubscription={})).CHAT="chat",y.NETWORK="network",y.LIVESTREAM="livestream",y.BLOCK="block",e.UserTypeEnum=void 0,(v=e.UserTypeEnum||(e.UserTypeEnum={})).SIGNED_IN="signed-in",v.VISITOR="visitor",v.BOT="bot",e.SearchUsersByEnum=void 0,(f=e.SearchUsersByEnum||(e.SearchUsersByEnum={})).DISPLAY_NAME="displayName",f.PROFILE_HANDLE="profileHandle",f.USER_ID="userId",e.UserReportTypeEnum=void 0,(b=e.UserReportTypeEnum||(e.UserReportTypeEnum={})).DISPLAY_NAME="displayName",b.DESCRIPTION="description",b.AVATAR="avatarFileId",b.BEHAVIOR="behavior";const D=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video",CLIP:"clip",AUDIO:"audio"}),U=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),j=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),E=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var M,q;e.FileAccessTypeEnum=void 0,(M=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",M.NETWORK="network",e.AmityChannelNotificationModeEnum=void 0,(q=e.AmityChannelNotificationModeEnum||(e.AmityChannelNotificationModeEnum={})).Default="default",q.Silent="silent",q.Subscribe="subscribe";const x=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),K=Object.freeze({ONLY_ADMIN_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!0},ADMIN_REVIEW_POST_REQUIRED:{needApprovalOnPostCreation:!0,onlyAdminCanPost:!1},ANYONE_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!1}}),N="ONLY_ADMIN_CAN_POST";var F;e.AmityCommunityType=void 0,(F=e.AmityCommunityType||(e.AmityCommunityType={})).Default="default",F.Event="event";const _=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"});var B;e.ContentFlagReasonEnum=void 0,(B=e.ContentFlagReasonEnum||(e.ContentFlagReasonEnum={})).CommunityGuidelines="Against community guidelines",B.HarassmentOrBullying="Harassment or bullying",B.SelfHarmOrSuicide="Self-harm or suicide",B.ViolenceOrThreateningContent="Violence or threatening content",B.SellingRestrictedItems="Selling and promoting restricted items",B.SexualContentOrNudity="Sexual content or nudity",B.SpamOrScams="Spam or scams",B.FalseInformation="False information or misinformation",B.Others="Others";const $=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),L=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll",CLIP:"clip",AUDIO:"audio",ROOM:"room",EVENT:"event"}),Q=Object.freeze({TEXT:"text",IMAGE:"image",VIDEO:"video",FILE:"file",AUDIO:"audio",MIXED:"mixed",EVENT:"event"});var V,J,H,W,z,G,Y,X,Z,ee,te,ne,ae,se,oe,ie,re,ce,de,le,ue,he,me;e.InvitationTypeEnum=void 0,(V=e.InvitationTypeEnum||(e.InvitationTypeEnum={})).CommunityMemberInvite="communityMemberInvite",V.LivestreamCohostInvite="livestreamCohostInvite",e.InvitationStatusEnum=void 0,(J=e.InvitationStatusEnum||(e.InvitationStatusEnum={})).Pending="pending",J.Approved="approved",J.Rejected="rejected",J.Cancelled="cancelled",e.InvitationSortByEnum=void 0,(H=e.InvitationSortByEnum||(e.InvitationSortByEnum={})).FirstCreated="firstCreated",H.LastCreated="lastCreated",e.InvitationTargetTypeEnum=void 0,(W=e.InvitationTargetTypeEnum||(e.InvitationTargetTypeEnum={})).Community="community",W.Room="room",e.JoinRequestStatusEnum=void 0,(z=e.JoinRequestStatusEnum||(e.JoinRequestStatusEnum={})).Pending="pending",z.Approved="approved",z.Rejected="rejected",z.Cancelled="cancelled",e.JoinResultStatusEnum=void 0,(G=e.JoinResultStatusEnum||(e.JoinResultStatusEnum={})).Success="success",G.Pending="pending",e.FeedDataTypeEnum=void 0,(Y=e.FeedDataTypeEnum||(e.FeedDataTypeEnum={})).Text="text",Y.Video="video",Y.Image="image",Y.File="file",Y.Audio="audio",Y.LiveStream="liveStream",Y.Clip="clip",Y.Poll="poll",Y.Room="room",e.FeedSortByEnum=void 0,(X=e.FeedSortByEnum||(e.FeedSortByEnum={})).LastCreated="lastCreated",X.FirstCreated="firstCreated",X.LastUpdated="lastUpdated",X.FirstUpdated="firstUpdated",e.FeedSourceEnum=void 0,(Z=e.FeedSourceEnum||(e.FeedSourceEnum={})).Community="community",Z.User="user",e.FeedTypeEnum=void 0,(ee=e.FeedTypeEnum||(e.FeedTypeEnum={})).Reviewing="reviewing",ee.Published="published",ee.Declined="declined",e.AmityEventType=void 0,(te=e.AmityEventType||(e.AmityEventType={})).Virtual="virtual",te.InPerson="in_person",e.AmityEventOriginType=void 0,(ne=e.AmityEventOriginType||(e.AmityEventOriginType={})).Community="community",ne.User="user",e.AmityEventStatus=void 0,(ae=e.AmityEventStatus||(e.AmityEventStatus={})).Scheduled="scheduled",ae.Live="live",ae.Ended="ended",ae.Cancelled="cancelled",e.AmityEventResponseStatus=void 0,(se=e.AmityEventResponseStatus||(e.AmityEventResponseStatus={})).Going="going",se.NotGoing="not_going",e.AmityEventSortOption=void 0,(oe=e.AmityEventSortOption||(e.AmityEventSortOption={})).StartTime="startTime",oe.CreatedAt="createdAt",e.AmityEventOrderOption=void 0,(ie=e.AmityEventOrderOption||(e.AmityEventOrderOption={})).Ascending="asc",ie.Descending="desc",e.AmitySharableContentType=void 0,(re=e.AmitySharableContentType||(e.AmitySharableContentType={})).POST="post",re.COMMUNITY="community",re.USER="user",re.LIVESTREAM="livestream",re.EVENT="event",e.AnalyticsSourceTypeEnum=void 0,(ce=e.AnalyticsSourceTypeEnum||(e.AnalyticsSourceTypeEnum={})).POST="post",ce.ROOM="room",e.UserNotificationModuleNameEnum=void 0,(de=e.UserNotificationModuleNameEnum||(e.UserNotificationModuleNameEnum={})).CHAT="chat",de.SOCIAL="social",de.VIDEO_STREAMING="video-streaming",e.CommunityNotificationEventNameEnum=void 0,(le=e.CommunityNotificationEventNameEnum||(e.CommunityNotificationEventNameEnum={})).POST_CREATED="post.created",le.POST_REACTED="post.reacted",le.COMMENT_CREATED="comment.created",le.COMMENT_REPLIED="comment.replied",le.COMMENT_REACTED="comment.reacted",le.STORY_CREATED="story.created",le.STORY_REACTED="story.reacted",le.STORY_COMMENT_CREATED="story-comment.created",le.LIVESTREAM_START="video-streaming.didStart",e.NotificationSettingsLevelEnum=void 0,(ue=e.NotificationSettingsLevelEnum||(e.NotificationSettingsLevelEnum={})).USER="user",ue.COMMUNITY="community",ue.CHANNEL="channel",e.NotificationRolesFilterTypeEnum=void 0,(he=e.NotificationRolesFilterTypeEnum||(e.NotificationRolesFilterTypeEnum={})).ALL="all",he.ONLY="only",e.AmityLiveViewerCountMode=void 0,(me=e.AmityLiveViewerCountMode||(e.AmityLiveViewerCountMode={})).ALWAYS_SHOW="always",me.HIDE_ENTIRELY="hidden",me.SHOW_ABOVE_MINIMUM="above-minimum";const ge=function(){try{return"v7.28.0-umd"}catch(e){return"__dev__"}}(),pe=5,ye=20,ve="cache_then_server",fe="For using Live Collection feature you need to enable Cache!",be="Observing unsynced object is not supported by Live Object.",Ie=-5,Ce=1e3,we=6e5,Se="/api/v1/feeds/for-you",Oe=e=>`/api/v3/communities/${encodeURIComponent(e)}/comments/review-queue`,Ae="dead",Te=6e4,Re=e=>JSON.stringify(e,((e,t)=>{return null!==t&&"object"==typeof t?(n=t,Object.keys(n).sort().reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:n[t]})),{})):t;var n})),Pe=e=>JSON.parse(e),ke=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>ke(e[n],t[n])))),De=e=>[400400,400300].includes(e),Ue=e=>["skip"].some((t=>t in e)),je=e=>["after","before","first","last","limit"].some((t=>t in e)),Ee=e=>"limit"in e,Me=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),qe=(e,n)=>{var a;if(!e||!Object.keys(e).length)return;let s={};return"skiplimit"===n?s={skip:null!==(a=e.after)&&void 0!==a?a:0,limit:e.limit}:"afterbefore"===n&&je(e)?((null==e?void 0:e.before)&&(s=Object.assign(Object.assign({},s),{before:e.before})),(null==e?void 0:e.after)&&(s=Object.assign(Object.assign({},s),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(s=Object.assign(Object.assign({},s),{limit:e.limit}))):"afterbeforeraw"===n&&(s=e),Object.keys(s).length?t.encode(JSON.stringify(s)):void 0},xe=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(Ue(n))return{after:n.skip,limit:n.limit};if(je(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},Ke=e=>"locally"in e,Ne=e=>"optimistically"in e,Fe=e=>Ke(e)||Ne(e),_e=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),Be=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},$e=(e,...t)=>({func:e,args:t}),Le=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<Te?Te:t},Qe=({func:e,args:t},n,a=Le("cache_then_server"))=>{let s;const{lifeSpan:o}=Le("cache_then_server",a.lifeSpan);if(Fe(e)){try{s=Ne(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(Ve(void 0,{origin:"local",loading:!1,error:e}))}const a=_e(s)&&Be(s,o);if(null==n||n(Ve(s,{origin:"local",loading:!(Ke(e)&&a)})),a)return}else null==n||n(Ve(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(Ve(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(Ve(void 0,{origin:"server",loading:!1,error:e}))}))};function Ve(e,t){return Me(e)||_e(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}class Je extends Error{constructor(e,t,n){super(`Amity SDK (${t}): ${e}`),this.code=t,this.level=n,this.type="ASC",this.timestamp=Date.now(),Error.captureStackTrace&&Error.captureStackTrace(this,Je)}}class He extends Je{constructor(e,t,n){super(e,t,n)}}class We extends Je{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class ze extends Je{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class Ge extends Je{constructor(e){super(e,800110,"error")}}let Ye=null;const Xe=()=>{if(!Ye)throw new Je("There is no active client",8e5,"fatal");return Ye},Ze=e=>{Ye=e},et={user:({userId:e})=>e,file:({fileId:e})=>e,role:({roleId:e})=>e,channel:({channelInternalId:e})=>e,subChannel:({subChannelId:e})=>e,channelUsers:({channelId:e,userId:t})=>`${e}#${t}`,archivedChannel:({channelId:e})=>e,message:({messageId:e,referenceId:t})=>null!=t?t:e,messagePreviewChannel:({channelId:e})=>`${e}`,messagePreviewSubChannel:({subChannelId:e})=>`${e}`,channelUnreadInfo:({channelId:e})=>e,subChannelUnreadInfo:({subChannelId:e})=>e,channelUnread:({channelId:e})=>e,channelMarker:({entityId:e,userId:t})=>`${e}#${t}`,subChannelMarker:({entityId:e,feedId:t,userId:n})=>`${e}#${t}#${n}`,messageMarker:({feedId:e,contentId:t,creatorId:n})=>`${e}#${t}#${n}`,feedMarker:({feedId:e,entityId:t})=>`${e}#${t}`,userMarker:({userId:e})=>e,community:({communityId:e})=>e,category:({categoryId:e})=>e,communityUsers:({communityId:e,userId:t})=>`${e}#${t}`,post:({postId:e})=>e,comment:({commentId:e})=>e,commentChildren:({commentId:e})=>e,poll:({pollId:e})=>e,reaction:({referenceType:e,referenceId:t})=>`${e}#${t}`,reactor:({reactionId:e})=>e,stream:({streamId:e})=>e,streamModeration:({streamId:e})=>e,follow:({from:e,to:t})=>`${e}#${t}`,followInfo:({userId:e})=>e,followCount:({userId:e})=>e,feed:({targetId:e,feedId:t})=>`${e}#${t}`,story:({referenceId:e})=>e,storyTarget:({targetId:e})=>e,ad:({adId:e})=>e,advertiser:({advertiserId:e})=>e,pin:({placement:e,referenceId:t})=>`${e}#${t}`,pinTarget:({targetId:e})=>e,notificationTrayItem:({_id:e})=>e,notificationTraySeen:({userId:e})=>e,invitation:({_id:e})=>e,joinRequest:({joinRequestId:e})=>e,room:({roomId:e})=>e,viewer:({userId:e})=>e,event:({eventId:e})=>e,eventResponse:({userId:e})=>e,product:({productId:e})=>e,feedMetadata:({postId:e})=>e},tt=e=>et[e],nt={users:"user",files:"file",roles:"role",stories:"story",storyTargets:"storyTarget",channels:"channel",messageFeeds:"subChannel",channelUsers:"channelUsers",archives:"archivedChannel",messages:"message",messagePreviewChannel:"messagePreviewChannel",messagePreviewSubChannel:"messagePreviewSubChannel",channelUnreadInfo:"channelUnreadInfo",subChannelUnreadInfo:"subChannelUnreadInfo",userEntityMarkers:"channelMarker",userFeedMarkers:"subChannelMarker",contentMarkers:"messageMarker",feedMarkers:"feedMarker",userMarkers:"userMarker",communities:"community",categories:"category",communityUsers:"communityUsers",posts:"post",postChildren:"post",comments:"comment",commentChildren:"comment",polls:"poll",reactors:"reactor",reactions:"reaction",videoStreamings:"stream",videoStreamingChildren:"stream",videoStreamModerations:"streamModeration",follows:"follow",followCounts:"followCount",feeds:"feed",ads:"ad",advertisers:"advertiser",pinTargets:"pinTarget",pins:"pin",notificationTrayItems:"notificationTrayItem",invitations:"invitation",joinRequests:"joinRequest",rooms:"room",events:"event",viewers:"viewer",eventResponses:"eventResponse",products:"product",feedMetadata:"feedMetadata"};function at(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}const st=e=>{const{log:t,cache:n}=Xe();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=Pe(t);return ke(e,n)})).map((e=>n.data[e]))},ot=e=>{const{log:t,cache:n}=Xe();if(!n)return;t("cache/api/pullFromCache",e);const a=Re(e);return n.data[a]?n.data[a]:void 0},it=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:s}=Xe();if(!s)return!1;a("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&s.persistIf&&(n.offline=s.persistIf(e,t));const o=Re(e);return s.data[o]=Object.assign({key:e,data:t},n),!0},rt=(e,t,n)=>{const{log:a,cache:s}=Xe();if(!s)return!1;a("cache/api/mergeInCache",{key:e,mutation:t});const o=ot(e);if(!o)return!1;const i="function"==typeof t?t(o.data):Object.assign(Object.assign({},o.data),t);return r=o.data,!("updatedAt"in(c=i)&&"updatedAt"in r&&new Date(c.updatedAt)<new Date(r.updatedAt))&&(it(e,i,n),!0);var r,c},ct=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:s}=Xe();if(!s)return!1;a("cache/api/upsertInCache",{key:e,data:t,options:n});return ot(e)?rt(e,t,n):it(e,t,n)},dt=(e,t=!1)=>{const{log:n,cache:a}=Xe();if(!a)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(a.data).map((e=>Pe(e))).filter((t=>ke(e,t))).map((e=>dt(e,!0))).every((e=>e));const s=Re(e);return s in a.data&&(delete a.data[s],!0)},lt=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,ut=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,ht=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,mt=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;if("community"===e.type)return!0;const s=tt("channelUsers")({channelId:e.channelPublicId,userId:n}),o=null===(a=ot(["channelUsers","get",s]))||void 0===a?void 0:a.data;return"member"===t?o&&"none"!==o.membership:!o||"none"===o.membership})),gt=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var a;const s=null===(a=ot(["feed","get",tt("feed")({targetId:e,feedId:n})]))||void 0===a?void 0:a.data;return s&&s.feedType===t})),pt=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;const s=tt("communityUsers")({communityId:e.communityId,userId:n}),o=null===(a=ot(["communityUsers","get",s]))||void 0===a?void 0:a.data;return"member"===t?o&&"member"===o.communityMembership:!o||"none"!==o.communityMembership})),yt=(e,t)=>e.reduce(((e,n)=>{var a;if(null==t?void 0:t.includes(n.dataType))return[...e,n];if(((null==n?void 0:n.children)||[]).length>0){const s=null===(a=ot(["post","get",n.children[0]]))||void 0===a?void 0:a.data;return(null==t?void 0:t.includes(null==s?void 0:s.dataType))?e:[...e,n]}return e}),[]),vt=(e,t)=>{const n=new RegExp(t,"i");return e.filter((e=>{var t;return!!e.userId.match(n)||e.user&&(null===(t=e.user.displayName)||void 0===t?void 0:t.match(n))}))},ft=()=>{var e;const{userId:t}=Xe(),n=new Set;return(null!==(e=st(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&(e.from===t||e.to===t))).forEach((e=>{n.add(e.from===t?e.to:e.from)})),n},bt=e=>{const t=ft();return 0===t.size?e:e.filter((e=>{var n,a;if(t.has(e.postedUserId))return!1;return!(null!==(a=null===(n=e.mentionees)||void 0===n?void 0:n.flatMap((e=>"user"===e.type?e.userIds:[])))&&void 0!==a?a:[]).some((e=>t.has(e)))}))},It=e=>{const t=ft();return 0===t.size?e:e.filter((e=>!t.has(e.userId)))},Ct=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,wt=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,St=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),Ot=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),At=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),Tt=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Rt=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),Pt=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf(),kt=e=>{if(void 0===e)return;const t=new Date(e).valueOf();if(!Number.isNaN(t))return e;console.warn("untilAt is an invalid Date — ignoring, pagination will not be bounded")},Dt=(e,t,n)=>{const a=new Date(e).valueOf(),s=new Date(t).valueOf();return"firstCreated"===n?a>=s:a<=s};let Ut=null;const jt=()=>{if(!Ut)throw new Je("Connect client first",8e5,"fatal");return Ut},Et=e=>{Ut={_id:e._id,userId:e.userId,path:e.path}};let Mt,qt=[];const xt=e=>{clearTimeout(Mt),qt.push(e),Mt=setTimeout((()=>{qt.forEach((e=>e())),qt=[]}),0)},Kt=["connect","message","disconnect","error","close","end","reconnect","video-streaming.didStart","video-streaming.didRecord","video-streaming.didStop","video-streaming.didFlag","video-streaming.didTerminate","video-streaming.viewerDidBan","video-streaming.viewerDidUnban","liveReaction.created"],Nt=(e,t,n,a)=>{const{log:s,emitter:o}=e,i=Date.now();s(`${t}(tmpid: ${i}) > listen`);const r=(...e)=>{s(`${t}(tmpid: ${i}) > trigger`,e);try{a(...e)}catch(e){s(`${t}(tmpid: ${i}) > error`,e)}};return o.on(n,r),()=>{s(`${t}(tmpid: ${i}) > dispose`),o.off(n,r)}},Ft=(e,t)=>{const{emitter:n}=Xe();xt((()=>{n.emit(e,t)}))};let _t,Bt;async function $t(){var e;const{mqtt:t,emitter:n,token:a}=Xe();if(!t)return;const s=null!==(e=null==a?void 0:a.accessToken)&&void 0!==e?e:"",o=jt();_t===s&&Bt===o._id||(_t=s,Bt=o._id,await t.connect({accessToken:_t,userId:Bt}),((e,t)=>{Kt.forEach((n=>{null==e||e.on(n,((...e)=>{t.emit(n,1===e.length?e[0]:e)}))})),e.on("message",((e,n)=>{const a=JSON.parse(n.toString());t.emit(a.eventType,a.data)}))})(t,n))}const Lt=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=ot(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),Qt=()=>{var e;const t=Xe();if(!t)throw new Je("Connect client first",8e5,"fatal");const n=null===(e=ot(["user","get",t.userId]))||void 0===e?void 0:e.data;return n?Lt(n):null};var Vt;e.SubscriptionLevels=void 0,(Vt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",Vt.POST="post",Vt.COMMENT="comment",Vt.POST_AND_COMMENT="post_and_comment",Vt.USER="user";const Jt=(e,t)=>{switch(t){case"post":return`${e}/post/+`;case"comment":return`${e}/post/+/comment/+`;case"post_and_comment":return`${e}/post/#`;default:return e}},Ht=e=>e.path.split("/user/")[0],Wt=()=>{const e=jt();return`${Ht(e)}/membership/${e._id}/+/+`},zt=()=>{const e=jt();return`${Ht(e)}/membership/+/${e._id}/+`},Gt=({channelId:e,subChannelId:t})=>{const n=jt();return`${Ht(n)}/marker/channel/${e}/message/${t}`},Yt=()=>Ht(jt()),Xt=()=>{const e=jt();return`${Ht(e)}/smartfeed/${e._id}/channels`},Zt=()=>{const e=jt();return`${Ht(e)}/smartfeed/${e._id}/messagefeeds`},en=()=>{const e=jt();return`${Ht(e)}/smartfeed/${e._id}/messages`},tn=()=>{const e=jt();return`${Ht(e)}/videostreaming`};function nn(e,t){const{mqtt:n}=Xe();return n?($t(),n.subscribe(e,t)):()=>null}var an;const sn="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:on={}}=sn,rn="production"===(null===(an=on.env)||void 0===an?void 0:an.NODE_ENV),cn={EU:"eu",SG:"sg",US:"us"},dn={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function ln(e,t){return dn[e].replace("{region}",t)}const un=()=>O.default.v4().toString(),hn=e=>{let t="";for(;t.length<2*e;)t+=un().replace(/-/g,"");return t.slice(0,2*e)};class mn{constructor(){this._listener=new Map}onNetworkActivities(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setNetworkActivities(e,t){this._listener.forEach((n=>n(e,t)))}destroy(){this._listener.clear()}}let gn;var pn,yn=()=>(gn||(gn=new mn),gn);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(pn||(pn={}));let vn=new AbortController;const fn=e=>{switch(e){case pn.UserGlobalBanned:throw new Je(e,400312,"fatal");case pn.UserDeleted:throw new Je(e,400100,"fatal");case pn.TokenExpired:throw Ft("tokenExpired","tokenExpired"),new Je(e,800403,"fatal");default:throw new Je("Request Aborted",8e5,"error")}};let bn=0;const In=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=w.default.create({baseURL:e,httpAgent:new S.default(t),httpsAgent:new o.HttpsAgent(t),signal:vn.signal});return n.defaults.withCredentials=!1,n.interceptors.request.use((e=>{if(e.headers.set("x-request-id",un()),e.headers.set("traceparent",`00-${hn(16)}-${hn(8)}-01`),"/api/v5/sessions"===e.url)return e;if(e.metadata){const{tokenExpiry:t,isGlobalBanned:n,isUserDeleted:a}=e.metadata;n&&(vn.abort(),fn(pn.UserGlobalBanned)),a&&(vn.abort(),fn(pn.UserDeleted))}return e})),n.interceptors.response.use((e=>{var t;const n=new Headers;Object.entries(e.headers).forEach((([e,t])=>{"string"==typeof t&&n.append(e,t)}));const a=(e.config.baseURL||"")+(e.config.url||""),s=null===(t=e.config.method)||void 0===t?void 0:t.toUpperCase(),o={method:s,headers:e.config.headers};return"GET"!==s&&"HEAD"!==s&&(o.body=e.config.data),yn().setNetworkActivities(new Request(a,o),{data:e.data,status:e.status,statusText:e.statusText,headers:n}),e}),(e=>{var t,n,a,s;const{response:o}=e;if(400100===(null==o?void 0:o.data.code)&&Ft("tokenTerminated","terminated"),400312===(null===(t=null==o?void 0:o.data)||void 0===t?void 0:t.code)&&Ft("user.didGlobalBan",{users:[],files:[]}),400323===(null===(n=null==o?void 0:o.data)||void 0===n?void 0:n.code))throw function(){const e=Date.now();e-bn<2e3||(bn=e,Ft("visitorUsageLimitReached",void 0))}(),new Je("Visitor usage limit exceeded",400323,"error");if((null===(a=null==o?void 0:o.data)||void 0===a?void 0:a.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new We(e.code);if("error"===e.status)throw new He(e.message,e.code,"error")})(null==o?void 0:o.data),vn.signal.aborted)throw e;throw new Error(null!==(s=null==o?void 0:o.data)&&void 0!==s?s:e)})),n.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},n};class Cn{constructor(){this._sessionState="notLoggedIn",this._listener=new Map}onSessionStateChange(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setSessionState(e,t){this._sessionState!==e&&(this._sessionState=e,this._listener.forEach((n=>n(e,t))))}destroy(){this._listener.clear()}}let wn;var Sn=()=>(wn||(wn=new Cn),wn);const On=e=>Sn().onSessionStateChange(e),An={[e.AmityAutoSubscription.NETWORK]:[Yt],[e.AmityAutoSubscription.CHAT]:[Xt,Zt,en],[e.AmityAutoSubscription.LIVESTREAM]:[tn],[e.AmityAutoSubscription.BLOCK]:[Wt,zt]},Tn=[e.AmityAutoSubscription.CHAT,e.AmityAutoSubscription.NETWORK,e.AmityAutoSubscription.LIVESTREAM,e.AmityAutoSubscription.BLOCK],Rn=Object.values(e.AmityAutoSubscription);class Pn{constructor(){this.refCountByFeature=new Map,this.disposers=new Map,this.seed()}seed(){this.refCountByFeature.clear(),Tn.forEach((e=>this.refCountByFeature.set(e,1)))}isActive(e){var t;return(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)>0}subscribeTopics(e){this.unsubscribeTopics(e),this.disposers.set(e,An[e].map((e=>nn(e()))))}unsubscribeTopics(e){var t;(null!==(t=this.disposers.get(e))&&void 0!==t?t:[]).forEach((e=>e())),this.disposers.delete(e)}initialize(){Rn.forEach((e=>{this.isActive(e)&&this.subscribeTopics(e)}))}subscribe(e){var t;const n=(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)+1;this.refCountByFeature.set(e,n),1===n&&this.subscribeTopics(e)}unsubscribe(e){var t;const n=Math.max(0,(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)-1);this.refCountByFeature.set(e,n),0===n&&this.unsubscribeTopics(e)}subscriptions(){return Rn.map((e=>({feature:e,isActive:this.isActive(e),isSystem:!0,topicCount:An[e].length})))}reset(){Rn.forEach((e=>this.unsubscribeTopics(e))),this.disposers.clear(),this.seed()}}let kn=null;const Dn=()=>(kn||(kn=new Pn),kn);class Un{constructor(){this.store={},this.store={}}clear(){this.store={}}getItem(e){return this.store[e]||null}setItem(e,t){this.store[e]=String(t)}removeItem(e){delete this.store[e]}get length(){return Object.keys(this.store).length}key(e){return Object.keys(this.store)[e]||null}}const jn=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new Un},En=async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await T.default.setItem(e,t),!0):new Promise((n=>{jn().localStorage.setItem(e,t),n(!0)})),Mn=async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){return await T.default.getItem(e)}return new Promise((t=>{t(jn().localStorage.getItem(e))}))};let qn=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=un(),t={},n=new BroadcastChannel("amity_ts_sdk");let a;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:s})=>{s.tabId!==e&&("startup"===s.type&&n.postMessage({type:"identify",tabId:e,tabIndex:qn}),"identify"===s.type&&void 0!==s.tabIndex&&s.tabId&&(t[s.tabId]=s.tabIndex,a||(a=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(qn=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const xn=async()=>{var e;const t=`${null!==(e=Xe().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await Mn(t);if(n)return n;const a=`ascWebSdk#${un()}`;return await En(t,a),a},Kn=()=>{var e;if(null===(e=on.versions)||void 0===e?void 0:e.node)return on.versions.node},Nn=()=>"undefined"!=typeof navigator&&!!navigator,Fn=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){return}},_n=()=>{var e;if(Nn())return null===(e=navigator.connection)||void 0===e?void 0:e.effectiveType},Bn=()=>{var e;return!!(null===(e=on.versions)||void 0===e?void 0:e.node)},$n=()=>{var e;let t;try{t=Xe()}catch(e){t=void 0}return Object.assign({kind:Bn()?"node":"web",model:Kn(),sdkVersion:ge,product:null!==(e=null==t?void 0:t.product)&&void 0!==e?e:"sdk",uikitVersion:null==t?void 0:t.uikitVersion,appId:null==t?void 0:t.appId,appVersion:null==t?void 0:t.appVersion,locale:Nn()?navigator.language:void 0,timezone:Fn(),networkType:_n()},(()=>{if(!Nn()||!navigator.userAgent)return{};const{os:e,browser:t,device:n}=new c.UAParser(navigator.userAgent).getResult(),a={};return e.name&&(a.osName=e.name),e.version&&(a.osVersion=e.version),t.name&&(a.browserName=t.name),t.version&&(a.browserVersion=t.version),"tablet"===n.type?a.deviceType="tablet":"mobile"===n.type?a.deviceType="mobile":a.deviceType="desktop",a})())},Ln=1e3;var Qn;!function(e){e[e.IDENTIFIER_REJECTED=2]="IDENTIFIER_REJECTED",e[e.CLIENT_IDENTIFIER_NOT_VALID=133]="CLIENT_IDENTIFIER_NOT_VALID",e[e.BAD_USERNAME_OR_PASSWORD=134]="BAD_USERNAME_OR_PASSWORD",e[e.NOT_AUTHORIZED=135]="NOT_AUTHORIZED"}(Qn||(Qn={}));const Vn=e=>{let t,n="disconnected";const a=new Set,s=e=>{n!==e&&(n=e,a.forEach((t=>{t(e)})))},o=new Map;function i(e,n,a){const s=(t,s)=>{var r;if(t||128===(null===(r=null==s?void 0:s[0])||void 0===r?void 0:r.qos))if(n<2){const t=Math.min(2**n*1e3,5e3);console.warn(`Failed to subscribe to topic ${e} (attempt ${n+1}/3). Retrying in ${t}ms.`);const s=setTimeout((()=>{i(e,n+1,a)}),t);o.set(e,{timer:s,callback:a})}else{o.delete(e);const n=t?new Je(t.message,8e5,"error"):new We(8e5,"error");console.warn(`Failed to subscribe to topic ${e} after 3 attempts`,n),null==a||a(n)}else o.delete(e),console.log(`Subscribed to topic ${e}`),null==a||a()};t?t.subscribe(e,{qos:0},s):s(new Error("No connection to broker"),[])}return{connect:async function(n){const a=await(async e=>`mqttjs_${await xn()}_${e}_${qn}`)(n.userId);return s("connecting"),t&&(s("disconnecting"),t.removeAllListeners(),t.on("error",(e=>{console.warn("MQTT discarded connection error:",null==e?void 0:e.message)})),t.end(!0)),t=A.default.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:5,reconnectPeriod:Ln,resubscribe:!0,keepalive:30,properties:{sessionExpiryInterval:1800}},e)}({username:n.userId,password:n.accessToken,clientId:a})),t.on("connect",(()=>{t.options.reconnectPeriod=Ln,s("connected"),Dn().initialize()})),t.on("error",(e=>{switch("code"in e?e.code:void 0){case 2:case 133:case 134:case 135:t.end(),s("disconnected")}})),t.on("reconnect",(()=>{s("reconnecting"),t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||Ln),8e3)})),t.on("close",(()=>{o.forEach((({timer:e})=>clearTimeout(e))),o.clear()})),new Promise((e=>t.once("connect",(()=>e()))))},async disconnect(e){if(this.connected)return(null==e?void 0:e.endSession)?new Promise((e=>null==t?void 0:t.end(!1,{reasonCode:0,properties:{sessionExpiryInterval:0}},(()=>e())))):new Promise((e=>null==t?void 0:t.end(!0,void 0,(()=>e()))))},reconnect:async()=>new Promise((e=>{null==t||t.reconnect(),e()})),listen:e=>(a.add(e),n&&e(n),()=>{a.delete(e)}),get connected(){return!!(null==t?void 0:t.connected)},on(e,n){null==t||t.on(e,n)},once(e,n){null==t||t.once(e,n)},off(e,n){void 0!==n?null==t||t.off(e,n):null==t||t.removeAllListeners(e)},removeAllListeners(){null==t||t.removeAllListeners()},subscribe(e,t){return i(e,0,t),()=>this.unsubscribe(e)},unsubscribe(e){var n;const a=o.get(e);if(void 0!==a){clearTimeout(a.timer),o.delete(e);const t=new Je("Subscription retry cancelled due to unsubscribe call",8e5,"error");null===(n=a.callback)||void 0===n||n.call(a,t)}null==t||t.unsubscribe(e)}}},Jn=async()=>{const e=Xe(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t},Hn=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,a])=>{const s=nt[e];if(!s)return;const o=tt(s);o&&a&&a.forEach((e=>{(n?it:ct)([s,"get",o(e)],e,t)}))}))},Wn=(e,t)=>{const{log:n,cache:a}=Xe(),s=[e,Ae,t],o={cachedAt:Date.now()};a&&(n("cache/api/pushToTombstone",{cacheKey:s,data:o}),dt([e,"get",t],!0),it(s,o))};function zn(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.indexOf(a)<0&&(n[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(a=Object.getOwnPropertySymbols(e);s<a.length;s++)t.indexOf(a[s])<0&&Object.prototype.propertyIsEnumerable.call(e,a[s])&&(n[a[s]]=e[a[s]])}return n}const Gn=(e,t="userId",n="user")=>{var a;return null!==(a=null==e?void 0:e.map((e=>((e,t="userId",n="user")=>e[n]?e:Object.assign({get[n](){var n;if(!Xe().cache)return;return(null===(n=ot(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==a?a:e},Yn=(e,t,n="userId",a="user")=>{const s=e,o=t,i=s[o],r=zn(s,["symbol"==typeof o?o:o+""]),c=Gn(i,n,a);return Object.assign(Object.assign({},r),{[t]:c})};function Xn(e){return e.map((e=>{var{isMentioned:t}=e,n=zn(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function Zn(e){return Xn(e)}function ea(e){return Xn(e)}const ta=e=>{var t,n;return null!==(n=null===(t=ot(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},na=e=>new Date(e).getTime(),aa=e=>{var t,n;return null!==(n=null===(t=ot(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},sa=e=>{var t;const n=e.messagePreviewId?aa(e.subChannelId):null,a=n?Object.assign(Object.assign({},n),{user:null===(t=ot(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:a})},oa=e=>{var t,n;const a={messagePreviewSubChannel:null!==(n=null===(t=e.messages)||void 0===t?void 0:t.map((t=>(t=>{var n;const a=null===(n=e.messageFeeds)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:o,messageId:i,creatorPublicId:r,data:c,dataType:d,isDeleted:l,segment:u,createdAt:h,updatedAt:m}=t;return{messagePreviewId:i,channelId:s,subChannelId:o,data:c,dataType:d,isDeleted:l,segment:u,creatorId:r,createdAt:h,updatedAt:m,subChannelName:null==a?void 0:a.name,subChannelUpdatedAt:null==a?void 0:a.updatedAt}})(t))))&&void 0!==n?n:[]};Hn(a)};function ia(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function ra(e,t,n){it(["subChannel","get",e],ia(t,n))}const ca=(e,t)=>{const{log:n,cache:a}=Xe(),s=[e,Ae,t];if(!a)return;n("cache/api/isInTombstone",s);const o=ot(s),{lifeSpan:i}=Le("cache_then_server",18e4);if(o&&Be(o.data,i))throw new He("Item not found!",400400,"error")},da=e=>{var t;const n=["channelUnreadInfo","get",e],a=null===(t=ot(n))||void 0===t?void 0:t.data,s=st(["subChannelUnreadInfo","get"]);let o=0,i=!1;if(s&&(null==s?void 0:s.length)>0){const t=null==s?void 0:s.filter((({data:t})=>t.channelId===e&&!t.isDeleted));o=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),i=t.some((({data:e})=>e.isMentioned))}const r=Object.assign(Object.assign({},null!=a?a:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:o,isMentioned:i});return it(n,r),r},la=e=>{const{feedMarkers:t,userFeedMarkers:n}=e;if(t.length>0&&n.length>0){const e=[],a=new Map(t.map((e=>[e.feedId,e])));n.forEach((t=>{const n=a.get(t.feedId);if(n&&n.feedId===t.feedId){const a=n.lastSegment-t.readToSegment,s={subChannelId:n.feedId,channelId:n.entityId,readToSegment:t.readToSegment,lastSegment:n.lastSegment,lastMentionSegment:t.lastMentionSegment,unreadCount:Math.max(0,a),isMentioned:t.isMentioned,isDeleted:n.isDeleted,createdAt:t.createdAt,updatedAt:t.updatedAt};Hn({subChannelUnreadInfo:[s]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{da(e)}))}},ua=async()=>{const e=Xe();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:n}=t,a=e.cache&&Date.now();e.cache&&Hn({userMarkers:n},{cachedAt:a}),Ft("local.userMarker.fetched",{userMarkers:n});return{data:n.reduce(((e,t)=>null==e||new Date(e.lastSyncAt).getTime()<new Date(t.lastSyncAt).getTime()?t:e),void 0),cachedAt:a}},ha=e=>{var t,n;const a=null===(t=ot(["message","get",e]))||void 0===t?void 0:t.data;if(a)return a;const s=st(["message","get"]);return null===(n=null==s?void 0:s.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data},ma=e=>!0===e&&void 0;function ga(e,t,n){var a,s;if(n)return n.hasMentioned;const o=Xe();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(a=ot(["subChannelUnreadInfo","get",t]))||void 0===a?void 0:a.data;return!!e&&e.isMentioned}const i={entityId:e,feedId:t,userId:jt()._id},r=null===(s=ot(["subChannelMarker","get",tt("subChannelMarker")(i)]))||void 0===s?void 0:s.data;return!!r&&r.hasMentioned}const pa=["broadcast","conversation","community"],ya=({channelType:e})=>pa.includes(e);function va(e){var{channelId:t,channelPublicId:n,channelType:a,childCount:s,creatorId:o,creatorPublicId:i,lastMessageId:r,lastMessageTimestamp:c,messageFeedId:d,name:l}=e,u=zn(e,["channelId","channelPublicId","channelType","childCount","creatorId","creatorPublicId","lastMessageId","lastMessageTimestamp","messageFeedId","name"]);return Object.assign(Object.assign({get unreadCount(){return function(e,t,n){var a,s;if(n)return n.unreadCount;const o=Xe();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(a=ot(["subChannelUnreadInfo","get",t]))||void 0===a?void 0:a.data;return e?e.isDeleted?0:e.unreadCount:0}const i={entityId:e,feedId:t,userId:jt()._id},r=null===(s=ot(["subChannelMarker","get",tt("subChannelMarker")(i)]))||void 0===s?void 0:s.data;return r?r.unreadCount:0}(t,d)},get hasMentioned(){return ga(t,d)},get isMentioned(){return ga(t,d)}},u),{channelId:n,creatorId:i,displayName:l,lastActivity:c,latestMessageId:r,messageCount:s,subChannelId:d,isUnreadCountSupport:ya({channelType:a})})}function fa(e,t,n){var a;const s=(e=>{var t,n,a;const s=null===(n=null===(t=st(["message","get"]))||void 0===t?void 0:t.find((({data:t})=>t.messageId===e.messageId)))||void 0===n?void 0:n.data;return s?Object.assign(Object.assign(Object.assign({},s),e),{referenceId:null!==(a=s.referenceId)&&void 0!==a?a:e.referenceId}):e})(e),{channelPublicId:o,childCount:i,creatorPublicId:r,mentionedUsers:c,messageFeedId:d,myReactions:l,reactionCount:u,reactions:h,referenceId:m,segment:g,messageId:p,creatorId:y}=s,v=zn(s,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let f;m&&(f=ot(["message","get",m])),f||(f=ot(["message","get",p]));const b=Object.assign(Object.assign({},v),{messageId:p,channelId:o,channelSegment:g,childrenNumber:i,creatorId:r,creatorPrivateId:e.creatorId,reactions:null!=h?h:{},myReactions:l||(null!==(a=null==f?void 0:f.data.myReactions)&&void 0!==a?a:[]),reactionsCount:u,subChannelId:d,uniqueId:f?f.data.uniqueId:p,referenceId:m,syncState:"synced"});return c&&(b.mentionees=c.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&n&&((e,t,n)=>{const a=Xe(),s=ha(e.messageId),o=(null==s?void 0:s.myReactions)||[];Object.assign(e,{myReactions:o});const i=t[0];i&&i.userId===a.userId&&("message.reactionAdded"!==n||o.includes(i.reactionName)||Object.assign(e,{myReactions:[...o,i.reactionName]}),"message.reactionRemoved"===n&&o.includes(i.reactionName)&&Object.assign(e,{myReactions:o.filter((e=>e!==i.reactionName))}))})(b,t,n),b}const ba={},Ia=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Hn({messages:(a=e).messages.map((e=>fa(e,a.reactions)))});const t=n.join("");ba[t]&&clearTimeout(ba[t]),ba[t]=setTimeout((()=>{try{(async e=>{const t=Xe();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:a,feedMarkers:s,userMarkers:o}=n,i=t.cache&&Date.now();t.cache&&Hn({contentMarkers:a,feedMarkers:s,userMarkers:o},{cachedAt:i}),Ft("local.feedMarker.fetched",{feedMarkers:s}),Ft("local.messageMarker.fetched",{contentMarkers:a}),Ft("local.userMarker.fetched",{userMarkers:o})})(n)}catch(e){}}),2e3)}var a;const{messageFeeds:s}=e,o=zn(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,n;const a=null!==(n=null===(t=ot(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},s=zn(va(e),["unreadCount","isMentioned"]);ra(e.messageFeedId,a,s)}))),Object.assign(Object.assign({},o),{messages:e.messages.map((n=>fa(n,e.reactions,t)))})};function Ca(e){var{subChannelId:t,mentionees:n,dataType:a,data:s}=e,o=zn(e,["subChannelId","mentionees","dataType","data"]);return a===$.IMAGE||a===$.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:a,data:Object.assign({caption:""},s)},o):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:a,data:s},o)}function wa(e){var{sortBy:t,subChannelId:n,includingTags:a,excludingTags:s,includeDeleted:o,aroundMessageId:i,limit:r,type:c}=e,d=zn(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const l=Object.assign(Object.assign({},d),{messageFeedId:n,isDeleted:ma(o),options:{sortBy:t,limit:r||pe,around:i}});return a&&(l.includeTags=a),c&&(l.dataType=c),s&&(l.excludeTags=s),l}function Sa(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const Oa=["broadcast","conversation","community"],Aa=({channelType:e})=>Oa.includes(e),Ta=async e=>{const t=e.messageFeeds.filter(Aa).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Hn({messageFeeds:e.messageFeeds.map((e=>va(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=Xe();n.log("channel/getSubChannelMarkers",e,t);const{data:a}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:qe(t,"skiplimit")}}}),{paging:s}=a,o=zn(a,["paging"]),{userEntityMarkers:i,userFeedMarkers:r,userMarkers:c,feedMarkers:d}=o;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&la({feedMarkers:d,userFeedMarkers:r});const l=Zn(i),u=ea(r),h=n.cache&&Date.now();n.cache&&Hn({userEntityMarkers:l,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),Ft("local.channelMarker.fetched",{userEntityMarkers:l}),Ft("local.subChannelMarker.fetched",{userFeedMarkers:u}),Ft("local.userMarker.fetched",{userMarkers:c});const m=xe(s.next);return{data:u,cachedAt:h,prevPage:xe(s.previous),nextPage:m}})(t)}catch(e){}}oa(e);const n=e.messageFeeds.map(va),a=e.messages.map((e=>fa(e))),s=e.users.map(Sa);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:a,users:s})};const Ra=async e=>{const t=Xe();t.log("channel/getSubChannel",e),ca("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),a=await Ta(n.data),s=t.cache&&Date.now();return t.cache&&Hn(a,{cachedAt:s}),Ft("local.message-feed.fetched",a),{data:a.messageFeeds[0],cachedAt:s}}catch(t){throw De(null==t?void 0:t.code)&&Wn("subChannel",e),t}};Ra.locally=e=>{const t=Xe();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=ot(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Pa=async e=>{var t;let n=null===(t=ot(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await Ra(e)).data),n},ka=async e=>{const t=await(async()=>Xe().getMessagePreviewSetting(!1))(),{channelId:n,messageId:a,creatorId:s,createdAt:o,updatedAt:i,data:r,dataType:c,subChannelId:d,channelSegment:l,isDeleted:u}=e,h=await Pa(d);"no-message-preview"!==t?(e=>{var t;const n=null===(t=ot(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||na(n.createdAt)<=na(e.createdAt)})(e)&&(it(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:s,messagePreviewId:a,createdAt:o,updatedAt:i,subChannelId:d,data:r,dataType:c,segment:l,isDeleted:u,subChannelUpdatedAt:null==h?void 0:h.updatedAt,subChannelName:null==h?void 0:h.displayName}),ra(e.subChannelId,h,{lastActivity:o,messagePreviewId:a})):na(h.lastActivity)<na(o)&&ra(e.subChannelId,h,{lastActivity:o})},Da=async e=>{var t;const{channelId:n,messageId:a,creatorId:s,createdAt:o,updatedAt:i,data:r,dataType:c,subChannelId:d,channelSegment:l,isDeleted:u}=e,h=null===(t=ot(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Pa(d);it(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:s,messagePreviewId:a,createdAt:o,updatedAt:i,subChannelId:d,data:r,dataType:c,segment:l,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Ua=async e=>{const{channelId:t,messageId:n,creatorId:a,createdAt:s,updatedAt:o,data:i,dataType:r,subChannelId:c,channelSegment:d,isDeleted:l}=e;if((e=>{var t;const n=null===(t=ot(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||na(n.createdAt)<=na(e.createdAt)})(e)){const u=await Pa(c);it(["messagePreviewChannel","get",e.channelId],{channelId:t,creatorId:a,messagePreviewId:n,createdAt:s,updatedAt:o,subChannelId:c,data:i,dataType:r,segment:d,isDeleted:l,subChannelUpdatedAt:null==u?void 0:u.updatedAt,subChannelName:null==u?void 0:u.displayName})}},ja=async e=>{var t;const{channelId:n,messageId:a,creatorId:s,createdAt:o,updatedAt:i,data:r,dataType:c,subChannelId:d,channelSegment:l,isDeleted:u}=e,h=null===(t=ot(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Pa(d);it(["messagePreviewChannel","get",e.channelId],{channelId:n,creatorId:s,messagePreviewId:a,createdAt:o,updatedAt:i,subChannelId:d,data:r,dataType:c,segment:l,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Ea=async e=>{var t,n,a,s;const{channelId:o,subChannelId:i}=e,r=null===(t=ot(["messagePreviewChannel","get",o]))||void 0===t?void 0:t.data;if((null==r?void 0:r.subChannelId)===i){const e=null===(n=ot(["subChannel","get",i]))||void 0===n?void 0:n.data;it(["messagePreviewChannel","get",o],Object.assign(Object.assign({},r),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const c=null===(a=ot(["messagePreviewSubChannel","get",i]))||void 0===a?void 0:a.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(s=ot(["subChannel","get",i]))||void 0===s?void 0:s.data;it(["messagePreviewSubChannel","get",i],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Ma=["broadcast","conversation","community"],qa=({type:e})=>Ma.includes(e);function xa(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:a}=e;const s=null===(n=ot(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==s?void 0:s.messagePreviewId)&&!t.isMessagePreviewUpdated&&(a=s.messagePreviewId),Object.assign(Object.assign({},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:qa(e),messagePreviewId:a})}const Ka=(e,t={isMessagePreviewUpdated:!0})=>{Hn({channels:e.channels.map((e=>xa(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Na=async(e,t={isMessagePreviewUpdated:!0})=>{const n=Xe(),a=await n.getMessagePreviewSetting(!1);if(t.isMessagePreviewUpdated&&"no-message-preview"!==a&&e.messagePreviews&&e.messagePreviews.length>0&&(e=>{var t;const n=(null!==(t=e.messagePreviews)&&void 0!==t?t:[]).map((t=>{var n;const a=null===(n=e.messageFeedsInfo)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:o,data:i,dataType:r,isDeleted:c,segment:d,creatorPublicId:l,createdAt:u,updatedAt:h}=t;return{channelId:s,subChannelId:o,data:i,dataType:r,isDeleted:c,segment:d,creatorId:l,createdAt:u,updatedAt:h,subChannelName:null==a?void 0:a.name,messagePreviewId:null==a?void 0:a.messagePreviewId,subChannelUpdatedAt:null==a?void 0:a.updatedAt}})).filter((e=>{var t;const n=null===(t=ot(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||na(n.createdAt)<=na(e.createdAt)}));0!==n.length&&Hn({messagePreviewChannel:n})})(e),n.useLegacyUnreadCount)(({currentUserId:e,channels:t,channelUsers:n})=>{var a,s;const o=[];for(let i=0;i<t.length;i+=1)if(qa(t[i])){const r=["channelUnread","get",t[i].channelId],c=n.find((n=>n.channelId===t[i].channelId&&n.userId===e)),d=null===(a=ot(r))||void 0===a?void 0:a.data,l=Math.max(null!==(s=null==d?void 0:d.lastSegment)&&void 0!==s?s:0,t[i].messageCount);let u=null,h=null,m=0,g=!1;if(c){const e=c.readToSegment,t=c.lastMentionedSegment;u="number"==typeof(null==d?void 0:d.readToSegment)&&("number"!=typeof e||d.readToSegment>e)?d.readToSegment:null!=e?e:null,h="number"==typeof(null==d?void 0:d.lastMentionedSegment)&&("number"!=typeof t||d.lastMentionedSegment>t)?d.lastMentionedSegment:null!=t?t:null;const n=null!=u?u:0;m=Math.max(l-n,0),g="number"==typeof h&&n<h}const p={channelId:t[i].channelId,lastSegment:l,readToSegment:u,lastMentionedSegment:h,unreadCount:m,isMentioned:g,isDeleted:t[i].isDeleted||!1};it(r,p),o.push(p)}o.length>0&&Ft("local.channelUnread.updated",o)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(qa).map((({channelInternalId:e})=>e));if(n.length>0){Ka(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=Xe();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:a,userMarkers:s}=n,o=Zn(a),i=t.cache&&Date.now();return t.cache&&Hn({userEntityMarkers:o,userMarkers:s},{cachedAt:i}),Ft("local.channelMarker.fetched",{userEntityMarkers:o}),Ft("local.userMarker.fetched",{userMarkers:s}),{data:o,cachedAt:i}})(n)}catch(e){}}}const s=e.channels.map((e=>xa(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),o=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(Xe().cache)return(null===(e=ot(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),i=e.users.map(Sa),r=zn(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},r),{users:i,channels:s,channelUsers:o})},Fa=e=>{var t,n,a;if(!e)return;const s=null===(t=ot(["channel","get",e]))||void 0===t?void 0:t.data;return s||(null===(a=null===(n=st(["channel","get"]))||void 0===n?void 0:n.find((({data:t})=>t.channelInternalId===e||t.channelPublicId===e||t.channelId===e)))||void 0===a?void 0:a.data)},_a=e=>{var t,n;return null!==(n=Fa(null===(t=e.pinnedMessage)||void 0===t?void 0:t.channelId))&&void 0!==n?n:Fa(e.channelId)},Ba=(e,t,n)=>{n&&n.length>0&&Hn({users:n.map(Sa)});const a=Object.assign(Object.assign({},e),{pinnedMessage:t});return it((e=>["channel","get",tt("channel")(e)])(e),a),a},$a=e=>{var t,n,a;const{channelId:s,users:o=[],channels:i=[]}=e,r=null!==(t=i.find((e=>e.channelId===s)))&&void 0!==t?t:i[0];let c;if(r){const e=["channel","get",tt("channel")(r)],t=xa(r,{isMessagePreviewUpdated:!1});ct(e,t),c=null!==(a=null===(n=ot(e))||void 0===n?void 0:n.data)&&void 0!==a?a:t}const d=[];return o.forEach((({userId:e,roles:t,permissions:n})=>{var a,o,i;const r=["channelUsers","get",tt("channelUsers")({channelId:s,userId:e})],c=null===(a=ot(r))||void 0===a?void 0:a.data;if(!c)return;const l=Object.assign(Object.assign({},c),{roles:t,permissions:n});it(r,l),d.push(null!==(i=null===(o=ot(r))||void 0===o?void 0:o.data)&&void 0!==i?i:l)})),{channel:c,members:d}},La=async e=>{const t=Xe();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return Ft("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},Qa=async e=>{const t=Xe(),n=await La(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:a,userFeedMarkers:s}=n;la({feedMarkers:a,userFeedMarkers:s}),t.log("channel/prepareUnreadCountInfo",e.channels)},Va=(e,t)=>{var n,a,s,o;const i=Xe();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=ot(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===n?void 0:n.isMentioned)&&void 0!==a&&a:void 0!==(null==t?void 0:t.hasMentioned)?null==t?void 0:t.hasMentioned:null!==(o=null===(s=(e=>{var t;const n={entityId:e,userId:jt()._id};return null===(t=ot(["channelMarker","get",tt("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===s?void 0:s.hasMentioned)&&void 0!==o&&o},Ja=(e,t)=>{var n,a,s,o,i;const r=Xe();return r.isUnreadCountEnabled&&r.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=ot(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===n?void 0:n.unreadCount)&&void 0!==a?a:0:(null==t?void 0:t.isDeleted)?0:null!==(i=null!==(s=null==t?void 0:t.unreadCount)&&void 0!==s?s:null===(o=(e=>{var t;const n={entityId:e,userId:jt()._id};return null===(t=ot(["channelMarker","get",tt("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===o?void 0:o.unreadCount)&&void 0!==i?i:0},Ha=e=>{var t;return null===(t=ot(["channelUnread","get",e]))||void 0===t?void 0:t.data},Wa=e=>{const t=Xe(),n=zn(e,["messageCount"]);return ia(n,{get unreadCount(){var e,t;return null!==(t=null===(e=Ha(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Ja(n)},get isMentioned(){var e,a;return t.useLegacyUnreadCount?null!==(a=null===(e=Ha(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==a&&a:Va(n)}})},za=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],a=null===(t=ot(n))||void 0===t?void 0:t.data;return a?Lt(a):void 0})()}});function Ga(e,t){if(null==e||null==t)return e===t;if(e.constructor!==t.constructor)return!1;if(e instanceof Function)return e===t;if(e instanceof RegExp)return e===t;if(e===t||e.valueOf()===t.valueOf())return!0;if(Array.isArray(e)&&e.length!==t.length)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Ga(e[n],t[n]))return!1;return!0}if(e instanceof Date)return!1;if(!(e instanceof Object))return!1;if(!(t instanceof Object))return!1;const n=Object.keys(e);return Object.keys(t).every((e=>-1!==n.indexOf(e)))&&n.every((n=>Ga(e[n],t[n])))}const Ya=e=>{const t=Xe();t.log("channel/getMyMembership.locally");const n=ot(["channelUsers","get",`${e}#${t.userId}`]);if(!n)throw new He("Item not found!",400400,"error");return{data:n.data,cachedAt:n.cachedAt}},Xa=[];let Za=null;const es=e=>{if(0===Xa.length){const e=Xe();Za=Nt(e,"onChannelCreated","channel.created",(async e=>{const t=await Na(e);Hn(t),Xa.forEach((e=>e(t.channels[0])))}))}return Xa.push(e),()=>(e=>{const t=Xa.indexOf(e);t>-1&&Xa.splice(t,1),0===Xa.length&&(null==Za||Za())})(e)},ts=[],ns=[],as=e=>{const t=Xe();if(0===ts.length){const e=async e=>{const t=await Na(e);Hn(t),ts.forEach((e=>e(t.channels[0])))};ns.push(Nt(t,"onChannelUpdated","channel.updated",e)),ns.push(Nt(t,"onChannelUpdated","local.channel.updated",(e=>ts.forEach((t=>t(e.channels[0]))))))}return ts.push(e),()=>(e=>{const t=ts.indexOf(e);t>-1&&ts.splice(t,1),0===ts.length&&ns.forEach((e=>e()))})(e)},ss=e=>{const t=st(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{it(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},os=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=ot(n))||void 0===t?void 0:t.data)&&dt(n)},is=[];let rs=null;const cs=e=>{if(0===is.length){const e=Xe(),t=async t=>{const n=await Na(t),a=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,s=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(a)ss(e.channelId),os(e.channelId);else if(s){const t=["channelUnread","get",e.channelId],n=ot(t);n&&it(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Hn(n),is.forEach((e=>e(n.channels[0])))};rs=Nt(e,"onChannelDeleted","channel.deleted",t)}return is.push(e),()=>(e=>{const t=is.indexOf(e);t>-1&&is.splice(t,1),0===is.length&&(null==rs||rs())})(e)},ds=[];let ls=null;const us=e=>{if(0===ds.length){const e=Xe();ls=Nt(e,"onChannelJoined","channel.joined",(async e=>{const t=await Na(e),{channels:n,channelUsers:a}=t;Hn(t),ds.forEach((e=>e(n[0],a[0])))}))}return ds.push(e),()=>(e=>{const t=ds.indexOf(e);t>-1&&ds.splice(t,1),0===ds.length&&(null==ls||ls())})(e)},hs=[];let ms=null;const gs=e=>{if(0===hs.length){const e=Xe(),t=async t=>{const{userId:n}=Xe(),{channelUsers:a}=t,s=a.some((e=>e.userId===n)),o=await Na(t,{isMessagePreviewUpdated:s}),i=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,r=e.useLegacyUnreadCount;s&&o.channels.forEach((e=>{i?(ss(e.channelId),os(e.channelId)):r&&dt(["channelUnread","get",e.channelId])}));const{channels:c,channelUsers:d}=o;Hn(o),hs.forEach((e=>e(c[0],d[0])))};ms=Nt(e,"onChannelLeft","channel.left",t)}return hs.push(e),()=>(e=>{const t=hs.indexOf(e);t>-1&&hs.splice(t,1),0===hs.length&&(null==ms||ms())})(e)},ps=[];let ys=null;const vs=e=>{if(0===ps.length){const e=Xe(),t=async e=>{var t;ct(["channel","get",e.channelId],{isMuted:Date.parse(e.muteTimeout)>Date.now()});const n=null===(t=ot(["channel","get",e.channelId]))||void 0===t?void 0:t.data;n&&ps.forEach((e=>e(n)))};ys=Nt(e,"onChannelMute","channel.setMuted",t)}return ps.push(e),()=>(e=>{const t=ps.indexOf(e);t>-1&&ps.splice(t,1),0===ps.length&&(null==ys||ys())})(e)},fs=[];let bs=null;const Is=e=>{if(0===fs.length){const e=Xe(),t=e=>{var t;const n=_a(e);if(!n)return;const a=Ba(n,null!==(t=e.pinnedMessage)&&void 0!==t?t:null,e.users);fs.forEach((e=>e(a)))};bs=Nt(e,"onChannelMessagePinned","channel.messagePinned",t)}return fs.push(e),()=>(e=>{const t=fs.indexOf(e);t>-1&&fs.splice(t,1),0===fs.length&&(null==bs||bs())})(e)},Cs=[];let ws=null;const Ss=e=>{if(0===Cs.length){const e=Xe();ws=Nt(e,"onChannelMessageUnpinned","channel.messageUnpinned",(e=>{const t=_a(e);if(!t)return;const n=Ba(t,null);Cs.forEach((e=>e(n)))}))}return Cs.push(e),()=>(e=>{const t=Cs.indexOf(e);t>-1&&Cs.splice(t,1),0===Cs.length&&(null==ws||ws())})(e)},Os=[];let As=null;const Ts=e=>{if(0===Os.length){const e=Xe();As=Nt(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await Na(e),{channels:n,channelUsers:a}=t;Hn(t),Os.forEach((e=>e(n[0],a.find((e=>"member"===e.membership)))))}))}return Os.push(e),()=>(e=>{const t=Os.indexOf(e);t>-1&&Os.splice(t,1),0===Os.length&&(null==As||As())})(e)},Rs=[];let Ps=null;const ks=e=>{if(0===Rs.length){const e=Xe();Ps=Nt(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await Na(e),{channels:n,channelUsers:a}=t;Hn(t),Rs.forEach((e=>e(n[0],a[0])))}))}return Rs.push(e),()=>(e=>{const t=Rs.indexOf(e);t>-1&&Rs.splice(t,1),0===Rs.length&&(null==Ps||Ps())})(e)},Ds=[];let Us=null;const js=e=>{const t=Xe();return Us=Nt(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await Na(e),{channels:a,channelUsers:s}=n,o=s.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&o&&n.channels.forEach((e=>{ss(e.channelId),os(e.channelId)})),Hn(n),Ds.forEach((e=>e(a[0],s.find((e=>"banned"===e.membership)))))})),Ds.push(e),()=>(e=>{const t=Ds.indexOf(e);t>-1&&Ds.splice(t,1),0===Ds.length&&(null==Us||Us())})(e)},Es=[];let Ms=null;const qs=e=>{if(0===Es.length){const e=Xe();Ms=Nt(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await Na(e),{channels:n,channelUsers:a}=t;Hn(t),Es.forEach((e=>e(n[0],a.find((e=>"none"===e.membership)))))}))}return Es.push(e),()=>(e=>{const t=Es.indexOf(e);t>-1&&Es.splice(t,1),0===Es.length&&(null==Ms||Ms())})(e)},xs=[],Ks=[],Ns=e=>{if(0===xs.length){const e=Xe(),t=async e=>{const{channels:t,channelUsers:n}=e;xs.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))},n=e=>{const{channel:t,members:n}=$a(e);t&&n.forEach((e=>xs.forEach((n=>n(t,e)))))};Ks.push(Nt(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",t)),Ks.push(Nt(e,"onChannelMemberRoleAdded","channel.roleAdded",n))}return xs.push(e),()=>(e=>{const t=xs.indexOf(e);t>-1&&xs.splice(t,1),0===xs.length&&(Ks.forEach((e=>e())),Ks.length=0)})(e)},Fs=[],_s=[],Bs=e=>{if(0===Fs.length){const e=Xe(),t=async e=>{const{channels:t,channelUsers:n}=e;Fs.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))},n=e=>{const{channel:t,members:n}=$a(e);t&&n.forEach((e=>Fs.forEach((n=>n(t,e)))))};_s.push(Nt(e,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",t)),_s.push(Nt(e,"onChannelMemberRoleRemoved","channel.roleRemoved",n))}return Fs.push(e),()=>(e=>{const t=Fs.indexOf(e);t>-1&&Fs.splice(t,1),0===Fs.length&&(_s.forEach((e=>e())),_s.length=0)})(e)},$s=e=>{const t=Xe();return Nt(t,"onChannelArchived","local.channel.archived",(async t=>{e(t)}))},Ls=e=>{const t=Xe();return Nt(t,"onChannelUnarchived","local.channel.unarchived",(async t=>{e(t)}))},Qs=[];let Vs=null;const Js=e=>{if(0===Qs.length){const e=Xe(),t=async e=>{var t,n,a;e.userIds.forEach((t=>ct(["channelUsers","get",`${e.channelId}#${t}`],{isMuted:Date.parse(e.muteTimeout)>Date.now()})));const s=null===(n=null===(t=st(["channel","get"]))||void 0===t?void 0:t.find((({data:t})=>t.channelPublicId===e.channelId)))||void 0===n?void 0:n.data,o=null===(a=ot(["channelUsers","get",`${e.channelId}#${e.userIds[0]}`]))||void 0===a?void 0:a.data;s&&o&&Qs.forEach((e=>e(s,o)))};Vs=Nt(e,"onChannelUserMute","channel.setMutedUsers",t)}return Qs.push(e),()=>(e=>{const t=Qs.indexOf(e);t>-1&&Qs.splice(t,1),0===Qs.length&&(null==Vs||Vs())})(e)},Hs=e=>{var t;let n=[];if(["conversation","community"].includes(e.type)){const a=st(["channelUsers","get"]);a&&(null==a?void 0:a.length)>0&&(n=(null!==(t=null==a?void 0:a.filter((({data:t})=>t.channelId===e.channelId&&"none"!==t.membership)))&&void 0!==t?t:[]).sort(((e,t)=>e.data.userInternalId.localeCompare(t.data.userInternalId))).slice(0,4).map((({data:e})=>za(e))))}return ia(e,{markAsRead:()=>(async e=>{const t=Xe();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:a,userEntityMarkers:s,userFeedMarkers:o}=n,i=zn(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),r=t.cache&&Date.now(),c=Zn(s),d=ea(o);return t.cache&&Hn(Object.assign({userMarkers:a,userEntityMarkers:c,userFeedMarkers:d},i),{cachedAt:r}),Ft("local.channelMarker.updated",{userEntityMarkers:c}),Ft("local.subChannelMarker.updated",{userFeedMarkers:d}),!0})(e.channelInternalId),previewMembers:n,myMembership:t=>((e,t)=>{const{_id:n}=jt();if(!n)throw new Je("The _id has not been defined in ActiveUser",8e5,"error");const{log:a,cache:s}=Xe();s||console.log("This observable object need the cache data!"),a(`liveMymembership(tmpid: ${Date.now()}) > listen`);const o=[];let i=!1;const r=e=>{t(Object.assign(Object.assign({},e),{data:e.data?za(e.data):e.data}))},c=(t,n)=>{const{data:a}=Ya(e);Ga(void 0,a)||r({loading:!1,data:a})};return o.push(js(c)),o.push(qs(c)),o.push(Js(c)),o.push(Ns(c)),o.push(Bs(c)),(()=>{const t=$e((async()=>Ya(e)));Qe(t,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{s===Ie?(r({data:t,origin:a,loading:!1,error:new He(be,800800,"error")}),i=!0,o.forEach((e=>e()))):i||r({loading:n,data:t,origin:a,error:e}),e&&o.forEach((e=>e()))}))})(),()=>{o.forEach((e=>e()))}})(e.channelId,t),get avatar(){var t;if(!e.avatarFileId)return;return null===(t=ot(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}})},Ws=e=>Hs(Wa((e=>{var t;const n=e.messagePreviewId?ta(e.channelId):null,a=null===(t=ot(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,s=n?Object.assign(Object.assign({},n),{user:a?Lt(a):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})})(e))),zs=async e=>{const t=Xe();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{De(null==t?void 0:t.code)&&Wn("channel",e)})),t}const s=await Na(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Qa(a);const o=t.cache&&Date.now();return t.cache&&Hn(s,{cachedAt:o}),Ft("local.channel.fetched",s.channels),{data:s.channels.map((e=>Ws(e))),cachedAt:o}};zs.locally=e=>{var t,n;const a=Xe();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const s=null===(t=st(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;const o=s.map((({data:e})=>e)),i=null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:o.map((e=>Ws(e))),cachedAt:i.cachedAt}};const Gs=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let Ys=!1;const Xs={},Zs=async()=>{const e=Object.entries(Xs).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=Xe();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:a,userFeedMarkers:s,feedMarkers:o,userMarkers:i}=n,r=Zn(a),c=ea(s),d=t.cache&&Date.now();return t.cache&&Hn({userEntityMarkers:r,userFeedMarkers:c,feedMarkers:o,userMarkers:i},{cachedAt:d}),Ft("local.feedMarker.fetched",{feedMarkers:o}),Ft("local.channelMarker.fetched",{userEntityMarkers:r}),Ft("local.subChannelMarker.fetched",{userFeedMarkers:c}),Ft("local.userMarker.fetched",{userMarkers:i}),!0})(e)},eo=()=>{Ys=!1},to=()=>(Ys=!0,On((e=>{"notLoggedIn"===e&&eo()})),()=>{eo()});Gs((async()=>{Ys&&await Zs()}),3e4);const no=async e=>{const t=Xe();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),a=await Ta(n.data),s=t.cache&&Date.now();return t.cache&&Hn(a,{cachedAt:s}),Ft("local.message-feed.fetched",a),{data:a.messageFeeds,cachedAt:s}};no.locally=e=>{var t;const n=Xe();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const a=e.map((e=>ot(["subChannel","get",e]))).filter(Boolean);if((null==a?void 0:a.length)<e.length)return;return{data:a.map((({data:e})=>e)),cachedAt:(null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const ao=async(e=!0)=>{var t;const n=null===(t=ot(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const a=await Jn();var s;return(s=a).messagePreview.enabled?s.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},so=async()=>{var e;const t=await ao();if(t===(null===(e=ot(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;it(["MessagePreviewSetting"],t);const n=[],a=[];if("no-message-preview"===t){const e=st(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{dt(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&a.push(t.subChannelId)}))}else if("message-preview-not-include-deleted"===t){const e=st(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(dt(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&a.push(t.subChannelId))})),0!==n.length&&await zs(n),0!==a.length&&await no(a)}},oo=async()=>{const e=Xe(),{data:t}=await e.http.get("/api/v3/network-settings/social");return Object.assign(Object.assign({},t.socialNetworkSetting),{isAllowEditCommentWhenReviewingEnabled:t.socialNetworkSetting.isAllowEditCommentWhenReviewingEnabled})},io=async()=>{const e=Xe(),{data:t}=await e.http.get("/api/v3/network-settings/users");return t},ro={mode:e.AmityLiveViewerCountMode.ALWAYS_SHOW,threshold:50},co=async()=>{var t,n;const a=Xe(),{data:s}=await a.http.get("/api/v3/network-settings/video-streaming"),o=null===(t=null==s?void 0:s.videoStreaming)||void 0===t?void 0:t.viewerCountDisplayMode,i=null===(n=null==s?void 0:s.videoStreaming)||void 0===n?void 0:n.viewerCountDisplayMinimum;return(r=o)!==e.AmityLiveViewerCountMode.ALWAYS_SHOW&&r!==e.AmityLiveViewerCountMode.HIDE_ENTIRELY&&r!==e.AmityLiveViewerCountMode.SHOW_ABOVE_MINIMUM||!(e=>"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=1e3)(i)?(a.log("client/getLiveViewerCountConfig","malformed videoStreaming settings, falling back to default",{mode:o,threshold:i}),ro):{mode:o,threshold:i};var r},lo=async()=>{const e=Xe(),{data:t}=await e.http.get("/api/v3/network-settings/product");return t},uo=async()=>{var e,t;const n=Xe(),{data:a}=await n.http.get("/api/v3/network-settings/for-you-feed");return{forYouFeed:{enabled:null!==(t=null===(e=a.forYouFeed)||void 0===e?void 0:e.enabled)&&void 0!==t&&t}}},ho=(e,t)=>{var n;const a=null===(n=ot(["user","get",e]))||void 0===n?void 0:n.data;return!!a&&a.permissions.some((e=>e===t))},mo=e=>{const{userId:t}=Xe();return{currentUser:()=>ho(t,e),community:n=>((e,t,n)=>{var a;if(!e)return!1;const s=null===(a=ot(["communityUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!s&&(!!s.permissions.some((e=>e===t))||ho(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var a;if(!e)return!1;const s=null===(a=ot(["channelUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!s&&(!!s.permissions.some((e=>e===t))||ho(e,t))})(t,e,n)}},go=async e=>{const t=Xe();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/allowlists/verify",{data:e});return n.success},po=async e=>{const t=Xe();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/blocklists/verify",{data:e});return n.success},yo=async()=>{const e=Xe(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},vo={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},fo=(e,t)=>{const n=Xe();n.log("client/api/setSessionState",e,t);const{sessionState:a}=n;if(a===e)return!1;if(!((e,t)=>vo[e].includes(t))(a,e))throw new Je(`Session state cannot change from ${a} to ${e}`,8e5,"error");return n.sessionState=e,Sn().setSessionState(e,t),!0};function bo(e){return{users:e.users.map(Sa),files:e.files}}const Io=async e=>{const t=Xe();fo("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Xe();n.log("client/api/getToken",e);const a=$n(),{data:s}=await n.http.post("/api/v5/sessions",Object.assign(Object.assign({},e),{deviceInfo:a}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.upload.defaults.headers.common.Authorization=`Bearer ${n}`,t.upload.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:s},fo("established"),Hn(bo({users:a,files:r})),{accessToken:n,users:a,userType:i}},Co=async e=>{const t=Xe();fo("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Xe();n.log("client/api/getVisitorToken",e);const a=$n(),{data:s}=await n.http.post("/api/v5/sessions/visitor",Object.assign(Object.assign({},e),{deviceInfo:a}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:s},fo("established"),Hn(bo({users:a,files:r})),{accessToken:n,users:a,userType:i}},wo=async()=>{var e;const t=Xe();return t.log("client/api/disconnectClient"),t.mqtt&&t.mqtt.connected&&await t.mqtt.disconnect({endSession:!0}),"established"===t.sessionState&&fo("notLoggedIn"),t.emitter.all.clear(),null===(e=t.mqtt)||void 0===e||e.removeAllListeners(),t.userId=void 0,t.token=void 0,t.loginType=void 0,t.isGloballyBanned=!1,t.http.defaults.headers.common.Authorization="",t.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},"undefined"!=typeof document&&(document.cookie="_ascSession=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"),"tokenExpired"!==t.sessionState&&t.cache&&(t.cache={data:{}}),!0},So=e=>{const t=Xe();fo("terminated",e),t.http.defaults.metadata&&("globalBan"===e&&(t.http.defaults.metadata.isGlobalBanned=!0),"userDeleted"===e&&(t.http.defaults.metadata.isUserDeleted=!0)),t.sessionHandler=void 0,wo()};let Oo=null;const Ao=e=>{Oo=e},To=({user:e,userType:t})=>{Et(e),Ao(t)},Ro=(e,t)=>{const n=Xe();return Nt(n,e,e,(e=>{const a=bo(e);n.cache&&Hn(a),t(a.users[0])}))},Po=e=>Ro("user.deleted",e),ko=["analytic","normal-priority"],Do=["analytic","high-priority"],Uo=async e=>{const t=Xe(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class jo{constructor(){this._timer=void 0,this._high_priority_timer=void 0}start(){this.syncCapturedEvent(),this._timer=setInterval((()=>{this.syncCapturedEvent()}),6e4),this._high_priority_timer=setInterval((()=>{this.syncHighPriorityCapturedEvent()}),1e4)}stop(){this._timer&&(clearInterval(this._timer),this._timer=void 0),this._high_priority_timer&&(clearInterval(this._high_priority_timer),this._high_priority_timer=void 0)}async syncCapturedEvent(){try{const e=ot(ko);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Uo(t),dt(ko)}catch(e){this.stop(),dt(ko)}}async syncHighPriorityCapturedEvent(){try{const e=ot(Do);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Uo(t),dt(Do)}catch(e){this.stop(),dt(Do)}}}class Eo{constructor(){this._expireTime=5e3,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({uniqueId:e,expireTime:t,isHighPriority:n=!1}){const a=new Date,s=n?this._recentHighPriorityViewed[e]:this._recentViewed[e];if(!s)return!0;return!(a.getTime()-s.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:a,metadata:s}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const o=new Date,i={event:[]},r=ot(ko);(null==r?void 0:r.data)&&(i.event=r.data.event),i.event.length>=this._poolLimit&&i.event.shift();const c={contentId:t,contentType:n,activityType:a,timestamp:o.toISOString()};s&&(c.metadata=s),i.event.push(c),ct(ko,i),this._recentViewed[e]=o}markPostAsViewed(e){this.markAs({uniqueId:`post.${e}`,contentId:e,contentType:"post",activityType:"view"})}markCuratedContentWidgetAsViewed(e){this.markAs({uniqueId:`curatedContentWidget.${e}`,contentId:e,contentType:"curated_content_widget",activityType:"view"})}markCuratedContentPostAsViewed(e,t){this.markAs({uniqueId:`curatedContentPost.${e}.view`,contentId:e,contentType:"curated_content_post",activityType:"view",metadata:{topicId:t}})}markCuratedContentPostAsClicked(e,t){this.markAs({uniqueId:`curatedContentPost.${e}.click`,contentId:e,contentType:"curated_content_post",activityType:"linkClicked",metadata:{topicId:t}})}markPostAsMeaningfullyViewed(e,t){var n;const a=null===(n=ot(["feedMetadata","get",e]))||void 0===n?void 0:n.data,s={};void 0!==t&&(s.feedRenderPosition=t),a&&(s.feedSnapshotPosition=a.feedSnapshotPosition,s.feedInjectionType=a.feedInjectionType,s.feedRelevanceScore=a.feedRelevanceScore,s.feedPopularityScore=a.feedPopularityScore,s.feedFreshnessScore=a.feedFreshnessScore,s.feedAffinityScore=a.feedAffinityScore,s.feedFinalScore=a.feedFinalScore,s.feedMmrPenalty=a.feedMmrPenalty),this.markAs({uniqueId:`post.${e}.meaningfulView`,contentId:e,contentType:"post",activityType:"meaningfulView",metadata:Object.keys(s).length>0?s:void 0})}markStory(e,t){if(!e.expiresAt)return;const n=new Date,a=new Date(e.expiresAt);if(!this.isAbleToEnqueue({uniqueId:e.storyId,expireTime:a.getTime(),isHighPriority:!0}))return;const s={event:[]},o=ot(Do);if((null==o?void 0:o.data)&&(s.event=o.data.event),s.event.length>=this._poolLimit&&s.event.shift(),s.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),ct(Do,s),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;it(["story-seen","get",e.storyId],(new Date).toISOString());const i=ot(["story-last-seen",e.targetId]);(null==i?void 0:i.data)?new Date(i.data).getTime()<new Date(e.expiresAt).getTime()&&it(["story-last-seen",e.targetId],e.expiresAt):it(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),Ft("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},dt(ko),dt(Do)}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}markAdAsViewed(e,t){const n={placement:t},a="view";this.markAs({uniqueId:`${e.adId}.view.${t}`,contentId:e.adId,contentType:"ad",activityType:a,metadata:n})}markAdAsClicked(e,t){const n={placement:t},a="linkClicked";this.markAs({uniqueId:`${e.adId}.linkClicked.${t}`,contentId:e.adId,contentType:"ad",activityType:a,metadata:n})}markProductAsClicked(e,t,n,a){const s={location:t,sourceType:n,sourceId:a},o="linkClicked";this.markAs({uniqueId:`${e.productId}.linkClicked.${t}`,contentId:e.productId,contentType:"product",activityType:o,metadata:s})}markProductAsViewed(e,t,n,a){const s={location:t,sourceType:n,sourceId:a},o="view";this.markAs({uniqueId:`${e.productId}.view.${t}`,contentId:e.productId,contentType:"product",activityType:o,metadata:s})}}class Mo{constructor(){this._client=Xe(),this._eventCapturer=new Eo,this._eventSyncer=new jo}markPostAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsViewed(e)}markCuratedContentWidgetAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markCuratedContentWidgetAsViewed(e)}markCuratedContentPostAsViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markCuratedContentPostAsViewed(e,t)}markCuratedContentPostAsClicked(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markCuratedContentPostAsClicked(e,t)}markPostAsMeaningfullyViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsMeaningfullyViewed(e,t)}markStoryAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsViewed(e)}markAdAsViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsViewed(e,t)}markAdAsClicked(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsClicked(e,t)}markStoryAsClicked(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsClicked(e)}markProductAsClicked(e,t,n,a){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markProductAsClicked(e,t,n,a)}markProductAsViewed(e,t,n,a){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markProductAsViewed(e,t,n,a)}established(){this._eventSyncer.start()}handleTokenExpired(){this._stopAndDestroy()}destroy(){this._stopAndDestroy()}_stopAndDestroy(){this._eventSyncer.stop(),this._eventCapturer.resetAllBuckets()}}let qo;var xo=()=>(qo||(qo=new Mo),qo),Ko=()=>{const e=xo();return e.established(),On((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}};class No{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Xe(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipts();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=st(["readReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.channelId,e.latestSegment)}))}getReadReceipts(){const e=this.jobQueue.splice(0,this.jobQueue.length);if(0!==e.length)return e.filter((e=>{var t;const n=null===(t=ot(["readReceipt",e.channelId]))||void 0===t?void 0:t.data;return!!n&&n.latestSegment>n.latestSyncSegment}))}async markReadApi(e){var t;const n=e.map((e=>({channelId:e.channelId,readToSegment:e.segment})));if(await(async e=>{const t=Xe();try{return await t.http.post("api/v3/channels/seen",{channels:e}),!0}catch(e){return!1}})(n))for(let n=0;n<e.length;n+=1){const a=["readReceipt",e[n].channelId],s=null===(t=ot(a))||void 0===t?void 0:t.data;it(a,Object.assign(Object.assign({},s),{latestSyncSegment:e[n].segment}))}else for(let t=0;t<e.length;t+=1){if(e[t].retryCount>=this.MAX_RETRY)return;const n=Object.assign(Object.assign({},e[t]),{syncState:"create",retryCount:e[t].retryCount+1});this.enqueueJob(n)}}startObservingReadReceiptQueue(){this.client.useLegacyUnreadCount&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1,this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const a=["channelUnread","get",e],s=null===(n=ot(a))||void 0===n?void 0:n.data;s&&("number"!=typeof s.readToSegment||t>s.readToSegment)&&(s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0),it(a,s),Ft("local.channelUnread.updated",[s])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=ot(["readReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)it(["readReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{it(["readReceipt",e],{channelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={channelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){const{jobQueue:t}=this;return t.find((t=>t.channelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}}let Fo=null;var _o=()=>(Fo||(Fo=new No),Fo),Bo=()=>{const e=_o();return e.startSyncReadReceipt(),On((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class $o{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Xe(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipt();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=st(["legacyReadReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.subChannelId,e.latestSegment)}))}getReadReceipt(){var e;const t=this.jobQueue[0];if(!t)return;if("syncing"===t.syncState)return;const n=null===(e=ot(["legacyReadReceipt",t.subChannelId]))||void 0===e?void 0:e.data;return n?(null==n?void 0:n.latestSegment)>(null==n?void 0:n.latestSyncSegment)?(t.segment=n.latestSegment,t):(this.removeSynedReceipt(n.subChannelId,n.latestSegment),this.getReadReceipt()):void 0}async markReadApi(e){var t;const n=e;n.syncState="syncing";const{subChannelId:a,segment:s}=n,o=await(async({subChannelId:e,readToSegment:t})=>{const n=Xe();n.log("subChannel/markAsReadBySegment",e);try{return await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-read`,{readToSegment:t}),!0}catch(e){return!1}})({subChannelId:a,readToSegment:s});if(o){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=ot(["legacyReadReceipt",a]))||void 0===t?void 0:t.data;it(["legacyReadReceipt",a],Object.assign(Object.assign({},n),{latestSyncSegment:s}))}else o||(n.retryCount>this.MAX_RETRY?this.removeJobFromQueue(n):(n.retryCount+=1,n.syncState="create"))}removeSynedReceipt(e,t){this.jobQueue.forEach((n=>{n.subChannelId===e&&n.segment<=t&&this.removeJobFromQueue(n)}))}startObservingReadReceiptQueue(){this.client.isUnreadCountEnabled&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1;this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const a=["subChannelUnreadInfo","get",e],s=null===(n=ot(a))||void 0===n?void 0:n.data;if(s&&t>s.readToSegment){s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0);const e=da(s.channelId);Ft("local.channelUnreadInfo.updated",e),it(a,s),Ft("local.subChannelUnread.updated",s)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=ot(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)it(["legacyReadReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{it(["legacyReadReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){return this.jobQueue.find((t=>t.subChannelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}removeJobFromQueue(e){const t=this.jobQueue.indexOf(e);t>-1&&this.jobQueue.splice(t,1)}}let Lo=null;var Qo=()=>(Lo||(Lo=new $o),Lo),Vo=()=>{const e=Qo();return e.startSyncReadReceipt(),On((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const Jo=e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("online",e),()=>window.removeEventListener("online",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("online",e),()=>document.removeEventListener("online",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return import("@react-native-community/netinfo").then((n=>{t=n.addEventListener((t=>{t.isConnected&&e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")},Ho=e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("offline",e),()=>window.removeEventListener("offline",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("offline",e),()=>document.removeEventListener("offline",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return import("@react-native-community/netinfo").then((n=>{t=n.addEventListener((t=>{t.isConnected||e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")},Wo=async e=>{const t=Xe();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{De(null==t?void 0:t.code)&&Wn("channel",e)})),t}const s=await Na(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Qa(a);const o=t.cache&&Date.now();return t.cache&&Hn(s,{cachedAt:o}),Ft("local.channel.fetched",s.channels),{data:s.channels,cachedAt:o}};Wo.locally=e=>{var t,n;const a=Xe();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const s=null===(t=st(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;return{data:s.map((({data:e})=>e)),cachedAt:(null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0]).cachedAt}};class zo{constructor(){this.TIMER_INTERVAL_MS=Ce,this.BUFFER_ID_LIMIT=100,this.buffer={channel:[],userMessageFeedMarker:[]},this.isResolvingTask=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startResolver(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.resolveObjects()}),this.TIMER_INTERVAL_MS))}stopResolver(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}resolve(e,t){const n=this.getBuffer(t);n.includes(e)||(n.length>=this.BUFFER_ID_LIMIT&&n.shift(),n.push(e))}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push(Jo((()=>{this.isConnected=!0}))),this.connectionListener.push(Ho((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&this.connectionListener.forEach((e=>e()))}resolveObjects(){if(this.isResolvingTask)return;this.isResolvingTask=!0;const e=this.getBuffer("channel"),t=this.getBuffer("userMessageFeedMarker");this.clearBuffer(),e.length>0&&(async e=>{var t,n,a;await Wo(e);const s=null!==(a=null===(n=null===(t=st(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId&&e.includes(t.channelPublicId))))||void 0===n?void 0:n.map((({data:e})=>e)))&&void 0!==a?a:[];Ft("local.channel.resolved",s)})(e),t.length>0&&(async e=>{const t=await La(e),{feedMarkers:n,userFeedMarkers:a}=t;la({feedMarkers:n,userFeedMarkers:a}),Ft("local.userMessageFeedMarkers.resolved",{feedMarkers:n,userFeedMarkers:a})})(t),this.isResolvingTask=!1}clearBuffer(){this.buffer={channel:[],userMessageFeedMarker:[]}}getBuffer(e){return this.buffer[e]}onSessionEstablished(){this.startResolver(),this.addConnectionListener()}onSessionDestroyed(){this.stopResolver(),this.clearBuffer(),this.isResolvingTask=!1,this.removeConnectionListener()}onTokenExpired(){this.stopResolver()}}let Go=null;var Yo=()=>(Go||(Go=new zo),Go),Xo=()=>{const e=Yo();return e.startResolver(),On((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Zo{constructor(){this.TIMER_INTERVAL_MS=1e3,this.buffer=[],this.isSyncing=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startReactionsSync(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.syncLiveReactions()}),this.TIMER_INTERVAL_MS))}stopReactionsSync(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}createLiveReaction(e){this.buffer.push(e)}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push(Jo((()=>{this.isConnected=!0}))),this.connectionListener.push(Ho((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&(this.connectionListener.forEach((e=>e())),this.connectionListener=[])}syncLiveReactions(){if(this.isSyncing)return;this.isSyncing=!0;const e=this.buffer;this.clearBuffer();const t=e.reduce(((e,t)=>{const{roomId:n,streamId:a}=t,s=zn(t,["roomId","streamId"]),o=a?"liveStream":"room",i=null!=a?a:n;return e[i]||(e[i]={referenceType:o,reactions:[]}),e[i].reactions.push(s),e}),{});Object.entries(t).forEach((([t,n])=>{(async({reactions:e,liveStreamId:t,roomId:n})=>{const a=Xe();a.log("live_reaction/addReaction",e);const{data:s}=await a.http.post("/api/v1/reactions/live",{liveStreamId:t,reactions:e,roomId:n})})({["room"===n.referenceType?"roomId":"liveStreamId"]:t,reactions:e})})),this.isSyncing=!1}clearBuffer(){this.buffer=[]}onSessionEstablished(){this.startReactionsSync(),this.addConnectionListener()}onSessionDestroyed(){this.stopReactionsSync(),this.clearBuffer(),this.isSyncing=!1,this.removeConnectionListener()}onTokenExpired(){this.stopReactionsSync()}}let ei;var ti=()=>(ei||(ei=new Zo),ei);function ni(e){const{users:t,follows:n}=e,a=zn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:Sa(n)})})),users:t.map(Sa)})}class ai{constructor(){this.lastFetchedAt=null}onSessionEstablished(){}onSessionDestroyed(){this.lastFetchedAt=null}onTokenExpired(){}isCacheExpired(){return null===this.lastFetchedAt||Date.now()-this.lastFetchedAt>3e5}async ensureFetched(){if(!this.isCacheExpired())return;const e=Xe(),{data:t}=await e.http.get("/api/v4/me/user-blocks",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=ni(t);e.cache&&Hn(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Xe();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=st(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&e.from===n)).sort(((e,t)=>{var n,a;return(null!==(n=e.updatedAt)&&void 0!==n?n:"")<(null!==(a=t.updatedAt)&&void 0!==a?a:"")?1:-1})).map((e=>{var t;return null===(t=ot(["user","get",e.to]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(Lt)}}let si=null;var oi=()=>(si||(si=new ai),si);function ii(e){const{users:t,follows:n}=e,a=zn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:Sa(n)})})),users:t.map(Sa)})}class ri{constructor(){this.lastFetchedAt=null}onSessionEstablished(){}onSessionDestroyed(){this.lastFetchedAt=null}onTokenExpired(){}isCacheExpired(){return null===this.lastFetchedAt||Date.now()-this.lastFetchedAt>3e5}async ensureFetched(){if(!this.isCacheExpired())return;const e=Xe(),{data:t}=await e.http.get("/api/v4/me/blockers",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=ii(t);e.cache&&Hn(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Xe();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=st(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&e.to===n)).sort(((e,t)=>{var n,a;return(null!==(n=e.updatedAt)&&void 0!==n?n:"")<(null!==(a=t.updatedAt)&&void 0!==a?a:"")?1:-1})).map((e=>{var t;return null===(t=ot(["user","get",e.from]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(Lt)}}let ci=null;var di=()=>(ci||(ci=new ri),ci);function li(e){const{users:t,follows:n}=e,a=zn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(Sa)})}function ui(e){const{users:t,follows:n}=e,a=zn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(Sa)})}function hi(e){const{follows:t}=e,n=zn(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const mi=(e,t)=>{const n=Xe();return Nt(n,e,e,(e=>{const a=li(e);n.cache&&Hn(a),t(a.follows[0])}))},gi=e=>mi("user.didBlock",e),pi=e=>mi("user.didUnblock",e);class yi{constructor(e,t){this.networkId=e,this.userId=t}static current(){try{const e=Qt();if(!e)return null;const t=Ht(e),{userId:n}=e;return t&&n?new yi(t,n):null}catch(e){return null}}static isExpired(e){return Date.now()>=e}static clearOnLogout(){return On((e=>{var t;"terminated"===e&&(null===(t=yi.current())||void 0===t||t.clear())}))}get key(){return`amity:forYouFeed:cursor:${this.networkId}:${this.userId}`}async get(){const e=await Mn(this.key);if(!e)return null;try{const t=JSON.parse(e);return"string"!=typeof(null==t?void 0:t.cursor)||"number"!=typeof(null==t?void 0:t.expiredAt)?null:{cursor:t.cursor,expiredAt:t.expiredAt,reachedEndOfFeed:!0===t.reachedEndOfFeed}}catch(e){return null}}async set(e){await En(this.key,JSON.stringify(e))}async markReachedEndOfFeed(e){var t;const n=await this.get();await this.set({cursor:null!==(t=null==n?void 0:n.cursor)&&void 0!==t?t:"",expiredAt:e,reachedEndOfFeed:!0})}async clear(){await En(this.key,"")}}class vi{constructor(e,t,n){this.postId=e,this.latestCreatedAt=t,this.serverCommentCount=n}}class fi{constructor(e,t,n){this.postId=e,this.commentId=t,this.createdAt=n}}class bi{constructor(e,t){this.postId=e,this.commentId=t}}class Ii{constructor(e,t){this.postId=e,this.commentId=t}}class Ci{constructor(e,t){this.latestCommentCreatedAt=e,this.serverCommentCount=t,this.createdCommentIds=new Set,this.deletedCommentIds=new Set}}class wi{constructor(){this.isProcessing=!1,this.tasks=[],this.commentChangeTracker=new Map,this.pendingAuthoredCommentIds=new Map}queueCommentChangeTask(e){this.tasks.push(e),this.isProcessing||this.processCommentChangeTask()}addPendingAuthoredComment(e,t,{publish:n=!0}={}){var a;const s=null!==(a=this.pendingAuthoredCommentIds.get(e))&&void 0!==a?a:new Set;s.has(t)||(s.add(t),this.pendingAuthoredCommentIds.set(e,s),n&&this.publishIfTracked(e))}removePendingAuthoredComment(e,t,{publish:n=!0}={}){const a=this.pendingAuthoredCommentIds.get(e);return!!(null==a?void 0:a.delete(t))&&(0===a.size&&this.pendingAuthoredCommentIds.delete(e),n&&this.publishIfTracked(e),!0)}hasTracker(e){return this.commentChangeTracker.has(e)}isPendingAuthoredComment(e,t){var n,a;return null!==(a=null===(n=this.pendingAuthoredCommentIds.get(e))||void 0===n?void 0:n.has(t))&&void 0!==a&&a}reset(){this.tasks=[],this.commentChangeTracker.clear(),this.pendingAuthoredCommentIds.clear()}publishIfTracked(e){this.commentChangeTracker.has(e)&&wi.publishUpdate(e,this.getLocalCommentCount(e,!0))}processCommentChangeTask(){if(this.isProcessing)return;if(this.isProcessing=!0,0===this.tasks.length)return void(this.isProcessing=!1);const e=this.tasks.splice(0,wi.BATCH_SIZE),t=new Set;e.forEach((e=>{let n=!1;e instanceof vi?n=this.processResetTaskInternal(e):e instanceof fi?n=this.processCreateTaskInternal(e):e instanceof bi?n=this.processApproveTaskInternal(e):e instanceof Ii&&(n=this.processDeleteTaskInternal(e)),n&&t.add(e.postId)})),t.forEach((e=>{wi.publishUpdate(e,this.getLocalCommentCount(e,!0))})),this.isProcessing=!1,this.tasks.length>0&&this.processCommentChangeTask()}processResetTaskInternal(e){return this.commentChangeTracker.set(e.postId,new Ci(e.latestCreatedAt,e.serverCommentCount)),!0}processCreateTaskInternal(e){const t=this.removePendingAuthoredComment(e.postId,e.commentId,{publish:!1}),n=this.commentChangeTracker.get(e.postId);return!!n&&(!!n.deletedCommentIds.delete(e.commentId)||(n.createdCommentIds.has(e.commentId)||e.createdAt<=n.latestCommentCreatedAt?t:(n.createdCommentIds.add(e.commentId),!0)))}processApproveTaskInternal(e){const t=this.removePendingAuthoredComment(e.postId,e.commentId,{publish:!1}),n=this.commentChangeTracker.get(e.postId);return!!n&&(!!n.deletedCommentIds.delete(e.commentId)||(n.createdCommentIds.has(e.commentId)?t:(n.createdCommentIds.add(e.commentId),!0)))}processDeleteTaskInternal(e){const t=this.commentChangeTracker.get(e.postId);return!!t&&(!t.deletedCommentIds.has(e.commentId)&&(t.deletedCommentIds.add(e.commentId),!0))}getLocalCommentCount(e,t=!1){var n;const a=this.commentChangeTracker.get(e);if(!a)return 0;const s=a.createdCommentIds.size-a.deletedCommentIds.size;if(!t)return Math.max(0,a.serverCommentCount+s);let o=0;return null===(n=this.pendingAuthoredCommentIds.get(e))||void 0===n||n.forEach((e=>{a.createdCommentIds.has(e)&&!a.deletedCommentIds.has(e)||(o+=1)})),Math.max(0,a.serverCommentCount+s+o)}static publishUpdate(e,t){var n;const a=["post","get",e];rt(a,{localCommentCount:t});const s=null===(n=ot(a))||void 0===n?void 0:n.data;s&&Ft("local.post.updated",{posts:[s]})}}let Si;wi.BATCH_SIZE=50;var Oi=()=>(Si||(Si=new wi),Si);const Ai=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Ti=e=>{const t=Xe(),n=Ai.map((n=>Nt(t,`client/onConnectionError(${n})`,n,(t=>{const a=(null==t?void 0:t.code)?new Je(t.message,t.code,"fatal"):new ze(n);e(a)}))));return()=>{n.forEach((e=>e()))}},Ri=e=>{const t=Xe();return Nt(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Pi=e=>{const t=Xe();return Nt(t,"client/onTokenExpired","tokenExpired",e)},ki=e=>{const t=Xe();return Nt(t,"client/onTokenTerminated","tokenTerminated",e)},Di=e=>{const t=tt("channelMarker")({userId:jt()._id,entityId:e.channelId});dt(["channelMarker","get",t],!0)},Ui=e=>{const t=Xe(),n=[];return n.push(Ri((t=>{So("globalBan"),n.forEach((e=>e())),e()})),ki((t=>{So(),n.forEach((e=>e())),e()})),Po((a=>{a.userId===t.userId&&(So("userDeleted"),n.forEach((e=>e())),e())})),Pi((e=>{Sn().setSessionState(e),wo(),n.forEach((e=>e()))})),cs(Di),js(Di),to(),Ko(),Xo(),(()=>{const e=ti();return e.startReactionsSync(),On((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=oi();return On((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=di();return On((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=[gi((()=>{})),pi((()=>{}))];return()=>e.forEach((e=>e()))})(),On((e=>{"established"!==e&&Dn().reset()})),yi.clearOnLogout(),On((e=>{"notLoggedIn"!==e&&"terminated"!==e||Oi().reset()}))),t.useLegacyUnreadCount?n.push(Bo()):n.push(Vo()),n};let ji=[];const Ei=async(e,t,n)=>{const a=Xe();let s;a.log("client/api/connectClient",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&a.userId!==e.userId&&(await wo(),ji.forEach((e=>e())),ji=[]);const o=await xn();try{const{users:n,userType:i}=await Io({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||o}),options:{setAccessTokenCookie:!0}}),r=n.find((t=>t.userId===e.userId));if(null==r)throw new Je(`${e.userId} has not been founded`,8e5,"error");if(r.isDeleted)return So("userDeleted"),!1;if(r.isGlobalBan)return So("globalBan"),!1;a.userId=r.userId,a.sessionHandler=t,a.loginType="userId",s=a.accessTokenExpiryWatcher(),To({user:r,userType:i})}catch(e){throw Sn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await $t()}(),await so(),0===ji.length&&(ji=Ui(s)),!0},Mi=[],qi=async e=>{const t=Xe();let n;t.log("client/api/connectClient",Object.assign({apiKey:t.apiKey,sessionState:t.sessionState},e));const a=await xn();let s;try{const{users:o,userType:i}=await Co({params:Object.assign(Object.assign({},e),{deviceId:a}),options:{setAccessTokenCookie:!0}});[s]=o,t.userId=s.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),To({user:s,userType:i})}catch(e){throw Sn().setSessionState("notLoggedIn"),e}return await so(),0===Mi.length&&Mi.push(ki((e=>{So(),Mi.forEach((e=>e())),n()})),Pi((e=>{Sn().setSessionState(e),wo(),Mi.forEach((e=>e()))}))),!0},xi=()=>{let e,t=!1;const n=Xe();n.log("initiating access token renewal");const a=async a=>{const{userId:s,displayName:o}=jt(),i={userId:s,displayName:o,authToken:a,deviceId:await xn()};"tokenExpired"===n.sessionState&&n.sessionHandler?await Ei(i,n.sessionHandler):await Io({params:i,options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):a()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):a(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(xi())}),we)},renewWithAuthSignature:a=>{t?console.log("'renew' method can be called only once per renewal instance"):(async({authSignature:a,authSignatureExpiresAt:s})=>{const o=await xn();"tokenExpired"===n.sessionState&&n.sessionHandler?await qi({sessionHandler:n.sessionHandler}):await Co({params:{authSignature:a,authSignatureExpiresAt:s,deviceId:o},options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)})(a)},unableToRetrieveAuthSignature:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(xi())}),we)}}},Ki=async({token:e,userId:t})=>{const n=Xe(),{data:a}=await n.http.get("/api/v4/sessions",{headers:{Authorization:`Bearer ${e.accessToken}`}}),{users:s,files:o,userType:i}=a,[r]=s;return t&&(null==r?void 0:r.userId)&&t!==r.userId&&n.log("client/api/validateAccessToken",{message:"session userId does not match the token userId; using the server value",tokenUserId:t,sessionUserId:r.userId}),n.http.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.http.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.upload.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.upload.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.token=e,Hn(bo({users:s,files:o})),Ao(i),r},Ni=e=>{var t;const n=Xe(),a=R.default(e);return(null===(t=null==a?void 0:a.user)||void 0===t?void 0:t.publicUserId)===n.userId};let Fi=[];const _i=async e=>{var t,n;const a=Xe();let s,o;if(a.log("client/api/loginWithAccessToken",{apiKey:a.apiKey,sessionState:a.sessionState}),!e||"string"!=typeof e||""===e.trim())throw new Je("Access token must be a non-empty string",8e5,"error");try{o=R.default(e)}catch(e){throw new Je("Invalid access token format",400100,"error")}const i=(null===(t=null==o?void 0:o.user)||void 0===t?void 0:t.publicUserId)||(null===(n=null==o?void 0:o.user)||void 0===n?void 0:n.userId);if(!i)throw new Je("Access token does not contain userId",400100,"error");if(a.userId){Ni(e)||await wo()}try{fo("establishing");const t={accessToken:e,issuedAt:o.iat?new Date(1e3*o.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*o.exp).toISOString()},n=await Ki({token:t,userId:i});if(null==n)throw fo("notLoggedIn"),new Je(`User ${i} has not been found`,8e5,"error");a.userId=n.userId,a.loginType="accessToken",Et(n),s=a.accessTokenExpiryWatcher(),fo("established")}catch(e){if(fo("notLoggedIn"),e instanceof Je)throw 400312===e.code&&(a.isGloballyBanned=!0),e;throw new Je((e instanceof Error?e.message:void 0)||"Login with access token failed",400100,"error")}return async function(){await $t()}(),await so(),0===Fi.length&&(Fi=Ui(s)),!0},Bi=async e=>{var t,n;const a=Xe();if(a.log("initiating access token renewal"),!e||"string"!=typeof e||""===e.trim())throw new Je("Access token must be a non-empty string",8e5,"error");let s;try{s=R.default(e)}catch(e){throw new Je("Invalid access token format",400100,"error")}const o=(null===(t=null==s?void 0:s.user)||void 0===t?void 0:t.publicUserId)||(null===(n=null==s?void 0:s.user)||void 0===n?void 0:n.userId);if(!o)throw new Je("Access token does not contain userId",400100,"error");if(a.userId){Ni(e)||await wo()}const i={accessToken:e,issuedAt:s.iat?new Date(1e3*s.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*s.exp).toISOString()};if("tokenExpired"===a.sessionState&&a.sessionHandler)await _i(e);else try{await Ki({token:i,userId:o})}catch(e){throw e instanceof Je&&400312===e.code&&(a.isGloballyBanned=!0),e}},$i=async({useScheduledTask:e=!1})=>{const t=Xe();if(t.userId&&t.accessTokenHandler&&!t.isGloballyBanned)try{const n=await t.accessTokenHandler.onTokenRenew(t.userId);e?xt((()=>Bi(n))):Bi(n)}catch(e){t.log("Proactive token renewal failed, will retry when token expires",e)}},Li=3e5,Qi=()=>{const e=setInterval((async()=>{const e=Xe(),{sessionHandler:t,accessTokenHandler:n,loginType:a}=e;if(!e.token||!e.userId)return;const{issuedAt:s,expiresAt:o}=e.token;if((e=>Date.now()>Date.parse(e)-Li)(o))return Ft("tokenExpired","tokenExpired"),void("accessToken"===a&&n?await $i({useScheduledTask:!1}):"userId"===a&&t&&xt((()=>t.sessionWillRenewAccessToken(xi()))));(e=>{const{expiresAt:t,issuedAt:n}=e,a=Date.parse(t),s=Date.parse(n),o=Date.now();return o>s+.8*(a-s-Li)&&o<a})({expiresAt:o,issuedAt:s})&&("accessToken"===a&&n?await $i({useScheduledTask:!1}):"userId"===a&&t&&t.sessionWillRenewAccessToken(xi()))}),we);return()=>clearInterval(e)},Vi=e=>{if(Xe().useLegacyUnreadCount){_o().markRead(e.channelId,e.channelSegment)}else{Qo().markRead(e.subChannelId,e.channelSegment)}},Ji=e=>{const t=Xe(),n=jt(),a=[Nt(t,"message/onMessageCreated","message.created",(async a=>{const s=await Ia(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messages.forEach((e=>{(e=>{var t;const n=Xe(),a=["subChannelUnreadInfo","get",e.messageFeedId],s=null===(t=ot(a))||void 0===t?void 0:t.data;if(!s)return;const o=s.lastSegment<e.segment?e.segment:s.lastSegment,i=o-s.readToSegment;let{lastMentionSegment:r}=s;e.mentionedUsers&&e.mentionedUsers.length>0&&e.mentionedUsers.forEach((t=>{("channel"===t.type||"user"===t.type&&n.userId&&t.userPublicIds.includes(n.userId))&&(r=e.segment)}));const c=Object.assign(Object.assign({},s),{lastMentionSegment:r,lastSegment:o,isMentioned:!(s.readToSegment>=r),unreadCount:Math.max(i,0)});it(a,c)})(e),da(e.channelId)})),t.useLegacyUnreadCount&&a.messages.forEach((e=>{var n,a,s;const o=null===(n=ot(["channelUnread","get",e.channelId]))||void 0===n?void 0:n.data;if(!o||o.lastSegment>=e.segment)return;const i=e.segment,r=(null===(a=e.mentionedUsers)||void 0===a?void 0:a.some((e=>"channel"===e.type||"user"===e.type&&t.userId&&e.userPublicIds.includes(t.userId))))?e.segment:o.lastMentionedSegment,c=null!==(s=o.readToSegment)&&void 0!==s?s:0,d=Object.assign(Object.assign({},o),{lastSegment:i,unreadCount:Math.max(i-c,0),lastMentionedSegment:r,isMentioned:"number"==typeof r&&c<r});it(["channelUnread","get",e.channelId],d),Ft("local.channelUnread.updated",[d])})),Hn(s),s.messages.forEach((t=>{t.creatorPrivateId===n._id&&Vi(t),e(t)}))}))];return()=>{a.forEach((e=>e()))}},Hi=e=>{const t=Xe(),n=[Nt(t,"message/onMessageCreated","local.message.created",(async t=>(Hn(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},Wi=e=>{const t=Xe();return Nt(t,"onSubChannelCreated","message-feed.created",(async n=>{const a=await Ta(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:a,updatedAt:s}=e,o={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:a,updatedAt:s};it(["subChannelUnreadInfo","get",o.subChannelId],o)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Hn(a),e(a.messageFeeds[0])}))},zi=e=>{const t=Xe(),n=[Nt(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const a=await Ta(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],a=null===(t=ot(n))||void 0===t?void 0:t.data;a&&it(n,Object.assign(Object.assign({},a),{isDeleted:!0}))})(e.subChannelId),da(e.channelId)})),Hn(a),e(a.messageFeeds[0])})),Nt(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Gi=async e=>{const t=Xe();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:a,userFeedMarkers:s,feedMarkers:o,userMarkers:i}=n,r=Zn(a),c=ea(s),d=t.cache&&Date.now();return t.cache&&Hn({userEntityMarkers:r,userFeedMarkers:c,feedMarkers:o,userMarkers:i},{cachedAt:d}),Ft("local.feedMarker.fetched",{feedMarkers:o}),Ft("local.channelMarker.fetched",{userEntityMarkers:r}),Ft("local.subChannelMarker.fetched",{userFeedMarkers:c}),Ft("local.userMarker.fetched",{userMarkers:i}),{data:n,hasMore:n.feedMarkers.length>0}};let Yi=!1,Xi=[],Zi=!1;let er=null;let tr=[];const nr=e=>{tr=e},ar=async()=>{var e;if(!Zi&&0!==tr.length)try{Zi=!0,tr=[];const t=await Gi((null==er?new Date:er).toISOString()),n=t.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);null!=(e=n)&&(!er||e.getTime()>er.getTime())&&(er=e),t.hasMore&&tr.push("has_more")}catch(e){}finally{Zi&&(Zi=!1)}};Gs((async()=>{Yi&&await ar()}),2e3);const sr=()=>true,or=e=>{var t;const n=Xe();if(n.mqtt)return null===(t=n.mqtt)||void 0===t?void 0:t.listen(e)},ir=async()=>{const e=Xe(),t=await xn(),{data:{status:n,error:a}}=await e.http.delete("/v1/notification",{params:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(a)throw new He(a,5e5,"error");return"success"===n};let rr=[];var cr;class dr{constructor(){cr.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,a,s){if("m"===a)throw new TypeError("Private method is not writable");if("a"===a&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===a?s.call(e,n):s?s.value=n:t.set(e,n)}(this,cr,e,"f")}getFileAccessType(){return function(e,t,n,a){if("a"===n&&!a)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?a:"a"===n?a.call(e):a?a.value:t.get(e)}(this,cr,"f")}}let lr;cr=new WeakMap;var ur=()=>(lr||(lr=new dr),lr);const hr={[e.AmitySharableContentType.POST]:{key:"posts",placeholder:"postId"},[e.AmitySharableContentType.COMMUNITY]:{key:"communities",placeholder:"communityId"},[e.AmitySharableContentType.USER]:{key:"users",placeholder:"userId"},[e.AmitySharableContentType.LIVESTREAM]:{key:"livestream",placeholder:"livestream"},[e.AmitySharableContentType.EVENT]:{key:"events",placeholder:"eventId"}},mr=async e=>{const t=Xe();fo("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Xe();n.log("client/api/getBotToken");const a=$n(),{data:s}=await n.http.post("/api/v5/sessions/bot",Object.assign(Object.assign({},e),{deviceInfo:a}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:s},fo("established"),Hn(bo({users:a,files:r})),{accessToken:n,users:a,userType:i}},gr=[];function pr(t,n){return n&&n.length>0?{type:"not",roleIds:n}:t&&t.length>0?{type:e.NotificationRolesFilterTypeEnum.ONLY,roleIds:t}:{type:e.NotificationRolesFilterTypeEnum.ALL}}function yr(t){return(null==t?void 0:t.type)===e.NotificationRolesFilterTypeEnum.ONLY?{listenFromRoleIds:t.roleIds}:{listenFromRoleIds:[]}}class vr{constructor(e){this.channelId=e}async enable(){const t=Xe(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!0};await t.http.post("/api/v3/notification/setting",n)}async disable(){const t=Xe(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!1};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){const t=Xe(),{data:n}=await t.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.CHANNEL}&channelId=${encodeURIComponent(this.channelId)}`);return{isEnabled:n.isPushNotifiable}}}class fr{async enable(t){var n;const a=Xe(),s=null!==(n=null==t?void 0:t.map((e=>Object.assign({moduleName:e.moduleName,isPushNotifiable:e.isEnabled},yr(e.rolesFilter)))))&&void 0!==n?n:[],o={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!0,notifiableEvents:s};await a.http.post("/api/v3/notification/setting",o)}async disableAllNotifications(){const t=Xe(),n={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=Xe(),{data:a}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.USER}`),s=Object.values(e.UserNotificationModuleNameEnum),o=(null!==(t=a.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.moduleName&&s.includes(e.moduleName))).map((e=>({moduleName:e.moduleName,isEnabled:e.isPushNotifiable,rolesFilter:pr(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,modules:o}}}class br{constructor(e){this.communityId=e}async enable(t){var n;const a=Xe(),s=null!==(n=null==t?void 0:t.map((t=>Object.assign({moduleName:e.UserNotificationModuleNameEnum.SOCIAL,name:t.eventName,isPushNotifiable:t.isEnabled},yr(t.rolesFilter)))))&&void 0!==n?n:[],o={level:e.NotificationSettingsLevelEnum.COMMUNITY,communityId:this.communityId,isPushNotifiable:!0,notifiableEvents:s};await a.http.post("/api/v3/notification/setting",o)}async disable(){const t=Xe(),n={level:e.NotificationSettingsLevelEnum.COMMUNITY,communityId:this.communityId,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=Xe(),{data:a}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.COMMUNITY}&communityId=${encodeURIComponent(this.communityId)}`),s=Object.values(e.CommunityNotificationEventNameEnum),o=(null!==(t=a.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.name&&s.includes(e.name))).map((e=>({eventName:e.name,isEnabled:e.isPushNotifiable,isNetworkEnabled:e.isNetworkEnabled,rolesFilter:pr(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,events:o}}}class Ir{user(){return new fr}community(e){return new br(e)}channel(e){return new vr(e)}}const Cr=e=>{const t=Xe();return Nt(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},wr=e=>{const t=Xe();return Nt(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},Sr=e=>{const t=Xe();return Nt(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},Or=e=>{const t=Xe();return Nt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},Ar=e=>{const t=Xe();return Nt(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},Tr=e=>{const t=Xe();return Nt(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,a,s;Hn(t);const o=st(["message","collection"]),{contentMarkers:i,feedMarkers:r}=t;if(o&&(null==o?void 0:o.length)>0&&(null==r?void 0:r.length)>0){const e=o.filter((e=>{var t,n;return(null===(n=null===(t=e.data)||void 0===t?void 0:t.query)||void 0===n?void 0:n.subChannelId)===r[0].feedId}));if(e.length>0&&(null==i?void 0:i.length)>0){(null!==(s=null===(a=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===a?void 0:a.map((e=>ot(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==s?s:[]).forEach((e=>{var t,n;const a=["messageMarker","get",tt("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],s=null===(t=ot(a))||void 0===t?void 0:t.data;if(!s)return;const o=i[0].feedId===s.feedId,r=i[0].readCount>s.readCount,c=(null===(n=i[0])||void 0===n?void 0:n.deliveredCount)>s.deliveredCount;if(o){const e=Object.assign(Object.assign({},s),{readCount:r?i[0].readCount:s.readCount,deliveredCount:c?i[0].deliveredCount:s.deliveredCount});it(a,e)}}))}}e(t.contentMarkers[0])}))};function Rr(e){return"object"==typeof e&&null!==e}const Pr=e=>{if(!Rr(e))return e;const t=Object.entries(e).map((([t,n])=>{const a=Object.getOwnPropertyDescriptor(e,t);return"function"==typeof(null==a?void 0:a.get)?[t,a.get.call(e)]:[t,n]}));return Object.fromEntries(t)},kr=e=>{if(!Rr(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var Dr=Object.freeze({__proto__:null,getActiveClient:Xe,getActiveUser:jt,setActiveUser:Et,createClient:(e,t=cn.SG,{debugSession:n="amity",apiEndpoint:a,prefixDeviceIdKey:s,rteEnabled:o=!0,product:i,uikitVersion:r,appId:c,appVersion:d}={})=>{var l,u,h;const m=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!rn,n=C.default(e),a=(e,...a)=>{t&&n(e,a)};return a.__instance__=n,a})(n);m("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const g=null!==(l=null==a?void 0:a.http)&&void 0!==l?l:ln("http",t),p=null!==(u=null==a?void 0:a.upload)&&void 0!==u?u:ln("upload",t),y=null!==(h=null==a?void 0:a.mqtt)&&void 0!==h?h:ln("mqtt",t),v=In(g),f=In(p);let b;o&&(b=Vn(y));const w=I.default(),S={version:`${ge}`,product:i,uikitVersion:r,appId:c,appVersion:d,apiKey:e,log:m,cache:{data:{}},http:v,ws:undefined,mqtt:b,upload:f,emitter:w,sessionState:"notLoggedIn",accessTokenExpiryWatcher:Qi,sessionHandler:undefined,hasPermission:mo,validateUrls:go,validateTexts:po,getFeedSettings:yo,getCoreUserSettings:io,getSocialSettings:oo,getChatSettings:Jn,getLiveViewerCountConfig:co,getVisitorDeviceId:xn,getMessagePreviewSetting:ao,onRTEConnectionStateChange:or,use:()=>Ze(S),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:sr,getProductCatalogueSetting:lo,getForYouFeedSetting:uo,prefixDeviceIdKey:s};try{const t=Xe();if(t.apiKey===e)return t;Ze(S)}catch(e){Ze(S)}return S},login:Ei,loginWithAccessToken:_i,logout:wo,secureLogout:async()=>{const e=Xe();try{await ir()}catch(t){e.log("client/api/secureLogout: failed to unregister push notification",t)}const{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return wo()},resumeSession:async(e,t,n)=>{const a=Xe();let s;a.log("client/api/resumeSession",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&(a.userId===e.userId&&Ni(e.token.accessToken)?(a.mqtt&&a.mqtt.connected&&a.mqtt.disconnect(),rr.forEach((e=>e())),rr=[]):(await wo(),rr.forEach((e=>e())),rr=[]));try{fo("establishing");const n=await Ki(e);if(null==n)throw new Je(`${e.userId} has not been found`,8e5,"error");a.userId=n.userId,a.sessionHandler=t,s=a.accessTokenExpiryWatcher(),Et(n)}catch(e){throw Sn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await $t()}(),await so(),0===rr.length&&(rr.push(Ri((e=>{So("globalBan"),rr.forEach((e=>e())),s()})),ki((e=>{So(),rr.forEach((e=>e())),s()})),Po((e=>{e.userId===a.userId&&(So("userDeleted"),rr.forEach((e=>e())),s())})),Pi((e=>{Sn().setSessionState(e),wo(),rr.forEach((e=>e()))})),cs(Di),js(Di),to(),Ko(),Xo()),a.useLegacyUnreadCount?rr.push(Bo()):rr.push(Vo())),!0},isConnected:()=>{var e,t;const n=Xe();return n.log("client/api/isConnected",n),!(!n.userId||!(null===(t=String(null===(e=n.http.defaults.headers.common)||void 0===e?void 0:e.Authorization))||void 0===t?void 0:t.length))},getFeedSettings:yo,renewal:xi,markerSync:Gi,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){ur().setFileAccessType(e)},registerPushNotification:async e=>{const t=Xe();let n;if("ios"!==u.Platform.OS&&"android"!==u.Platform.OS)throw new Ge("Unsupported platform");n=u.Platform.OS;const a=await xn(),{data:{status:s,error:o}}=await t.http.post("/v1/notification",{userId:t.userId,deviceId:a,platform:n,token:e},{headers:{"X-API-Key":t.apiKey}});if(o)throw new He(o,5e5,"error");return"success"===s},unregisterPushNotification:ir,onRTEConnectionStateChange:or,fetchLinkPreview:async e=>{const t=Xe();let n=e;/^https?:\/\//i.test(e)||(n=`https://${e}`);const{data:a}=await t.http.get(`/api/v1/link-preview?url=${encodeURIComponent(n)}`);return a},getLinkPreviewMetadata:async e=>{const t=Xe(),{data:n}=await t.http.get(`/api/v1/link-preview?url=${e}`);return n},getSocialSettings:oo,getShareableLinkConfiguration:async()=>{var e,t;const n=Xe(),{data:a}=await n.http.get("/api/v3/network-settings/shareable-deep-links"),s=null!==(e=a.domain)&&void 0!==e?e:"",o=null!==(t=a.patterns)&&void 0!==t?t:{};return{domain:s,patterns:o,isEnabled(e){const{key:t}=hr[e];return!!s&&!!o[t]},getPattern(e){const{key:t}=hr[e];return o[t]||null},generateLink(e,t){const{key:n,placeholder:a}=hr[e];return s&&o[n]?s+o[n].replace(`{${a}}`,t):null}}},getProductCatalogueSetting:lo,getForYouFeedSetting:uo,loginAsVisitor:qi,loginAsBot:async e=>{const t=Xe();let n;t.log("client/api/connectClient",{apiKey:t.apiKey,sessionState:t.sessionState});const a=await xn();let s;try{const{users:o,userType:i}=await mr({params:{deviceId:a},options:{setAccessTokenCookie:!0}});[s]=o,t.userId=s.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),To({user:s,userType:i})}catch(e){throw Sn().setSessionState("notLoggedIn"),e}return await so(),0===gr.length&&gr.push(ki((e=>{So(),gr.forEach((e=>e())),n()})),Pi((e=>{Sn().setSessionState(e),wo(),gr.forEach((e=>e()))}))),!0},getCurrentUser:Qt,getCurrentUserType:()=>{if(!Oo)throw new Je("Connect client first",8e5,"fatal");return Oo},setCurrentUserType:Ao,setAccessTokenHandler:e=>{const t=Xe();if(t.log("client/api/setAccessTokenHandler",{apiKey:t.apiKey,sessionState:t.sessionState,hasOnTokenRenew:"function"==typeof(null==e?void 0:e.onTokenRenew)}),!e||"function"!=typeof e.onTokenRenew)throw new Error("AccessTokenHandler must implement onTokenRenew() method");t.accessTokenHandler=e},getChatSettings:Jn,getLiveViewerCountConfig:co,getCoreUserSettings:io,notifications:()=>new Ir,enableAutoSubscriptions:e=>{const t=Dn();e.forEach((e=>t.subscribe(e)))},disableAutoSubscriptions:e=>{const t=Dn();e.forEach((e=>t.unsubscribe(e)))},autoSubscriptions:()=>Dn().subscriptions(),onConnectionError:Ti,onClientDisconnected:e=>Ti((({code:t})=>{800211===t&&e()})),onClientBanned:Ri,onSessionStateChange:On,onNetworkActivities:e=>yn().onNetworkActivities(e),onVisitorUsageLimitReached:e=>{const t=Xe();return Nt(t,"client/onVisitorUsageLimitReached","visitorUsageLimitReached",e)},getUserUnread:e=>{const{_id:t}=jt();if(!t)throw new Je("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=Xe();a||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const s=[];let o,i=!1;const r=t=>{const{data:n}=t,a=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;o=a?Pr(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return s.push(Or((e=>(e=>{var n;const a=e.filter((e=>t===e.userId)),s=a.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),i={unreadCount:null!==(n=null==s?void 0:s.unreadCount)&&void 0!==n?n:0,isMentioned:a.some((e=>!!e.isMentioned))};Ga(o,i)||r({loading:!1,data:i})})(e)))),(()=>{const e=$e(ua);Qe(e,(({error:e,data:t,loading:n,origin:a,cachedAt:o})=>{!function(e){return null!=e&&null!=e}(t)?r({loading:n,data:void 0,origin:a,error:e}):(o===Ie?(r({data:t,origin:a,loading:!1,error:new He(be,800800,"error")}),i=!0,s.forEach((e=>e()))):i||r({loading:n,data:t,origin:a,error:e}),e&&s.forEach((e=>e())))}))})(),()=>{s.forEach((e=>e()))}},getMarkerSyncEvents:()=>tr,setMarkerSyncEvents:nr,pushMarkerSyncEvent:e=>tr.push(e),markerSyncTrigger:ar,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{Yi=!1,nr([]),Xi.forEach((e=>e())),Xi=[]},getMarkerSyncConsistentMode:sr});const Ur=(e,t)=>{const n=Xe();return Nt(n,e,e,(e=>{const a=li(e);n.cache?(Hn(a),t(a.follows[0])):t(a.follows[0])}))},jr=(e,t)=>{const n=Xe();return Nt(n,e,e,(e=>{const a=hi(e);n.cache?(Hn(a),t(a.follows[0])):t(a.follows[0])}))},Er=e=>Ur("follow.created",e),Mr=e=>Ur("follow.unfollowed",e),qr=e=>Ur("follow.followerDeleted",e),xr=e=>Ur("follow.requested",e),Kr=e=>Ur("follow.requestCanceled",e),Nr=e=>Ur("follow.accepted",e),Fr=e=>Ur("follow.requestDeclined",e),_r=async e=>{var t,n;const a=Xe();a.log("follow/getFollowInfo",e);const{data:s}=await a.http.get(a.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),o=a.cache&&Date.now(),i="follows"in s?Object.assign(Object.assign({},s.followCounts[0]),{status:null===(n=null===(t=s.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):s.followCounts[0];return a.cache&&it(["followInfo","get",e],i,{cachedAt:o}),{data:i,cachedAt:o}};_r.locally=e=>{const t=Xe();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=ot(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Br=e=>{const t=async t=>{const[{data:n},{data:a}]=await Promise.all([_r(t.from),_r(t.to)]);e(n),e(a)},n=[Ur("follow.created",t),Ur("follow.requested",t),Ur("follow.accepted",t),Ur("follow.unfollowed",t),Ur("follow.requestCanceled",t),Ur("follow.requestDeclined",t),Ur("follow.followerDeleted",t),jr("local.follow.created",t),jr("local.follow.requested",t),jr("local.follow.accepted",t),jr("local.follow.unfollowed",t),jr("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},$r=e=>jr("local.follow.created",e),Lr=e=>jr("local.follow.unfollowed",e),Qr=e=>jr("local.follow.requested",e),Vr=e=>jr("local.follow.accepted",e),Jr=e=>jr("local.follow.requestDeclined",e);class Hr{constructor(e){const{http:t}=Xe();this.queryParams=e,this.http=t}loadFirstPage(){return this.onFetch("first")}loadNextPage(){return this.onFetch("next")}loadPreviousPage(){return this.onFetch("prev")}async onFetch(e="first"){var t,n,a,s;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let o;"prev"===e&&(o=this.previousToken),"next"===e&&(o=this.nextToken);const i=await this.getRequest(this.queryParams,o);return"first"===e&&(this.nextToken=null===(t=i.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=i.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(a=i.paging)||void 0===a?void 0:a.previous),"next"===e&&(this.nextToken=null===(s=i.paging)||void 0===s?void 0:s.next),i}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class Wr extends Hr{async getRequest(e,t){const{limit:n=pe,userId:a}=e,s=zn(e,["limit","userId"]),o=t?{token:t}:{limit:n},i=Xe().userId===a?"/api/v4/me/followers":`/api/v4/users/${a}/followers`,{data:r}=await this.http.get(i,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:!1})});return r}}class zr{constructor(e,t){this.query=e,this.cacheKey=t}}var Gr;!function(e){e.OnRequested="onRequested",e.OnAccepted="onAccepted",e.OnDeclined="onDeclined",e.OnCanceled="onCanceled",e.OnFollowed="onFollowed",e.OnUnfollowed="onUnfollowed",e.OnDeleted="onDeleted",e.OnUserDeleted="onUserDeleted"}(Gr||(Gr={}));class Yr extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.follows.map(tt("follow"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(tt("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&a){switch(e){case Gr.OnDeclined:case Gr.OnCanceled:case Gr.OnUnfollowed:case Gr.OnDeleted:a.data=a.data.filter((e=>e!==tt("follow")(t)));break;case Gr.OnRequested:case Gr.OnAccepted:case Gr.OnFollowed:a.data=[...new Set([tt("follow")(t),...a.data])]}it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Xr{constructor(e){const{http:t}=Xe();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class Zr{constructor(e,t,n,a){this.paginationController=e,this.queryStreamId=t,this.cacheKey=n,this.callback=a}async refresh(){try{let e;if(e=this.paginationController instanceof Xr?await this.paginationController.onFetch():await this.paginationController.loadFirstPage(),!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next",refresh:!0}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}loadPage({initial:e=!1,direction:t="next"}){this.setup(),this.notifyChange({origin:"local",loading:!0}),e?this.refresh():"prev"===t?this.loadPrevPage():"next"===t&&this.loadNextPage()}async loadNextPage(){try{if(this.paginationController instanceof Xr)return;const e=await this.paginationController.loadNextPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}async loadPrevPage(){try{if(this.paginationController instanceof Xr)return;const e=await this.paginationController.loadPreviousPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"prev"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}shouldNotify(e){const t=e.map(Pr).map(kr);return!Ga(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function ec(e){return null!=e}const tc=({userId:e})=>t=>{const n=Xe();return Nt(n,"user.deleted","user.deleted",(n=>{const a=bo(n);Hn(a);const s=ot(["follow","get",tt("follow")({from:a.users[0].userId,to:e})]);s&&t(null==s?void 0:s.data)}))};class nc extends Zr{constructor(e,t){const n=P.default(Object.assign(Object.assign({},e),{type:"follower"})),a=["follow","collection",n];super(new Wr(e),n,a,t),this.query=e,this.queryStreamController=new Yr(this.query,this.cacheKey,this.notifyChange.bind(this),li),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Er,action:Gr.OnFollowed},{fn:Mr,action:Gr.OnUnfollowed},{fn:Nr,action:Gr.OnAccepted},{fn:Fr,action:Gr.OnDeclined},{fn:Kr,action:Gr.OnCanceled},{fn:qr,action:Gr.OnDeleted},{fn:Vr,action:Gr.OnAccepted},{fn:Jr,action:Gr.OnDeclined},{fn:$r,action:Gr.OnFollowed},{fn:Lr,action:Gr.OnUnfollowed},{fn:tc({userId:this.query.userId}),action:Gr.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["follow","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=ot(["user","get",e.from]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}class ac extends Hr{async getRequest(e,t){const{limit:n=pe,userId:a}=e,s=zn(e,["limit","userId"]),o=t?{token:t}:{limit:n},i=Xe().userId===a?"/api/v4/me/following":`/api/v4/users/${a}/following`,{data:r}=await this.http.get(i,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:!1})});return r}}class sc extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.follows.map(tt("follow"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(tt("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&a){switch(e){case Gr.OnDeclined:case Gr.OnCanceled:case Gr.OnUnfollowed:case Gr.OnDeleted:a.data=a.data.filter((e=>e!==tt("follow")(t)));break;case Gr.OnRequested:case Gr.OnAccepted:case Gr.OnFollowed:a.data=[...new Set([tt("follow")(t),...a.data])]}it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const oc=({userId:e})=>t=>{const n=Xe();return Nt(n,"user.deleted","user.deleted",(n=>{const a=bo(n);Hn(a);const s=ot(["follow","get",tt("follow")({from:e,to:a.users[0].userId})]);s&&t(null==s?void 0:s.data)}))};class ic extends Zr{constructor(e,t){const n=P.default(Object.assign(Object.assign({},e),{type:"following"})),a=["follow","collection",n];super(new ac(e),n,a,t),this.query=e,this.queryStreamController=new sc(this.query,this.cacheKey,this.notifyChange.bind(this),ui),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:xr,action:Gr.OnRequested},{fn:Nr,action:Gr.OnAccepted},{fn:Fr,action:Gr.OnDeclined},{fn:Kr,action:Gr.OnCanceled},{fn:Er,action:Gr.OnFollowed},{fn:Mr,action:Gr.OnUnfollowed},{fn:qr,action:Gr.OnDeleted},{fn:Qr,action:Gr.OnRequested},{fn:Vr,action:Gr.OnAccepted},{fn:Jr,action:Gr.OnDeclined},{fn:$r,action:Gr.OnFollowed},{fn:Lr,action:Gr.OnUnfollowed},{fn:oc({userId:this.query.userId}),action:Gr.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["follow","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=ot(["user","get",e.to]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}const rc=(e,t,n,a,s,o)=>{const{forceDispatch:i,callbackDataSelector:r,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},o),{cache:d}=Xe();let l;d||console.log("For using Live Object feature you need to enable Cache!");let u=!1;const h=[],m=e=>{const{data:n}=e,a=zn(e,["data"]);c&&!c(n,l)||t(Object.assign({data:r(n)},a)),l=Pr(n)};return h.push(...s.map((t=>t((t=>((t,a=!1)=>{e===t[n]&&(l&&!a&&Ga(l,t)||m({loading:!1,data:t,origin:"event"}))})(t,i)))))),(()=>{const t=$e(a,e,!0);Qe(t,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{s===Ie?(m({data:t,origin:a,loading:!1,error:new He(be,800800,"error")}),u=!0,h.forEach((e=>e()))):u||m({loading:n,data:t,origin:a,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var cc=Object.freeze({__proto__:null,blockUser:async e=>{const t=Xe();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),a=t.cache&&Date.now(),{follows:s,followCounts:o}=n,i={follows:s};t.cache&&(Hn(i,{cachedAt:a}),ct(["followInfo","get",e],o[0],{cachedAt:a}));const r={follows:s.map((e=>{const t=Object.assign(Object.assign({},e),{to:e.from,from:e.to,status:"none"});return"blocked"===e.status?t:e}))},c=hi(r);return Ft("local.follow.unfollowed",c),n},unBlockUser:async e=>{const t=Xe();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),a=t.cache&&Date.now(),{follows:s,followCounts:o}=n,i={follows:s};t.cache&&(Hn(i,{cachedAt:a}),ct(["followInfo","get",e],o[0],{cachedAt:a}));const r=hi(i);return Ft("local.follow.created",r),n},onUserDidBlock:gi,onUserDidUnblock:pi,follow:async e=>{const t=Xe();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),a=t.cache&&Date.now();t.cache&&Hn(n,{cachedAt:a});const s=hi(n);return"accepted"===n.follows[0].status?Ft("local.follow.created",s):Ft("local.follow.requested",s),{data:n.follows[0],cachedAt:a}},unfollow:async e=>{const t=Xe();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Hn(n);const a=hi(n);return Ft("local.follow.unfollowed",a),!0},acceptMyFollower:async e=>{const t=Xe();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Hn(n);const a=hi(n);return Ft("local.follow.accepted",a),!0},declineMyFollower:async e=>{const t=Xe();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Hn(n);const a=hi(n);return Ft("local.follow.requestDeclined",a),!0},onUserFollowed:Er,onUserUnfollowed:Mr,onFollowerDeleted:qr,onFollowerRequested:xr,onFollowRequestCanceled:Kr,onFollowRequestAccepted:Nr,onFollowRequestDeclined:Fr,onFollowInfoUpdated:Br,onLocalUserFollowed:$r,onLocalUserUnfollowed:Lr,onLocalFollowerRequested:Qr,onLocalFollowRequestAccepted:Vr,onLocalFollowRequestDeclined:Jr,getFollowers:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getFollowers(tmpid: ${o}) > listen`);const i=new nc(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getFollowers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();a(`getFollowings(tmpid: ${o}) > listen`);const i=new ic(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getFollowings(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getFollowInfo:(e,t)=>rc(e,t,"userId",_r,[Br],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=jt();return rc(t,e,"userId",_r,[Br],{forceDispatch:!0})}});function dc(e,t){return e.map((e=>{const n=ot(["community","get",e.communityId]);if((null==n?void 0:n.data)&&(null==n?void 0:n.data.hasOwnProperty("isJoined")))return Object.assign(Object.assign({},n.data),e);const a=void 0!==e.isJoined?e.isJoined:t.some((t=>function(e,t){const{userId:n}=jt();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:a})}))}const lc=e=>{var t;return null!==(t=Object.keys(K).find((t=>e.needApprovalOnPostCreation===K[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===K[t].onlyAdminCanPost)))&&void 0!==t?t:N};function uc({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,a=zn(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:lc({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},a)}))}const hc=e=>{const t=uc({communities:e.communities}),n=e.users.map(Sa),a=e.communityUsers.map((e=>{const t=n.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),s=dc(t,a);return Object.assign(Object.assign({},e),{users:e.users.map(Sa),communities:s,communityUsers:a})},mc=e=>{const t=e.joinRequests.map((e=>Object.assign(Object.assign({},e),{joinRequestId:e._id}))),n=e.users.map(Sa);return Object.assign(Object.assign({},e),{joinRequests:t,users:n})},gc=e=>{const t=uc({communities:e.communities}),n=e.communityUsers.map((t=>{const n=e.users.find((e=>e.userId===t.userId));return Object.assign(Object.assign({},t),{user:n})})),a=dc(t,n);return Object.assign(Object.assign({},e),{communities:a,communityUsers:n})},pc=e=>{const{postSetting:t,storySetting:n}=e,a=zn(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},a),t?K[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},yc=e=>{var t=zn(e,["searchResult"]);const n=hc(t);return Object.assign({},n)},vc=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=ot(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return Lt(n)},cancel:async()=>{await(async e=>{var t;const n=Xe();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:a}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),s=null===(t=ot(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(ct(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),Ft("local.joinRequest.deleted",[s])),a.success})(e)},approve:async()=>{await(async e=>{var t;const n=Xe();n.log("joinRequest/approveJoinRequest",e.joinRequestId);const{data:a}=await n.http.post(`/api/v4/communities/${e.targetId}/join/approve`,{userId:e.requestorInternalId}),s=null===(t=ot(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(ct(["joinRequest","get",e.joinRequestId],{status:"approved"}),Ft("local.joinRequest.updated",[s])),a.success})(e)},reject:async()=>{await(async e=>{var t;const n=Xe();n.log("joinRequest/rejectJoinRequest",e.joinRequestId);const{data:a}=await n.http.post(`/api/v4/communities/${e.targetId}/join/reject`,{userId:e.requestorInternalId}),s=null===(t=ot(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(ct(["joinRequest","get",e.joinRequestId],{status:"rejected"}),Ft("local.joinRequest.updated",[s])),a.success})(e)}});class fc extends Hr{async getRequest(e,t){const{limit:n=20,communityId:a}=e,s=zn(e,["limit","communityId"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get(`/api/v4/communities/${a}/join`,{params:Object.assign(Object.assign({},s),{options:o})});return i}}var bc;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(bc||(bc={}));class Ic extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.joinRequests.map((e=>tt("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>tt("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===bc.OnLocalJoinRequestUpdated){if(!a.data.find((e=>e===t[0].joinRequestId)))return}e===bc.OnLocalJoinRequestCreated&&(a.data=[...new Set([...t.map((e=>e.joinRequestId)),...a.data])]),e===bc.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>e!==t[0].joinRequestId))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Cc=e=>{const t=Xe(),n=[Nt(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},wc=e=>{const t=Xe(),n=[Nt(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Sc=e=>{const t=Xe(),n=[Nt(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Oc extends Zr{constructor(e,t){const n=P.default(e),a=["joinRequest","collection",n];super(new fc(e),n,a,t),this.query=e,this.queryStreamController=new Ic(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const a=e;this.queryStreamController.appendToQueryStream(a,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Cc,action:bc.OnLocalJoinRequestCreated},{fn:wc,action:bc.OnLocalJoinRequestUpdated},{fn:Sc,action:bc.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(s.data.map((e=>ot(["joinRequest","get",e]))).filter(ec).map((({data:e})=>e)).map(vc));(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.status&&(t=t.filter((e=>e.status===this.query.status)));const n=(()=>"firstCreated"===this.query.sortBy?St:At)();return t=t.sort(n),t}}const Ac=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),Tc=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map(Ac),users:e.users.map(Sa)}),Rc=async e=>{const t=Xe();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),a=Tc(n),s=t.cache&&Date.now();return t.cache&&Hn(a,{cachedAt:s}),Ft("local.invitation.created",a.invitations),{data:a.invitations,cachedAt:s}},Pc=e=>Object.assign(Object.assign({},e),{users:e.users.map(Sa),invitations:e.invitations.map(Ac)}),kc=e=>Object.assign(Object.assign({},e),{get user(){const t=ot(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return Lt(t.data)},get createdBy(){const t=ot(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return Lt(t.data)},get target(){if("community"===e.targetType){const t=ot(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=Xe();n.log("invitation/acceptInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/accept`),s=null===(t=ot(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(ct(["invitation","get",e],{status:"approved"}),Ft("local.invitation.updated",[s])),a.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=Xe();n.log("invitation/rejectInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/reject`),s=null===(t=ot(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(ct(["invitation","get",e],{status:"rejected"}),Ft("local.invitation.updated",[s])),a.success})(e._id)}}),Dc=async e=>{const t=Xe();t.log("invitation/getInvitation",e.targetType,e.targetId,e.type);const{data:n}=await t.http.get("/api/v1/invitations/me",{params:e}),a=Pc(n),s=t.cache&&Date.now();return t.cache&&Hn(a,{cachedAt:s}),{data:a.invitations[0]?kc(a.invitations[0]):void 0,cachedAt:s}};var Uc;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationCanceled="onLocalInvitationCanceled"}(Uc||(Uc={}));class jc extends Hr{async getRequest(e,t){const{limit:n=pe}=e,a=zn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/invitations",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class Ec extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.invitations.map(tt("invitation"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(tt("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Uc.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}e===Uc.OnLocalInvitationCreated&&(a.data=[...new Set([...t.map((e=>e.invitationId)),...a.data])]),e===Uc.OnLocalInvitationDeleted&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Mc=e=>{const t=Xe(),n=[Nt(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},qc=e=>{const t=Xe(),n=[Nt(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},xc=e=>{const t=Xe(),n=[Nt(t,"onLocalInvitationCanceled","local.invitation.canceled",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Kc extends Zr{constructor(e,t){const n=P.default(e),a=["invitation","collection",n];super(new jc(e),n,a,t),this.query=e,this.queryStreamController=new Ec(this.query,this.cacheKey,this.notifyChange.bind(this),Tc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Mc,action:Uc.OnLocalInvitationCreated},{fn:qc,action:Uc.OnLocalInvitationUpdated},{fn:xc,action:Uc.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["invitation","get",e]))).filter(ec).map((({data:e})=>kc(e))))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?St:At)();return t=t.sort(n),t}}const Nc=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=ot(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),Fc=e=>Object.assign(Object.assign({},e),{get categories(){var t;return(null!==(t=null==e?void 0:e.categoryIds)&&void 0!==t?t:[]).map((e=>{const t=ot(["category","get",e]);if(null==t?void 0:t.data)return Nc(t.data)})).filter((e=>!!e))},get avatar(){var t;if(!e.avatarFileId)return;return null===(t=ot(["file","get",e.avatarFileId]))||void 0===t?void 0:t.data},createInvitations:async t=>{await Rc({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getInvitations: (tmpid: ${o}) > listen`);const i=new Kc(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{dt(c)})),()=>{a(`getInvitations (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{targetId:e.communityId,targetType:"community",type:"communityMemberInvite"}),n),getInvitation:async()=>{const{data:t}=await Dc({targetType:"community",targetId:e.communityId});return t},join:async()=>(async e=>{var t;const n=Xe();n.log("community/joinRequest",e);const{data:a}=await n.http.post(`/api/v4/communities/${e}/join`),s=mc(a),o=n.cache&&Date.now();n.cache&&Hn(s,{cachedAt:o});const i="approved"===s.joinRequests[0].status?"success":"pending";if("success"===i&&n.cache){const n=null===(t=ot(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});ct(["community","get",e],t)}}return Ft("v4.local.community.joined",s.joinRequests),"success"===i?{status:i}:{status:i,request:vc(s.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getJoinRequests: (tmpid: ${o}) > listen`);const i=new Oc(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{dt(c)})),()=>{a(`getJoinRequests (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{communityId:e.communityId}),n),getMyJoinRequest:async()=>{const{data:t}=await(async e=>{const t=Xe();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),a=mc(n),s=t.cache&&Date.now();return t.cache&&Hn(a,{cachedAt:s}),{data:a.joinRequests[0]?vc(a.joinRequests[0]):void 0,cachedAt:s}})(e.communityId);return t}});class _c{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=ot(["story-expire",this._targetId]),this.cacheStoreSeenTime=ot(["story-last-seen",this._targetId]),this.getTotalStoryByStatus()}get lastStoryExpiresAt(){return this._lastStoryExpiresAt?new Date(this._lastStoryExpiresAt).getTime():0}get lastStorySeenExpiresAt(){return this._lastStorySeenExpiresAt?new Date(this._lastStorySeenExpiresAt).getTime():0}get localLastStoryExpires(){var e,t;return(null===(e=this.cacheStoryExpireTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoryExpireTime)||void 0===t?void 0:t.data).getTime():0}get localLastStorySeenExpiresAt(){var e,t;return(null===(e=this.cacheStoreSeenTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoreSeenTime)||void 0===t?void 0:t.data).getTime():0}get isContainUnSyncedStory(){const e=ot(["story-sync-state",this._targetId]);return!!(null==e?void 0:e.data)&&["syncing","error"].includes(e.data)}getLocalLastSortingDate(){return this.isContainUnSyncedStory?this.localLastStoryExpires:this.lastStoryExpiresAt}getHasUnseenFlag(){const e=(new Date).getTime(),t=Math.max(this.lastStorySeenExpiresAt,this.localLastStorySeenExpiresAt);return ot(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=st(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:a,isDeleted:s}}=t;return n!==this._targetId||s||(e[a]+=1),e}),{syncing:0,error:0,synced:0});this._errorStoriesCount=t.error,this._syncingStoriesCount=t.syncing}get syncingStoriesCount(){return this._syncingStoriesCount}get failedStoriesCount(){return this._errorStoriesCount}}const Bc=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:a,lastStorySeenExpiresAt:s,targetUpdatedAt:o,localFilter:i}=e,r=new _c(n,a,s);return{targetType:t,targetId:n,lastStoryExpiresAt:a,updatedAt:o,hasUnseen:r.getHasUnseenFlag(),syncingStoriesCount:r.syncingStoriesCount,failedStoriesCount:r.failedStoriesCount,localFilter:i,localLastExpires:r.localLastStoryExpires,localLastSeen:r.localLastStorySeenExpiresAt,localSortingDate:r.getLocalLastSortingDate()}},$c=async e=>{const t=Xe();let n;if(t.log("user/createChannel",e),"conversation"===(null==e?void 0:e.type))n=await t.http.post("/api/v3/channels/conversation",Object.assign(Object.assign({},e),{isDistinct:!0}));else{const{isPublic:a}=e,s=zn(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},s),{isPublic:"community"===(null==e?void 0:e.type)?a:void 0}))}Ft("channel.created",n.data);const a=await Na(n.data),s=t.cache&&Date.now();t.cache&&Hn(a,{cachedAt:s});const{channels:o}=a;return{data:Ws(o[0]),cachedAt:s}},Lc=async e=>{const t=Xe();let n;t.log("channel/getChannel",e),ca("channel",e);try{const{data:a}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await Na(a),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&Qa(a)}catch(t){throw De(null==t?void 0:t.code)&&Wn("channel",e),t}const a=t.cache&&Date.now();t.cache&&Hn(n,{cachedAt:a});const{channels:s}=n;return{data:s.find((t=>t.channelId===e)),cachedAt:a}};Lc.locally=e=>{var t;const n=Xe();if(n.log("channel/getChannel.locally",e),!n.cache)return;const a=null===(t=st(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId===e));return a&&0!==(null==a?void 0:a.length)?{data:a[0].data,cachedAt:a[0].cachedAt}:void 0};const Qc=Symbol("getWatcherUrls"),Vc=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=ot(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=ot(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=ot(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=ot(["user","get",e.userId]))||void 0===t?void 0:t.data},get childStreams(){return e.childStreamIds&&0!==e.childStreamIds.length?e.childStreamIds.map((e=>{var t;const n=null===(t=ot(["stream","get",e]))||void 0===t?void 0:t.data;if(n)return Vc(n)})).filter(ec):[]},getLiveChat:()=>(async e=>{var t;const n=Xe();if(n.log("stream/getLiveChat",e.streamId),e.channelId){const n=null===(t=ot(["channel","get",e.channelId]))||void 0===t?void 0:t.data;if(n)return Hs(Ws(n));const{data:a}=await Lc(e.channelId);return Hs(Ws(a))}if(e.userId===n.userId){const{data:t}=await $c({type:"live",postId:e.postId,videoStreamId:e.streamId});return rt(["stream","get",e.streamId],{channelId:t.channelId}),t}})(e),isBanned:!e.watcherUrl,watcherUrl:null,get[Qc](){return e.watcherUrl}}),Jc=["pending","approved","rejected"],Hc=e=>e&&Jc.includes(e)?e:"approved",Wc=e=>Object.assign(Object.assign(Object.assign({},e.hasOwnProperty("myReactions")?{}:{myReactions:[]}),e),{approvalStatus:Hc(e.approvalStatus)});function zc(e){const{comments:t,commentChildren:n}=e;return Object.assign(Object.assign(Object.assign({},e),{comments:t.map(Wc)}),n?{commentChildren:n.map(Wc)}:{})}const Gc=e=>Object.assign(Object.assign({},e),{approvalStatus:Hc(e.approvalStatus),get target(){const t={type:e.targetType};if("user"===e.targetType)return Object.assign(Object.assign({},t),{userId:e.targetId});if("content"===t.type)return Object.assign(Object.assign({},t),{contentId:e.targetId});if("community"===t.type){const n=ot(["communityUsers","get",`${e.targetId}#${e.userId}`]);return Object.assign(Object.assign({},t),{communityId:e.targetId,creatorMember:null==n?void 0:n.data})}return{type:"unknown"}},get creator(){const t=ot(["user","get",e.userId]);if(null==t?void 0:t.data)return Lt(t.data)},get childrenComment(){return e.children.map((e=>{const t=ot(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(ec).map((e=>Gc(e)))}});function Yc(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}function Xc(e){return!(!e.data||"string"==typeof e.data||!("streamId"in e.data)||"liveStream"!==e.dataType)}class Zc{constructor(){this.sessions=new Map}addSession(e){this.sessions.set(e.sessionId,e)}getSession(e){return this.sessions.get(e)}updateSession(e,t){const n=this.sessions.get(e);n&&this.sessions.set(e,Object.assign(Object.assign({},n),t))}getSessionsByState(e){return Array.from(this.sessions.values()).filter((t=>t.syncState===e))}deleteSession(e){this.sessions.delete(e)}getPendingSessions(){return this.getSessionsByState("PENDING")}getSyncingSessions(){return this.getSessionsByState("SYNCING")}}let ed=null;const td=()=>(ed||(ed=new Zc),ed),nd={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},ad="-----BEGIN PRIVATE KEY-----";function sd(e){const n=new Uint8Array(e);let a="";return n.forEach((e=>{a+=String.fromCharCode(e)})),t.btoa(a)}function od(e){return e<128?new Uint8Array([e]):e<256?new Uint8Array([129,e]):new Uint8Array([130,e>>8&255,255&e])}async function id(e){let n=e;n=e.includes(ad)?e.substring(ad.length,e.length-"-----END PRIVATE KEY-----".length).replace(/\s/g,""):e.replace(/\s/g,"");const a=t.atob(n),s=new Uint8Array(a.length);for(let e=0;e<a.length;e+=1)s[e]=a.charCodeAt(e);const o=function(e){const t=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),n=new Uint8Array([2,1,0]),a=od(e.length),s=n.length+t.length+1+a.length+e.length,o=od(s),i=new Uint8Array(1+o.length+s);let r=0;return i[r]=48,r+=1,i.set(o,r),r+=o.length,i.set(n,r),r+=n.length,i.set(t,r),r+=t.length,i[r]=4,r+=1,i.set(a,r),r+=a.length,i.set(e,r),i}(s);return await crypto.subtle.importKey("pkcs8",o.buffer,nd,!1,["sign"])}async function rd({timestamp:e,rooms:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),a=O.default.v4(),s=`nonceStr=${a}&timestamp=${e}&data=${n}==`,o=(new TextEncoder).encode(s),i=await id("-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHo80SecH7FuF2\nhFYnb+l26/VN8UMLXAQFLnxciNTEwkGVFMpdezlH8rU2HtUJL4RETogbAOLVY0XM\njs6sPn8G1nALmh9qeDpUtVqFOVtBHxEZ910TLOtQiunjqJKO5nWdqZ71EC3OFluR\niGQkO84BiIFbv37ub7xl3S8XarbtKoLcyVpkDHi+1wx1pgCAn6gtBUgckPL5NR8j\nLseabl3HAXQfhTCKo4tmOFM2Dxwl1IUMmIJrJg/aIU/U0tj/1Eoo7mG0JcNWX19l\nW3EecCbi0ncCJOrkUdwlBrcjaMayaX/ubEwyUeTGiLdyc4L3GRLHjyK8xgVNXRMH\nbZWJ2a5NAgMBAAECggEASxuE+35zTFO/XydKgmvIGcWL9FbgMlXb7Vcf0nBoG945\nbiz0NVc2paraIhJXc608xbYF3qLmtAE1MVBI0ORyRdBHNxY024l/6H6SH60Ed+uI\nM4ysp5ourY6Vj+DLwpdRiI9YDjqYAQDIUmhNxJP7XPhOMoZI6st+xZQBM34ic/bv\nAMSJm9OZphSp3+qXVkFZztr2mxD2EZSJJLYxi8BCdgM2qhazalbcJ6zDKHCZWVWm\n8RRxDGldyMb/237JxETzP40tAlzOZDmBAbUgEnurDJ93RVDIE3rbZUshwgeQd18a\nem096mWgvB1AIKYgsTAR3pw+V19YWAjq/glP6fz8wQKBgQD/oQq+ukKF0PRgBeM5\ngeTjSwsdGppQLmf5ndujvoiz/TpdjDEPu6R8kigQr1rG2t4K/yfdZoI8RdmJD1al\n3Q7N9hofooSy4rj6E3txzWZCHJjHad2cnCp/O26HiReGAl7wTcfTmNdiFHhZQzm5\nJBkvWAiwuvQMNfEbnXxw6/vIDwKBgQDH7fX8gsc77JLvAWgp1MaQN/sbqVb6JeT1\nFQfR8E/WFCSmzQBtNzd5KgYuCeelwr/8DyYytvN2BzCYZXp73gI1jF3YlW5jVn74\nOY6TwQ095digwo6Z0yuxopdIOApKgAkL9PRKgNrqAf3NAyMua6lOGifzjDojC3KU\nfylQmxMn4wKBgHp2B9O/H0dEBw5JQ8W0+JX6yWQz7mEjGiR2/1W+XXb8hQ1zr709\nw1r6Gb+EghRpnZ3fBpYGGbYOMFx8wKHM+N6qW3F0ReX8v2juFGE8aRSa5oYBrWzt\nU16Idjbv8hj84cZ1PJmdyvDtpYn9rpWHOZl4rxEbPvbqkIsOMyNVqdT5AoGAOSge\nmwIIU2le2FVeohbibXiToWTYKMuMmURZ5/r72AgKMmWJKbAPe+Q3wBG01/7FRBpQ\noU8Ma0HC8s6QJbliiEyIx9JwrJWd1vkdecBHONrtA4ibm/5zD2WcOllLF+FitLhi\n3qnX6+6F0IaFGFBPJrTzlv0P4dTz/OAdv52V7GECgYEA2TttOKBAqWllgOaZOkql\nLVMJVmgR7s6tLi1+cEP8ZcapV9aRbRzTAKXm4f8AEhtlG9F9kCOvHYCYGi6JaiWJ\nZkHjeex3T+eE6Di6y5Bm/Ift5jtVhJ4jCVwHOKTMej79NPUFTJfv8hCo29haBDv6\nRXFrv+T21KCcw8k3sJeJWWQ=\n-----END PRIVATE KEY-----");return{signature:sd(await crypto.subtle.sign(nd,i,o)),nonceStr:a}}async function cd(){const e=td(),t=e.getPendingSessions();if(0===t.length)return!0;try{const n=(new Date).toISOString(),a=t.map((e=>({sessionId:e.sessionId,roomId:e.roomId,watchSeconds:e.watchSeconds,startTime:e.startTime.toISOString(),endTime:e.endTime?e.endTime.toISOString():""}))),s=await rd({timestamp:n,rooms:a});if(!s||!s.signature)throw new Error("Signature is undefined");t.forEach((t=>{e.updateSession(t.sessionId,{syncState:"SYNCING"})}));const o={signature:s.signature,nonceStr:s.nonceStr,timestamp:n,rooms:a},i=Xe();return await i.http.post("/api/v3/user-event/room",o),t.forEach((t=>{e.updateSession(t.sessionId,{syncState:"SYNCED",syncedAt:new Date})})),!0}catch(n){return console.error("[SDK syncWatchSessions] ERROR caught:",(null==n?void 0:n.message)||n),t.forEach((t=>{const n=e.getSession(t.sessionId);if(n){const a=n.retryCount+1;a>=3?e.deleteSession(t.sessionId):e.updateSession(t.sessionId,{syncState:"PENDING",retryCount:a})}})),!1}}const dd=["live","recorded"];class ld{constructor(e){this.storage=td(),this.client=Xe(),this.room=e}async createWatchSession(e){if(!dd.includes(this.room.status))throw new He("room is not in watchable state",5e5,"error");const t=("live"===this.room.status?"room_":"room_playback_")+O.default.v4(),n={sessionId:t,roomId:this.room.roomId,watchSeconds:0,startTime:e,endTime:null,syncState:"PENDING",syncedAt:null,retryCount:0};return this.storage.addSession(n),t}async updateWatchSession(e,t,n){if(!this.storage.getSession(e))throw new Error(`Watch session ${e} not found`);this.storage.updateSession(e,{watchSeconds:t,endTime:n})}syncPendingWatchSessions(){const e=Math.floor(25001*Math.random())+5e3;this.client.log("room/RoomAnalytics: syncPendingWatchSessions called, jitter delay:",`${e}ms`),setTimeout((async()=>{this.client.log("room/RoomAnalytics: Jitter delay completed, starting sync process");try{const e=this.storage.getSyncingSessions();this.client.log("room/RoomAnalytics: SYNCING sessions to reset:",e.length),e.forEach((e=>{this.storage.updateSession(e.sessionId,{syncState:"PENDING"})})),await((e=6e4)=>new Promise((t=>{if("undefined"==typeof navigator||void 0===navigator.onLine)return void t();const n=Date.now(),a=()=>{navigator.onLine||Date.now()-n>=e?t():setTimeout(a,1e3)};a()})))(6e4),this.client.log("room/RoomAnalytics: Network available"),this.client.log("room/RoomAnalytics: Calling syncWatchSessions()"),await cd(),this.client.log("room/RoomAnalytics: syncWatchSessions completed")}catch(e){console.error("Failed to sync watch sessions:",e)}}),e)}}const ud=e=>Object.assign(Object.assign({},e),{get post(){var t;if("post"===e.referenceType)return null===(t=ot(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=ot(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;const n=null===(t=ot(["user","get",e.createdBy]))||void 0===t?void 0:t.data;return n?Lt(n):n},get childRooms(){return e.childRoomIds&&0!==e.childRoomIds.length?e.childRoomIds.map((e=>{var t;const n=null===(t=ot(["room","get",e]))||void 0===t?void 0:t.data;if(n)return ud(n)})).filter(ec):[]},participants:e.participants.map((e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=ot(["user","get",e.userId]))||void 0===t?void 0:t.data;return n?Lt(n):n}}))),getLiveChat:()=>(async e=>{var t;const n=Xe();if(n.log("room/getLiveChat",e.roomId),e.liveChannelId){const n=null===(t=ot(["channel","get",e.liveChannelId]))||void 0===t?void 0:t.data;if(n)return Hs(Ws(n));const{data:a}=await Lc(e.liveChannelId);return Hs(Ws(a))}if(e.createdBy===n.userId){const{data:t}=await $c({type:"live",postId:e.referenceId,roomId:e.roomId});return rt(["room","get",e.roomId],{liveChannelId:t.channelId}),t}})(e),createInvitation:t=>Rc({type:"livestreamCohostInvite",targetType:"room",targetId:e.roomId,userIds:[t]}),getInvitations:async()=>{const{data:t}=await Dc({targetId:e.roomId,targetType:"room",type:"livestreamCohostInvite"});return t},analytics(){return new ld(this)}}),hd=e=>Object.assign(Object.assign({},e),{answers:e.answers.map((e=>Object.assign(Object.assign({},e),{get image(){var t;if(e.fileId)return null===(t=ot(["file","get",e.fileId]))||void 0===t?void 0:t.data}})))}),md=e=>{const t=xo();return Object.assign(Object.assign({},e),{analytics:{markAsClicked:(n,a,s)=>{t.markProductAsClicked(e,n,a,s)},markAsViewed:(n,a,s)=>{t.markProductAsViewed(e,n,a,s)}}})},gd=e=>{var t,n,a;if(!e)return e;if("video"===e.type){const a=null===(n=null===(t=e.attributes)||void 0===t?void 0:t.metadata)||void 0===n?void 0:n.video;return Object.assign(Object.assign({},e),{getWidth:()=>{var e;return null!==(e=null==a?void 0:a.width)&&void 0!==e?e:0},getHeight:()=>{var e;return null!==(e=null==a?void 0:a.height)&&void 0!==e?e:0},getRotation:()=>{var e;return null!==(e=null==a?void 0:a.rotation)&&void 0!==e?e:0}})}if("image"===e.type){const t=null===(a=e.attributes)||void 0===a?void 0:a.metadata;return Object.assign(Object.assign({},e),{getWidth:()=>{var e;return null!==(e=null==t?void 0:t.width)&&void 0!==e?e:0},getHeight:()=>{var e;return null!==(e=null==t?void 0:t.height)&&void 0!==e?e:0}})}return e},pd=e=>"pending"===Hc(e.approvalStatus),yd=e=>"approved"===Hc(e.approvalStatus),vd=e=>["post","content"].includes(e.referenceType),fd=e=>{var t,n;if("post"!==e.referenceType)return!1;const a=null===(t=ot(["post","get",e.referenceId]))||void 0===t?void 0:t.data;if(!a)return!0;if("community"!==a.targetType)return!1;const s=null===(n=ot(["community","get",a.targetId]))||void 0===n?void 0:n.data;return!s||!0===s.needApprovalOnCommentCreation},bd=(e,t)=>{vd(e)&&(e=>e.userId===Xe().userId)(e)&&Oi().addPendingAuthoredComment(e.referenceId,e.commentId,t)},Id=e=>{vd(e)&&Oi().removePendingAuthoredComment(e.referenceId,e.commentId)},Cd=e=>{vd(e)&&Oi().queueCommentChangeTask(new bi(e.referenceId,e.commentId))},wd=e=>{vd(e)&&(bd(e,{publish:!1}),Oi().queueCommentChangeTask(new Ii(e.referenceId,e.commentId)))},Sd=e=>{var t;if(!e.parentId)return;const n=["comment","get",e.parentId],a=null===(t=ot(n))||void 0===t?void 0:t.data;a&&!a.children.includes(e.commentId)&&it(n,Object.assign(Object.assign({},a),{childrenNumber:a.childrenNumber+1,children:[...new Set([...a.children,e.commentId])]}))},Od=e=>{var t;if(!e.parentId)return;const n=["comment","get",e.parentId],a=null===(t=ot(n))||void 0===t?void 0:t.data;a&&a.children.includes(e.commentId)&&it(n,Object.assign(Object.assign({},a),{childrenNumber:a.childrenNumber-1,children:a.children.filter((t=>t!==e.commentId))}))},Ad=e=>void 0!==e&&!e.isDeleted&&yd(e),Td=(e,t)=>{var n,a;return a=[...null!==(n=e.comments)&&void 0!==n?n:[],t],[...new Set(a)].slice(-5)},Rd=e=>ia(e,{childrenPosts:e.children.map((e=>{var t;return null===(t=ot(["post","get",e]))||void 0===t?void 0:t.data})).filter(ec).map(Rd),analytics:{markAsViewed:()=>{xo().markPostAsViewed(e.postId)},markAsMeaningfullyViewed:t=>{xo().markPostAsMeaningfullyViewed(e.postId,t)}},get productTags(){var t,n;return null!==(n=null===(t=e.productTags)||void 0===t?void 0:t.map((e=>(e=>{var t;const n=null===(t=ot(["product","get",e.productId]))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{product:n?md(n):void 0})})(e))))&&void 0!==n?n:[]},get latestComments(){return e.comments?e.comments.map((e=>{var t;return null===(t=ot(["comment","get",e]))||void 0===t?void 0:t.data})).filter(Ad).slice(-5).map(Gc):[]},get creator(){if(!e.postedUserId)return;const t=ot(["user","get",e.postedUserId]);return(null==t?void 0:t.data)?Lt(t.data):void 0},getLocalCommentCount(t=!1){var n;const a=Oi();return a.hasTracker(e.postId)?a.getLocalCommentCount(e.postId,t):null!==(n=e.localCommentCount)&&void 0!==n?n:e.commentsCount},get targetCommunity(){var t;if(!e.targetId)return;const n=null===(t=ot(["community","get",e.targetId]))||void 0===t?void 0:t.data;return n?Fc(n):void 0},getImageInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return gd(null===(n=ot(["file","get",e.data.fileId]))||void 0===n?void 0:n.data)},getVideoInfo(){var t,n,a;const s=Yc(e)?null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original:void 0;if(s)return gd(null===(a=ot(["file","get",s]))||void 0===a?void 0:a.data)},getVideoThumbnailInfo(){var t,n;const a=Yc(e)?null===(t=e.data)||void 0===t?void 0:t.thumbnailFileId:void 0;if(a)return gd(null===(n=ot(["file","get",a]))||void 0===n?void 0:n.data)},getFileInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"file"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=ot(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getLivestreamInfo(){var t,n;if(!Xc(e)||!(null===(t=e.data)||void 0===t?void 0:t.streamId))return;const a=null===(n=ot(["stream","get",e.data.streamId]))||void 0===n?void 0:n.data;return a?Vc(a):void 0},getPollInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("pollId"in e.data)||"poll"!==e.dataType)}(e)||!(null===(t=e.data)||void 0===t?void 0:t.pollId))return;const a=null===(n=ot(["poll","get",e.data.pollId]))||void 0===n?void 0:n.data;return a?hd(a):void 0},getClipInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"clip"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=ot(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getAudioInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"audio"!==e.dataType)}(e)&&(null===(t=e.data)||void 0===t?void 0:t.fileId))return null===(n=ot(["file","get",e.data.fileId]))||void 0===n?void 0:n.data},getRoomInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("roomId"in e.data)||"room"!==e.dataType)}(e)||!(null===(t=e.data)||void 0===t?void 0:t.roomId))return;const a=null===(n=ot(["room","get",e.data.roomId]))||void 0===n?void 0:n.data;return a?ud(a):void 0},getEventInfo(){var t,n;if(!function(e){return"event"===e.dataType||"event"===e.structureType}(e))return;const a=e=>{if(e&&"object"==typeof e&&"eventId"in e){const t=e.eventId;return"string"==typeof t?t:void 0}},s=a(e.data),o=null!=s?s:null===(t=e.children)||void 0===t?void 0:t.map((e=>{var t;return null===(t=ot(["post","get",e]))||void 0===t?void 0:t.data})).map((e=>a(null==e?void 0:e.data))).find(Boolean);if(!o)return;const i=null===(n=ot(["event","get",o]))||void 0===n?void 0:n.data;return i?Object.assign(Object.assign({},i),{get creator(){const e=ot(["user","get",i.userId]);if(null==e?void 0:e.data)return Lt(e.data)},get targetCommunity(){var e;if(!i.originId)return;const t=null===(e=ot(["community","get",i.originId]))||void 0===e?void 0:e.data;return t?Fc(t):void 0},get coverImage(){var e;if(i.coverImageFileId)return null===(e=ot(["file","get",i.coverImageFileId]))||void 0===e?void 0:e.data}}):void 0}}),Pd=(e,t)=>{"message"===e?Ft("local.message.updated",{messages:[t]}):"post"===e?Ft("post.updated",{posts:[t]}):"comment"===e?Ft("comment.updated",{comments:[t]}):"story"===e&&Ft("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},kd=async(e,t,n,a)=>{var s,o,i;const r=Xe();if(r.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new He("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:c}=await r.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:a});if(r.cache){const a=ot([e,"get",t]);if(!a||(null===(s=a.data.myReactions)||void 0===s?void 0:s.includes(n)))return!0;const d=Object.assign(Object.assign({},a.data),{reactionsCount:a.data.reactionsCount+1,myReactions:[...null!==(o=a.data.myReactions)&&void 0!==o?o:[],n],reactions:Object.assign(Object.assign({},a.data.reactions),{[n]:(null!==(i=a.data.reactions[n])&&void 0!==i?i:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return Ft("local.comment.addReaction",{comment:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("post"===e)return Ft("local.post.addReaction",{post:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("story"===e)return Ft("local.story.reactionAdded",{story:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("message"===e)return ct(["message","get",t],d),Ft("local.message.updated",{messages:[d]}),!0}return!0};kd.optimistically=(e,t,n)=>{var a,s,o,i,r;const c=Xe();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const d=ot([e,"get",t]);if(!(null==d?void 0:d.data)||(null===(a=d.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const l=Object.assign(Object.assign({},d.data),{reactionsCount:d.data.reactionsCount+1,myReactions:[...null!==(s=d.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},d.data.reactions),{[n]:(null!==(o=d.data.reactions[n])&&void 0!==o?o:0)+1})});return ct([e,"get",t],l,{cachedAt:Ie}),Pd(e,l),null!==(r=null===(i=null==l?void 0:l.myReactions)||void 0===i?void 0:i.includes(n))&&void 0!==r&&r};const Dd=(e,t)=>{var n;return null!==(n=null!=t?t:(e=>{var t,n;const a={creatorId:"creatorPrivateId"in e?e.creatorPrivateId:e.creatorId,feedId:null!==(t=e.messageFeedId)&&void 0!==t?t:e.subChannelId,contentId:e.messageId};return null===(n=ot(["messageMarker","get",tt("messageMarker")(a)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},Ud=(e,t)=>{const n=t.publicId!==t.messageId;return(async(e,t,n,a)=>{var s,o;const i=Xe();if(i.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new He("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:r}=await i.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:a}});if(i.cache){const a=ot([e,"get",t]);if(!a)return!0;const c=Object.assign(Object.assign({},a.data),{reactionsCount:Math.max(0,a.data.reactionsCount-1),myReactions:(null!==(s=a.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},a.data.reactions),{[n]:Math.max(0,(null!==(o=a.data.reactions[n])&&void 0!==o?o:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return Ft("local.comment.removeReaction",{comment:c,reactor:{reactionId:r.removedId,reactionName:n,userId:i.userId}}),!0;if("post"===e)return Ft("local.post.removeReaction",{post:c,reactor:{reactionId:r.removedId,reactionName:n,userId:i.userId}}),!0;if("story"===e)return Ft("local.story.reactionRemoved",{story:c,reactor:{userId:i.userId,reactionName:n,reactionId:r.removedId}}),!0;if("message"===e)return ct(["message","get",t],c),Ft("local.message.updated",{messages:[c]}),!0}return!0})("message",n?t.publicId:t.messageId,e,n?3:5)},jd=e=>Object.assign(Object.assign({},e),{users:e.users.map(Sa)}),Ed=e=>Object.assign(Object.assign({},e),{get status(){return e.status},get userId(){return e.userId},get eventId(){return e.eventId},get respondedAt(){return e.respondedAt},get event(){const t=ot(["event","get",e.eventId]);if(null==t?void 0:t.data)return t.data},get user(){const t=ot(["user","get",e.userId]);if(null==t?void 0:t.data)return Lt(t.data)}}),Md=e=>Object.assign(Object.assign({},e),{users:e.users.map(Sa)}),qd=(e,t)=>{const n=Xe();return Nt(n,e,e,(e=>{const a=Md(e);if(n.cache){Hn(a);const e=ot(["event","get",a.events[0].eventId]);t(e.data)}else t(a.events[0])}))},xd=(e,t)=>{const n=Xe();return Nt(n,e,e,(e=>{const a=jd(e);if(n.cache){Hn(a);const e=ot(["eventResponse","get",a.eventResponses[0].userId]);t(e.data)}else t(a.eventResponses[0])}))},Kd=async e=>{const t=Xe();t.log("event/getMyRSVP",e);const{data:n}=await t.http.get(`/api/v1/events/${e}/me/rsvp`),a=jd(n),s=t.cache&&Date.now();return t.cache&&Hn(a,{cachedAt:s}),{data:Ed(a.eventResponses[0]),cachedAt:s}};var Nd;Kd.locally=e=>{const t=Xe();if(t.log("event/getMyRSVP.locally",e),!t.cache)return;const n=ot(["event","getMyRSVP",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0},function(e){e.OnEventCreated="onEventCreated",e.OnEventUpdated="onEventUpdated",e.OnEventDeleted="onEventDeleted",e.OnRSVPCreated="onRSVPCreated",e.OnRSVPUpdated="onRSVPUpdated"}(Nd||(Nd={}));class Fd extends Hr{async getRequest(e,t){const{limit:n=pe,eventId:a}=e,s=zn(e,["limit","eventId"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get(`/api/v1/events/${a}/rsvp`,{params:Object.assign(Object.assign({},s),{options:o})});return i}}class _d extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.eventResponses.map(tt("eventResponse"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.eventResponses.map(tt("eventResponse"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Nd.OnRSVPCreated&&(a.data=[...new Set([t.userId,...a.data])]),e===Nd.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Bd=e=>qd("event.created",e),$d=e=>qd("event.updated",e),Ld=e=>qd("event.deleted",e),Qd=e=>qd("local.event.created",e),Vd=e=>qd("local.event.updated",e),Jd=e=>qd("local.event.deleted",e),Hd=e=>xd("event.rsvp.created",e),Wd=e=>xd("event.rsvp.updated",e),zd=e=>xd("local.rsvp.created",e),Gd=e=>xd("local.rsvp.updated",e);class Yd extends Zr{constructor(e,t){const n=P.default(e),a=["eventResponse","collection",n];super(new Fd(e),n,a,t),this.query=e,this.queryStreamController=new _d(this.query,this.cacheKey,this.notifyChange.bind(this),jd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Hd,action:Nd.OnRSVPCreated},{fn:Wd,action:Nd.OnRSVPUpdated},{fn:zd,action:Nd.OnRSVPCreated},{fn:Gd,action:Nd.OnRSVPUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=s.data.map((e=>ot(["eventResponse","get",e]))).filter(ec).map((({data:e})=>Ed(e)));(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}const Xd=(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getRSVPs: (tmpid: ${o}) > listen`);const i=new Yd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getRSVPs (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},Zd=e=>Object.assign(Object.assign({},e),{get creator(){const t=ot(["user","get",e.userId]);if(null==t?void 0:t.data)return Lt(t.data)},get targetCommunity(){if(!e.originId)return;const t=ot(["community","get",e.originId]);return(null==t?void 0:t.data)?Fc(t.data):void 0},get coverImage(){if(!e.coverImageFileId)return;const t=ot(["file","get",e.coverImageFileId]);return(null==t?void 0:t.data)?t.data:void 0},get post(){if(!e.postId)return;const t=ot(["post","get",e.postId]);return(null==t?void 0:t.data)?Rd(t.data):void 0},get room(){var t;if(!e.postId)return;const n=null===(t=st(["room","get"]))||void 0===t?void 0:t.filter((t=>t.data.referenceId===e.postId));return(null==n?void 0:n.length)&&n[0].data?ud(n[0].data):void 0},createRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Xe();n.log("event/createRSVP",e,t);const{data:a}=await n.http.post(`/api/v1/events/${e}/rsvp`,{status:t});Ft("local.rsvp.created",a);const s=jd(a),o=n.cache&&Date.now();return n.cache&&Hn(s,{cachedAt:o}),{data:Ed(s.eventResponses[0]),cachedAt:o}})(e.eventId,t);return n},updateRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Xe();n.log("event/updateRSVP",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}/rsvp`,{status:t});Ft("local.rsvp.updated",a);const s=jd(a),o=n.cache&&Date.now();return n.cache&&Hn(s,{cachedAt:o}),{data:Ed(s.eventResponses[0]),cachedAt:o}})(e.eventId,t);return n},getMyRSVP:async()=>{const{data:t}=await Kd(e.eventId);return t},getRSVPs:(t,n)=>Xd(Object.assign({eventId:e.eventId},t),n)}),el={file:gd,ad:e=>{const t=xo(),{image9_16:n,image1_1:a}=e,s=zn(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},s),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const a=null===(t=ot(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!a)return;const s=null===(n=ot(["file","get",a.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},a),{avatar:s})},get image1_1(){const e=ot(["file","get",a]);if(e)return e.data||void 0},get image9_16(){const e=ot(["file","get",n]);if(e)return e.data||void 0}})},comment:Gc,post:Rd,user:Lt,category:Nc,stream:Vc,story:e=>{const t=xo(),n=ot(["storyTarget","get",e.targetId]),a=ot(["community","get",e.targetId]);return Object.assign(Object.assign({},e),{analytics:{markAsSeen:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsViewed(e)},markLinkAsClicked:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsClicked(e)}},get videoData(){var t,n;const a=ot(["file","get",null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]);if(!a)return;const{data:s}=a;return s||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const a=ot(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!a)return;const{data:s}=a;return s?Object.assign(Object.assign({},s),{fileUrl:`${s.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&(null==a?void 0:a.data))return Fc(a.data)},get communityCategories(){if("community"!==e.targetType)return;if(!a)return;const{data:{categoryIds:t}}=a;return 0!==t.length?t.map((e=>{const t=ot(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=ot(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return Lt(t.data)},get storyTarget(){if(null==n?void 0:n.data)return Bc(n.data)},get isSeen(){const t=ot(["story-last-seen",e.targetId]);if(!(null==n?void 0:n.data))return!1;const a=(null==t?void 0:t.data)?new Date(t.data).getTime():0,s=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,o=new Date(e.expiresAt).getTime();return Math.max(a,s)>=o}})},storyTarget:Bc,message:e=>{const t=zn(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return Dd(e).readCount},get deliveredCount(){return Dd(e).deliveredCount},get creator(){var t;const n=null===(t=ot(["user","get",e.creatorId]))||void 0===t?void 0:t.data;return n?Lt(n):void 0},markRead:()=>Vi(e),addReaction:t=>((e,t)=>{const n=t.publicId!==t.messageId;return kd("message",n?t.publicId:t.messageId,e,n?3:5)})(t,e),removeReaction:t=>Ud(t,e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=ot(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return Lt(n)}}),channel:Hs,pinnedPost:e=>{var t;const n=ot(["post","get",e.referenceId]),a=null===(t=st(["user","get"]).find((t=>{var n;return(null===(n=t.data)||void 0===n?void 0:n.userInternalId)===e.pinnedBy})))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{pinnedBy:a,get post(){if(null==n?void 0:n.data)return Rd(n.data)},get target(){const e=ot(["pinTarget","get",null==n?void 0:n.data.targetId]);if(null==e?void 0:e.data)return null==e?void 0:e.data}})},notificationTray:e=>Object.assign(Object.assign({},e),{isSeen:e.lastSeenAt>e.lastOccurredAt,isRecent:new Date(e.lastOccurredAt).getTime()>=Date.now()-6048e5,users:e.actors.map((({publicId:e})=>ot(["user","get",e]))).filter(ec).map((({data:e})=>e)).map((e=>Lt(e))),get event(){const t=ot(["event","get",e.actionReferenceId]);if(null==t?void 0:t.data)return t.data}}),community:Fc,invitation:kc,joinRequest:vc,channelMember:za,room:ud,event:Zd,eventResponse:Ed,product:md,poll:hd,curatedContentTopic:e=>ia(e,{analytics:{markAsViewed:()=>{xo().markCuratedContentWidgetAsViewed(e.topicId)},markPostAsViewed:t=>{xo().markCuratedContentPostAsViewed(t,e.topicId)},markPostClick:t=>{xo().markCuratedContentPostAsClicked(t,e.topicId)}}})},tl=async e=>{const t=Xe();t.log("user/getUsers",e);const n=e.map((e=>encodeURIComponent(e))),{data:a}=await t.http.get("/api/v3/users/list",{params:{userIds:n}}),s=bo(a),o=t.cache&&Date.now();return t.cache&&Hn(s,{cachedAt:o}),Ft("user.fetched",a),{data:s.users.map((e=>el.user(e))),cachedAt:o}};tl.locally=e=>{var t;const n=Xe();if(n.log("user/getUsers.locally",e),!n.cache)return;const a=e.map((e=>ot(["user","get",e]))).filter(Boolean),s=a.map((({data:e})=>el.user(e))),o=null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==a?void 0:a.length)<e.length?void 0:{data:s,cachedAt:o.cachedAt}};const nl=async(e,t)=>{var n;const a=Xe();a.log("user/flagUser",{userId:e,options:t});const s=(e=>{if(!e)return;const t={};return void 0!==e.reportType&&(t.reportType=e.reportType),void 0!==e.reason&&(t.reason=e.reason),void 0!==e.comment&&(t.comment=e.comment),Object.keys(t).length>0?t:void 0})(t),{data:o}=await a.http.post(`/api/v4/me/flags/${encodeURIComponent(e)}`,s),i=bo(o);return a.cache&&Hn(i),Ft("user.flagged",o),null!==(n=i.users.find((t=>t.userId===e)))&&void 0!==n?n:i.users[0]},al=e=>Ro("user.updated",e),sl=e=>Ro("user.flagged",e),ol=e=>Ro("user.unflagged",e),il=e=>Ro("user.flagCleared",e),rl=e=>Ro("user.fetched",e),cl=async e=>{const t=Xe();t.log("user/getUser",e),ca("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),a=t.cache&&Date.now(),s=bo(n);return t.cache&&Hn(s,{cachedAt:a}),Ft("user.fetched",n),{data:s.users.find((t=>t.userId===e)),cachedAt:a}}catch(t){throw De(null==t?void 0:t.code)&&Wn("user",e),t}};cl.locally=e=>{const t=Xe();if(t.log("user/getUser.locally",e),!t.cache)return;const n=ot(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class dl extends Hr{async getRequest(e,t){const{limit:n=pe}=e,a=zn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return o}}class ll extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.users.map(tt("user"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(tt("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=ot(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],it(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var ul;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(ul||(ul={}));class hl extends Zr{constructor(e,t){const n=P.default(e),a=["user","collection",n];super(new dl(e),n,a,t),this.query=e,this.queryStreamController=new ll(this.query,this.cacheKey,this.notifyChange.bind(this),bo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Po,action:ul.OnUserDeleted},{fn:al,action:ul.OnUserUpdated},{fn:sl,action:ul.OnUserFlagged},{fn:ol,action:ul.OnUserUnflagged},{fn:il,action:ul.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["user","get",e]))).filter(ec).map((({data:e})=>e)).map(el.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;const n=(()=>"firstCreated"===this.query.sortBy?St:At)();return t=t.sort(n),"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class ml extends Hr{async getRequest(e,t){const{limit:n=pe}=e,a=zn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return o}}var gl;!function(e){e.OnBlocked="onBlocked",e.OnUnblocked="onUnblocked"}(gl||(gl={}));class pl extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.users.map(tt("user"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(tt("user"))])]}))}}reactor(e){return t=>{var n,a;const s=e===Gr.OnFollowed||e===gl.OnUnblocked,o=e===gl.OnBlocked;if(s||o){const e=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data,s=null!==(a=null==e?void 0:e.data)&&void 0!==a?a:[],i=o?[...new Set([...s,t.userId])]:s.filter((e=>e!==t.userId));it(this.cacheKey,Object.assign(Object.assign({},e),{data:i}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const yl=(e,t,n)=>a=>e((e=>{var s;if(!e)return e;const o=[n,"get",`${e[t]}`],i=null===(s=ot(o))||void 0===s?void 0:s.data;return i?a(i):void 0}));class vl extends Zr{constructor(e,t){const n=P.default(e),a=["blockedUsers","collection",n];super(new ml(e),n,a,t),this.query=e,this.queryStreamController=new pl(this.query,this.cacheKey,this.notifyChange.bind(this),ni),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Po,action:ul.OnUserDeleted},{fn:yl($r,"to","user"),action:Gr.OnFollowed},{fn:yl(Er,"to","user"),action:Gr.OnFollowed},{fn:e=>gi((t=>{var n;if(t.from!==Xe().userId)return;const a=null===(n=ot(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:gl.OnBlocked},{fn:e=>pi((t=>{var n;if(t.from!==Xe().userId)return;const a=null===(n=ot(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:gl.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["user","get",e]))).filter(ec).map((({data:e})=>e)).map(el.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class fl extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.users.map(tt("user"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(tt("user"))])]}))}}reactor(e){return t=>{var n,a;if(t&&(e===gl.OnBlocked||e===gl.OnUnblocked)){const s=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[],i=e===gl.OnBlocked?[...new Set([...o,t.userId])]:o.filter((e=>e!==t.userId));it(this.cacheKey,Object.assign(Object.assign({},s),{data:i}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class bl extends Hr{async getRequest(e,t){const{limit:n=ye}=e,a=zn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/blockers",{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return o}}class Il extends Zr{constructor(e){const t=`blocking-users-${Xe().userId}`,n={},a=["blockingUsers","collection",t];super(new bl(n),t,a,e),this.queryStreamController=new fl(n,this.cacheKey,this.notifyChange.bind(this),ii),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Po,action:ul.OnUserDeleted},{fn:e=>gi((t=>{var n;if(t.to!==Xe().userId)return;const a=null===(n=ot(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:gl.OnBlocked},{fn:e=>pi((t=>{var n;if(t.to!==Xe().userId)return;const a=null===(n=ot(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:gl.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["user","get",e]))).filter(ec).map((({data:e})=>e)).map(el.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Cl extends Hr{async getRequest(e,t){const{limit:n=pe,displayName:a}=e,s=zn(e,["limit","displayName"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},s),{keyword:a,options:o,isDeleted:!1})});return i}}class wl extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.users.map(tt("user"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(tt("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=ot(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],it(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Sl extends Zr{constructor(e,t){var n;const a=P.default(e),s=["user","collection",a];super(new Cl(e),a,s,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new wl(this.query,this.cacheKey,this.notifyChange.bind(this),bo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Po,action:ul.OnUserDeleted},{fn:al,action:ul.OnUserUpdated},{fn:sl,action:ul.OnUserFlagged},{fn:ol,action:ul.OnUserUnflagged},{fn:il,action:ul.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["user","get",e]))).filter(ec).map((({data:e})=>e)).map(el.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const Ol=async({viewId:e,viewedType:t,limit:n,token:a})=>{const s=Xe(),o={};a?o.token=a:o.limit=n;const i=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,r=await s.http.get(i,{params:o});return Hn(r.data),r.data};var Al;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(Al||(Al={}));var Tl=Object.freeze({__proto__:null,Relationship:cc,getUserByIds:tl,updateUser:async(e,t)=>{const n=Xe();n.log("user/updateUser",e,t);const{data:a}=await n.http.put("/api/v3/users/",Object.assign(Object.assign({userId:e},t),{createNewUserWhenNotFound:!1})),s=bo(a),o=n.cache&&Date.now();return n.cache&&Hn(s,{cachedAt:o}),Ft("user.updated",a),{data:s.users.find((t=>t.userId===e)),cachedAt:o}},flagUser:nl,unflagUser:async e=>{const t=Xe();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),a=bo(n);return t.cache&&Hn(a),Ft("user.unflagged",n),!!a},isUserFlaggedByMe:async e=>{const t=Xe();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},getAllBlockedUsers:async()=>{Xe().log("user/getAllBlockedUsers");const e=oi();return await e.ensureFetched(),e.getCachedUsers()},getAllBlockingUsers:async()=>{Xe().log("user/getAllBlockingUsers");const e=di();return await e.ensureFetched(),e.getCachedUsers()},onUserUpdated:al,onUserDeleted:Po,onUserFlagged:sl,onUserUnflagged:ol,onUserFlagCleared:il,getUser:(e,t)=>rc(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?el.user(e.data):e.data}))),"userId",cl,[rl,al,Po,sl,ol,il]),getUsers:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`liveUsers(tmpid: ${o}) > listen`);const i=new hl(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`liveUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getBlockedUsers(tmpid: ${o}) > listen`);const i=new vl(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getBlockedUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e())),dt(c)}},getBlockingUsers:e=>{const{log:t,cache:n}=Xe();n||console.log(fe);const a=Date.now();t(`getBlockingUsers(tmpid: ${a}) > listen`);const s=new Il(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>dt(i))),()=>{t(`getBlockingUsers(tmpid: ${a}) > dispose`),o.forEach((e=>e())),dt(i)}},searchUsers:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`liveSearchUsers(tmpid: ${o}) > listen`);const i=new Sl(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`liveSearchUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchUserByDisplayName:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`liveSearchUsers(tmpid: ${o}) > listen`);const i=new Sl(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`liveSearchUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:a,cache:s}=Xe(),o=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(fe);const i=Date.now();a(`getReachUsers(tmpid: ${i}) > listen`);const{limit:r,viewId:c,viewedType:d}=e;return n=(e=!1)=>{var a,s,i;const l=null===(a=ot(o))||void 0===a?void 0:a.data,u=null!==(s=null==l?void 0:l.data)&&void 0!==s?s:[];if(!e&&u.length>0&&!(null==l?void 0:l.params.page))return;const h=$e(Ol,{viewId:c,viewedType:d,limit:r||10,token:e||null===(i=null==l?void 0:l.params.page)||void 0===i?void 0:i.next});Qe(h,(e=>{var a,s,i,r,c;let d=null!==(i=null===(s=null===(a=ot(o))||void 0===a?void 0:a.data)||void 0===s?void 0:s.data)&&void 0!==i?i:[];(null===(r=e.data)||void 0===r?void 0:r.users)&&(d=[...new Set([...d,...e.data.users.map((({userId:e})=>e))])]);const l={loading:e.loading,params:{page:null===(c=e.data)||void 0===c?void 0:c.paging},data:d||[]};it(o,l),(e=>{var a,s;let o=[];(null==e?void 0:e.data)&&(o=e.data.map((e=>ot(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:o,hasNextPage:!!(null===(s=null===(a=e.params)||void 0===a?void 0:a.page)||void 0===s?void 0:s.next),loading:e.loading||!1})})(l)}),Le(ve,2e3))},n(!0),()=>{a(`getReachUsers(tmpid: ${i}) > dispose`),dt(o)}},get AmityUserSearchMatchType(){return Al}});const Rl=async e=>{const t=Xe();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),a=t.cache&&Date.now();return t.cache&&Hn({files:[n]},{cachedAt:a}),{data:gd(n),cachedAt:a}};Rl.locally=e=>{const t=Xe();if(t.log("file/getFile.locally",e),!t.cache)return;const n=ot(["file","get",e]);return n?{data:gd(n.data),cachedAt:n.cachedAt}:void 0};const Pl=async(e,t,n)=>{const a=Xe();a.log("file/uploadVideo",e);const s=e.getAll("files");if(!s.length)throw new Error("The formData object must have a `files` key.");const o=ur().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",s[0].name),t&&e.append("feedType",t);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:r}=await a.upload.post("/api/v4/videos",e,{headers:i,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=a.cache&&Date.now();return a.cache&&Hn({files:r},{cachedAt:c}),{data:r.map((e=>gd(e))),cachedAt:c}},kl=async(e,t,n)=>{const a=Xe();a.log("file/uploadImage",e);const s=e.getAll("files");if(null==s?void 0:s.length)console.warn("Deprecation Warning: `files` is deprecated, please use `file` instead."),e.append("preferredFilename",s[0].name);else{const t=e.get("file");if(!t)throw new Error("The formData object must have a `file` or `files` key");e.append("preferredFilename",t.name),n&&e.append("altText",n)}const o=ur().getFileAccessType();e.append("accessType",o);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:r}=await a.upload.post("/api/v4/images",e,{headers:i,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),c=a.cache&&Date.now();return a.cache&&Hn({files:r},{cachedAt:c}),{data:r.map((e=>gd(e))),cachedAt:c}};var Dl=Object.freeze({__proto__:null,getFile:Rl,uploadFile:async(e,t)=>{const n=Xe();n.log("file/uploadFile",e);const a=e.getAll("files");if(!a.length)throw new Error("The formData object must have a `files` key.");const s=ur().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",a[0].name);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await n.upload.post("/api/v4/files",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),r=n.cache&&Date.now();return n.cache&&Hn({files:i},{cachedAt:r}),{data:i,cachedAt:r}},deleteFile:async e=>{const t=Xe();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),dt(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:Pl,uploadImage:kl,updateAltText:async(e,t)=>{const n=Xe();n.log("file/updateAltText",t);const{data:a}=await n.http.put(`/api/v3/files/${e}`,{altText:t}),s=n.cache&&Date.now();return n.cache&&Hn({files:[a]},{cachedAt:s}),!0},uploadClip:async(e,t,n)=>{const a=Xe();a.log("file/uploadClip",e);const s=e.get("files");if(!s)throw new Error("The formData object must have a `files` key.");const o=ur().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",s.name),t&&e.append("feedType",t);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:r}=await a.upload.post("/api/v4/clips",e,{headers:i,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=a.cache&&Date.now();return a.cache&&Hn({files:r},{cachedAt:c}),{data:r,cachedAt:c}},uploadAudio:async(e,t)=>{const n=Xe();n.log("file/uploadAudio",e);const a=e.getAll("file");if(0===a.length)throw new Error("The formData object must have a `file` key with audio file.");const s=a[0],o=ur().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",s.name);const{data:i}=await n.upload.post("/api/v4/audios",e,{headers:{"content-type":"multipart/form-data"},onUploadProgress({loaded:e,total:n=100}){null==t||t(Math.round(100*e/n))}}),r=n.cache&&Date.now();return n.cache&&Hn({files:i},{cachedAt:r}),{data:i,cachedAt:r}}});const Ul=async e=>{const t=Xe();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:a=10,queryToken:s,displayName:o,sortBy:i}=n,r=zn(n,["limit","queryToken","displayName","sortBy"]),c=s?{token:s}:a?{limit:a}:void 0,{data:d}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},r),{keyword:o,sortBy:i,options:c})}),{paging:l}=d,u=zn(d,["paging"]),{roles:h}=u,m=t.cache&&Date.now();t.cache&&Hn(u,{cachedAt:m});const g=xe(l.next);return{data:h,cachedAt:m,prevPage:xe(l.previous),nextPage:g,paging:l}};Ul.locally=e=>{Xe().log("role/queryRoles.locally",e)};const jl=async e=>{const t=Xe();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),a=t.cache&&Date.now();return t.cache&&Hn({roles:n},{cachedAt:a}),{data:n.find((t=>t.roleId===e)),cachedAt:a}};jl.locally=e=>{const t=Xe();if(t.log("role/getRole.locally",e),!t.cache)return;const n=ot(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const El=async(e,t=!1)=>{const n=Xe();let a;n.log("message/getMessage",e),ca("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);a=await Ia(t)}catch(t){throw De(null==t?void 0:t.code)&&Wn("message",e),t}const s=n.cache&&Date.now();n.cache&&Hn(a,{cachedAt:s});const{messages:o}=a;return Ft("local.message.fetched",{messages:o}),{data:o.find((t=>t.messageId===e)),cachedAt:s}};El.locally=e=>{const t=Xe();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=ot(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ml=e=>{const{posts:t,postChildren:n,videoStreamings:a}=e,s=zn(e,["posts","postChildren","videoStreamings"]),o=uc({communities:s.communities}),i=s.communityUsers.map((e=>{const t=s.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),r=dc(o,i);let c=[];const d=t.map((t=>{var n,o,i;const r=null===(n=s.feeds.find((e=>e.feedId===t.feedId)))||void 0===n?void 0:n.feedType,d=e.postChildren.filter((e=>e.parentPostId===t.postId));var l,u,h;d.length>0&&Xc(d[0])&&(l=a,u=null===(o=d[0].data)||void 0===o?void 0:o.streamId,h=t.postId,c=u?l.map((e=>e.streamId===u?Object.assign(Object.assign({},e),{referenceType:"post",referenceId:h,postId:h}):e)):l);const m=(e.comments||[]).filter((e=>"post"===e.referenceType&&e.referenceId===t.postId)),g=0===m.length?(new Date).toISOString():m.map((e=>e.createdAt)).sort().at(-1);return Oi().queueCommentChangeTask(new vi(t.postId,g,null!==(i=t.commentsCount)&&void 0!==i?i:0)),Object.assign(Object.assign({},t),{childPosts:d,feedType:r,localCommentCount:Oi().getLocalCommentCount(t.postId,!0),pinnedProductId:null==t?void 0:t.pinnedProductId})}));return Object.assign(Object.assign({},s),{postChildren:n,videoStreamings:c,posts:d,communities:r,communityUsers:i})},ql=e=>{var{searchResult:t,polls:n}=e,a=zn(e,["searchResult","polls"]);const s=Ml(a);return Object.assign(Object.assign({},s),{polls:n})},xl=async e=>{const t=Xe();let n;t.log("post/getPost",e),ca("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw De(null==t?void 0:t.code)&&Wn("post",e),t}const a=Ml(n),s=t.cache&&Date.now();t.cache&&Hn(a,{cachedAt:s});const{posts:o}=a;return{data:o.find((t=>t.postId===e)),cachedAt:s}};xl.locally=e=>{const t=Xe();if(t.log("post/getPost.locally",e),!t.cache)return;const n=ot(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Kl=async e=>{const t=Xe();let n;t.log("comment/getComment",e),ca("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw De(null==t?void 0:t.code)&&Wn("comment",e),t}const a=t.cache&&Date.now();t.cache&&Hn(n,{cachedAt:a});const{comments:s}=n;return{data:el.comment(s.find((t=>t.commentId===e))),cachedAt:a}};Kl.locally=e=>{const t=Xe();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=ot(["comment","get",e]);return n?{data:el.comment(n.data),cachedAt:n.cachedAt}:void 0};const Nl=(e,t)=>{var n,a;let s,o;if("post"===t)o="post",s=e.posts[0].postId;else if("comment"===t)o="comment",s=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");o="story",s=e.stories[0].referenceId}return(null===(a=null===(n=ot([o,"get",s]))||void 0===n?void 0:n.data)||void 0===a?void 0:a.myReactions)||[]},Fl=(e,t,n)=>{const[a]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},a),{myReactions:n})]})},_l=(e,t,n,a=[])=>{const s=e.split(".")[1];let o=a;if(Xe().userId===t)if(["addReaction","reactionAdded"].includes(s))o.includes(n)||o.push(n);else{if(!["removeReaction","reactionRemoved"].includes(s))throw new Error(`Unknown event type: ${s}`);o=o.filter((e=>e!==n))}return o},Bl=(e,t)=>{const n=e.split(".")[0],a=Nl(t,n),s=_l(e,t.reactor.userId,t.reactor.reactionName,a);return Fl(t,`${n}s`,s)},$l=(e,t)=>{var n,a;const s=e.split(".")[0];let o=Nl(t,s);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(o=_l(e,null===(n=t.reactions[0])||void 0===n?void 0:n.userId,null===(a=t.reactions[0])||void 0===a?void 0:a.reactionName,o));const i=Fl(t,"stories",o);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return i;const r=dc(t.communities,t.communityUsers);return Object.assign(Object.assign({},i),{communities:r})},Ll=async(e,t,n)=>{var a,s,o;const i=Xe();if(i.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new He("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:r}=await i.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0});if(i.cache){const c=ot([e,"get",t]);if(!c||(null===(a=c.data.myReactions)||void 0===a?void 0:a.includes(n)))return!0;const d=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(s=c.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(o=c.data.reactions[n])&&void 0!==o?o:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return Ft("local.comment.addReaction",{comment:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0;if("post"===e)return Ft("local.post.addReaction",{post:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0;if("story"===e)return Ft("local.story.reactionAdded",{story:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0}return!0};Ll.optimistically=(e,t,n)=>{var a,s,o,i,r;const c=Xe();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const d=ot([e,"get",t]);if(!(null==d?void 0:d.data)||(null===(a=d.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const l=Object.assign(Object.assign({},d.data),{reactionsCount:d.data.reactionsCount+1,myReactions:[...null!==(s=d.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},d.data.reactions),{[n]:(null!==(o=d.data.reactions[n])&&void 0!==o?o:0)+1})});return ct([e,"get",t],l,{cachedAt:Ie}),Pd(e,l),null!==(r=null===(i=null==l?void 0:l.myReactions)||void 0===i?void 0:i.includes(n))&&void 0!==r&&r};const Ql=async(e,t,n)=>{var a,s;const o=Xe();if(o.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new He("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await o.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}});if(o.cache){const r=ot([e,"get",t]);if(!r)return!0;const c=Object.assign(Object.assign({},r.data),{reactionsCount:Math.max(0,r.data.reactionsCount-1),myReactions:(null!==(a=r.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:Math.max(0,(null!==(s=r.data.reactions[n])&&void 0!==s?s:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return Ft("local.comment.removeReaction",{comment:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("post"===e)return Ft("local.post.removeReaction",{post:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("story"===e)return Ft("local.story.reactionRemoved",{story:c,reactor:{userId:o.userId,reactionName:n,reactionId:i.removedId}}),!0}return!0};Ql.optimistically=(e,t,n)=>{var a,s,o,i;const r=Xe();if(r.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!r.cache)return;const c=ot([e,"get",t]);if(!(null==c?void 0:c.data)||!(null===(a=c.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const d=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(s=c.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:Math.max(0,(null!==(o=c.data.reactions[n])&&void 0!==o?o:0)-1)})});return ct([e,"get",t],d,{cachedAt:Ie}),Pd(e,d),!(null===(i=null==d?void 0:d.myReactions)||void 0===i?void 0:i.includes(n))};const Vl=e=>{var t;const n=e.posts[0];if(n.parentId){const e=null===(t=ot(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;if(!e)return;it(["post","get",e.postId],Object.assign(Object.assign({},e),{children:e.children.filter((e=>e!==n.postId))}))}else n.children.forEach((e=>rt(["post","get",e],{isDeleted:!0})))},Jl=(e,t)=>{const n=Xe();return Nt(n,e,e,(a=>{var s;if(n.cache){const o=Ml(a),{communities:i}=o;if(Hn(o,void 0,!1),(null==i?void 0:i[0])&&!["post.updated"].includes(e)&&Ft("community.updated",{communities:i,categories:[],communityUsers:o.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=a.posts[0];Vl(a);try{ca("post",e)}catch(e){return}return s!==n.userId&&dt(["post","get",e]),t(a.posts[0])}const r=ot(["post","get",a.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=st(["post","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===r.data.targetId}));"post.declined"===e&&(t=null==t?void 0:t.filter((({key:e})=>{var t;return"reviewing"===(null===(t=e[2])||void 0===t?void 0:t.feedType)}))),null==t||t.map((({key:e,data:t})=>ct(e,t,{cachedAt:-1})))}"post.created"===e&&(e=>{var t;const n=e.posts[0];if(!n.parentId)return;const a=null===(t=ot(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;a&&it(["post","get",a.postId],Object.assign(Object.assign({},a),{children:[...new Set([n.postId,...a.children])]}))})(a),t(r.data)}else t(a.posts[0])}))},Hl=(e,t)=>{const n=Xe();return Nt(n,e,e,(a=>{if(n.cache){const{communities:n}=a;(null==n?void 0:n[0])&&!["local.post.updated"].includes(e)&&Ft("community.updated",{communities:n,categories:[],communityUsers:a.communityUsers,feeds:[],files:[],users:[]});const s=ot(["post","get",a.posts[0].postId]);"local.post.deleted"===e&&Vl(a),t(s.data)}else t(a.posts[0])}))},Wl=e=>Jl("post.created",e),zl=e=>Jl("post.updated",e),Gl=e=>Jl("post.deleted",e),Yl=e=>Jl("post.approved",e),Xl=e=>Jl("post.declined",e),Zl=e=>Jl("post.flagged",e),eu=e=>Jl("post.unflagged",e),tu=e=>{const t=Xe();return Nt(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=zn(Bl("post.addReaction",n),["reactor"]);Hn(t);const a=ot(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},nu=e=>{const t=Xe();return Nt(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=zn(Bl("post.removeReaction",n),["reactor"]);Hn(t);const a=ot(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},au=(e,t,n)=>{switch(e){case"comment.created":pd(t)?bd(t):(Sd(t),(e=>{vd(e)&&Oi().queueCommentChangeTask(new fi(e.referenceId,e.commentId,e.createdAt))})(t));break;case"comment.approved":Sd(t),Cd(t);break;case"comment.updated":pd(t)&&n&&yd(n)&&(Od(t),wd(t));break;case"comment.deleted":Od(t),n&&pd(n)&&Id(t)}},su=(e,t)=>{const n=Xe();return Nt(n,e,e,(a=>{var s,o;if(n.cache){const n=zc(["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=Nl(e,"comment");return Fl(e,"comments",t)})(a):a),{comments:i}=n;if(i.length>0){const a=["comment","get",i[0].commentId],r=null===(s=ot(a))||void 0===s?void 0:s.data;Hn(n,void 0,!1);const c=ot(a);if(au(e,c.data,r),["comment.deleted"].includes(e)){const e=null===(o=st(["comment","query"]))||void 0===o?void 0:o.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===c.data.referenceId}));null==e||e.map((({key:e,data:t})=>ct(e,t,{cachedAt:-1})))}t(el.comment(c.data))}}else t(el.comment(a.comments[0]))}))},ou=(e,t)=>{const n=Xe();return Nt(n,e,e,(a=>{var s,o,i,r;if(n.cache){const n=zc(a);Hn(n);const{comments:c}=n;if(c.length>0){const n=ot(["comment","get",c[0].commentId]);if(["local.comment.created"].includes(e)&&yd(c[0])){if(c[0].parentId){const e=ot(["comment","get",c[0].parentId]);if((null==e?void 0:e.data)&&!e.data.children.includes(c[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,c[0].commentId])]});it(["comment","get",c[0].parentId],t),setTimeout((()=>{Ft("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",c[0].referenceId],t=null===(s=ot(e))||void 0===s?void 0:s.data;if(t){const n=Object.assign(Object.assign({},t),{comments:Td(t,c[0].commentId)});it(e,n)}}const e=null===(o=st(["comment","query"]))||void 0===o?void 0:o.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>ct(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(c[0].parentId){const e=ot(["comment","get",c[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(c[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==c[0].commentId))])]});it(["comment","get",c[0].parentId],t),setTimeout((()=>{Ft("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",c[0].referenceId],t=null===(i=ot(e))||void 0===i?void 0:i.data;if(t){const n=Object.assign(Object.assign({},t),{comments:null==t?void 0:t.comments.filter((e=>{var t;return e!==(null===(t=c[0])||void 0===t?void 0:t.commentId)}))});it(e,n)}}const e=null===(r=st(["comment","query"]))||void 0===r?void 0:r.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>ct(e,t,{cachedAt:-1})))}t(el.comment(n.data))}}else t(el.comment(a.comments[0]))}))},iu=e=>su("comment.created",e),ru=e=>su("comment.updated",e),cu=e=>su("comment.deleted",e),du=e=>su("comment.approved",e),lu=e=>su("comment.flagged",e),uu=e=>su("comment.unflagged",e),hu=e=>{const t=Xe();return Nt(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=zn(Bl("comment.addReaction",n),["reactor"]);Hn(t);const a=ot(["comment","get",n.comments[0].commentId]);e(el.comment(a.data))}else e(el.comment(n.comments[0]))}))},mu=e=>{const t=Xe();return Nt(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=zn(Bl("comment.removeReaction",n),["reactor"]);Hn(t);const a=ot(["comment","get",n.comments[0].commentId]);e(el.comment(a.data))}else e(el.comment(n.comments[0]))}))},gu=(e,t,n)=>{const a=Xe(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e){return Nt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await Ia(e);t.reactions[0]&&(Hn(t),Hn({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Nt(a,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=zn(e,["reactor"]);Hn(n),Hn({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Nt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=zn(e,["reactions"]);Hn(n),Hn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Nt(a,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=zn(e,["reactor"]);Hn(n),Hn({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},pu=(e,t,n)=>{const a=Xe(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e){return Nt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await Ia(e);t.reactions[0]&&(Hn(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Nt(a,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=zn(e,["reactor"]);Hn(n),Hn({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Nt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=zn(e,["reactions"]);Hn(n),Hn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Nt(a,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=zn(e,["reactor"]);Hn(n),Hn({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))};class yu extends Hr{async getRequest(e,t){const{limit:n=pe,referenceType:a}=e,s=zn(e,["limit","referenceType"]),o=t?{token:t}:{limit:n};Xe().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(a))throw new He("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await this.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},s),{referenceType:a,referenceVersion:"message"===a?5:void 0,options:o})});return i}}class vu extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){var t;const n=await this.preparePayload(e),a=Xe(),s=a.cache&&Date.now();if(a.cache){const{reactions:e}=n,a=zn(n,["reactions"]);Hn(Object.assign(Object.assign({},a),{reactions:e,reactors:null===(t=e[0])||void 0===t?void 0:t.reactors}),{cachedAt:s})}}appendToQueryStream(e,t,n=!1){var a,s,o,i;const r=null!==(s=null===(a=e.reactions[0])||void 0===a?void 0:a.reactors)&&void 0!==s?s:[];if(n)it(this.cacheKey,{data:r.map(tt("reactor"))});else{const e=null===(o=ot(this.cacheKey))||void 0===o?void 0:o.data,t=null!==(i=null==e?void 0:e.data)&&void 0!==i?i:[];it(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...r.map(tt("reactor"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;a&&("onAdded"===e?a.data=[...new Set([t.reactionId,...a.data])]:"onRemoved"===e&&(a.data=a.data.filter((e=>e!==t.reactionId))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class fu extends Zr{constructor(e,t){const n=P.default(e),a=["reaction","collection",n];super(new yu(e),n,a,t),this.query=e,this.queryStreamController=new vu(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:e=>gu(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>pu(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const a=Xe(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e)return Nt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await Ia(e);t.reactions[0]&&(Hn(t),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return Nt(a,"local.post.removeReaction","local.post.removeReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return Nt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=zn(e,["reactions"]);Hn(n),Hn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return Nt(a,"local.comment.removeReaction","local.comment.removeReaction",(e=>{s("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const a=Xe(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e)return Nt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await Ia(e);t.reactions[0]&&(Hn(t),Hn({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return Nt(a,"local.post.addReaction","local.post.addReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return Nt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=zn(e,["reactions"]);Hn(n),Hn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return Nt(a,"local.comment.addReaction","local.comment.addReaction",(e=>{s("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>ot(["reactor","get",e]))).filter(Boolean).map((({data:e})=>el.reactor(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var bu=Object.freeze({__proto__:null,addReaction:Ll,removeReaction:Ql,onReactionAdded:(e,t,n)=>{const a=a=>{tt(e)(a)===t&&n(a)};if("message"===e){const e=Xe(),t=async e=>{var t;const n=await Ia(e),s=ot(["message","get",n.messages[0].messageId]),o=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Hn(n),o&&a(n.messages[0])};return Nt(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?tu(a):hu(a)},onReactionRemoved:(e,t,n)=>{const a=a=>{tt(e)(a)===t&&n(a)};if("message"===e){const e=Xe(),t=async e=>{var t;const n=await Ia(e),s=ot(["message","get",n.messages[0].messageId]),o=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Hn(n),o&&a(n.messages[0])};return Nt(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?nu(a):mu(a)},onReactorAdded:gu,onReactorRemoved:pu,getReactions:(e,t,n)=>{const{log:a,cache:s}=Xe(),o=Date.now();a(`getReactions(tmpid: ${o}) > listen`);const i=new fu(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{dt(c)})),()=>{a(`getReactions(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});const Iu=async()=>{var e;const t=Xe();t.log("channel/getArchivedChannelIds");const{data:n}=await t.http.get("/api/v1/archives/channels"),a=null!==(e=n.archives)&&void 0!==e?e:[];return t.cache&&(dt(["archivedChannel","get"]),a.forEach((e=>{e.channelId&&it(["archivedChannel","get",e.channelId],e)}))),a.map((e=>e.channelId)).filter((e=>!!e))},Cu=e=>{const t=Xe(),n=[Nt(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await Ia(t);Hn(n),e(n.messages[0])})),Nt(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},wu=e=>Cu((t=>{var n;const a=Fa(t.channelId);a&&(null===(n=a.pinnedMessage)||void 0===n?void 0:n.messageId)===t.messageId&&e(Ba(a,null))})),Su=e=>{const t=Xe(),n=[Nt(t,"onMessageUpdated","message.updated",(async t=>{const n=await Ia(t);Hn(n),e(n.messages[0])})),Nt(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},Ou=e=>{const t=Xe(),n=[Nt(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await Ta(t);Hn(n),e(n.messageFeeds[0])})),Nt(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function Au(e,t){it(["channel","get",e.channelId],ia(e,t))}const Tu=e=>{const t=Xe();return Nt(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},Ru=async(e,t=!1)=>{const n=Xe(),a=await Ra(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const s=Object.assign(Object.assign({},a.data),{isDeleted:!0,updatedAt:at(a.data.updatedAt)});return t?setTimeout((()=>{Wn("subChannel",e)}),0):ct(["subChannel","get",e],s),Ft("local.message-feed.deleted",{messageFeeds:[s]}),s},Pu=e=>Nt(Xe(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),ku=()=>`LOCAL_${un()}`;let Du;const Uu=async(e,t)=>{const n=Xe();n.log("message/updateMessage",t),console.warn("MessageRepository.updateMessage will be replaced with MessageRepository.editMessage");const{data:a}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,Ca(t)),s=await Ia(a),o=n.cache&&Date.now();n.cache&&Hn(s,{cachedAt:o});const{messages:i}=s;return Ft("local.message.updated",{messages:i}),{data:el.message(i.find((t=>t.messageId===e))),cachedAt:o}};Uu.optimistically=(e,t)=>{const n=Xe();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const a=ot(["message","get",e]);if(!a)return;const s=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return ct(["message","get",e],s,{cachedAt:-1}),Ft("local.message.updated",{messages:[s]}),{data:el.message(s),cachedAt:-1}};const ju=async(e,t)=>{const n=Xe();n.log("message/editMessage",t);const{data:a}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,Ca(t)),s=await Ia(a),o=n.cache&&Date.now();n.cache&&Hn(s,{cachedAt:o});const{messages:i}=s;return Ft("local.message.updated",{messages:i}),{data:el.message(i.find((t=>t.messageId===e))),cachedAt:o}};ju.optimistically=(e,t)=>{const n=Xe();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const a=ot(["message","get",e]);if(!a)return;const s=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return ct(["message","get",e],s,{cachedAt:-1}),Ft("local.message.updated",{messages:[s]}),{data:el.message(s),cachedAt:-1}};const Eu=async e=>{var t;const n=Xe();if(n.log("message/deleteMessage",e),e.includes("LOCAL_")){const n=null===(t=ot(["message","get",e]))||void 0===t?void 0:t.data;if(!n)throw Error("messageId not found");const a=Object.assign(Object.assign({},n),{isDeleted:!0});return Ft("local.message.deleted",{messages:[a]}),el.message(a)}const{data:a}=await n.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),s=await Ia(a);return Ft("local.message.deleted",{messages:[s.messages[0]]}),el.message(s.messages[0])};Eu.optimistically=e=>{Xe().log("message/deleteMessage.optimistically",e);const t=ot(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return ct(["message","get",e],n,{cachedAt:-1}),Ft("local.message.deleted",{messages:[n]}),{data:el.message(n),cachedAt:-1}};const Mu=async e=>{const t=Xe();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await El(e);return Ft("local.message.deleted",{messages:[n.data]}),el.message(n.data)};Mu.optimistically=e=>{Xe().log("message/softDeleteMessage.optimistically",e);const t=ot(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return ct(["message","get",e],n,{cachedAt:-1}),Ft("local.message.deleted",{messages:[n]}),{data:el.message(n),cachedAt:-1}};const qu=e=>{var t,n,a;const s=null===(t=El.locally(e))||void 0===t?void 0:t.data;let o=null==s?void 0:s.channelId;o||(o=null===(a=null===(n=st(["channel","get"]))||void 0===n?void 0:n.find((({data:t})=>{var n;return(null===(n=t.pinnedMessage)||void 0===n?void 0:n.messageId)===e})))||void 0===a?void 0:a.data.channelId),o&&Lc(o).catch((()=>{}))},xu=async e=>{const t=Xe();t.log("user/getReadUsers",e);const{page:n,messageId:a}=e,s=zn(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${a}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:qe(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:r,userFeedMarkers:c}=o,d=zn(o,["paging","publicUserIds","userFeedMarkers"]),l=t.cache&&Date.now();if(t.cache){Hn(Object.assign(Object.assign({},d),{userFeedMarkers:ea(c)}),{cachedAt:l});const e=["read-user","query",Object.assign(Object.assign({messageId:a},s),{options:Object.assign({},n)})];it(e,{users:r,paging:i})}let u=[];r.length>0&&({data:u}=await tl(r));return{data:u,cachedAt:l,prevPage:xe(i.previous),nextPage:xe(i.next)}};xu.locally=e=>{var t;const n=Xe();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:a}=e,s=zn(e,["page"]),o=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},a)})],{data:i,cachedAt:r}=null!==(t=ot(o))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=ot(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:r,prevPage:xe(null==i?void 0:i.paging.previous),nextPage:xe(null==i?void 0:i.paging.next)}};const Ku=async e=>{const t=Xe();t.log("user/getDeliveredUsers",e);const{page:n,messageId:a}=e,s=zn(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${a}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:qe(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:r,userFeedMarkers:c}=o,d=zn(o,["paging","publicUserIds","userFeedMarkers"]),l=t.cache&&Date.now();if(t.cache){Hn(Object.assign(Object.assign({},d),{userFeedMarkers:ea(c)}),{cachedAt:l});const e=["delivered-user","query",Object.assign(Object.assign({messageId:a},s),{options:Object.assign({},n)})];it(e,{users:r,paging:i})}let u=[];r.length>0&&({data:u}=await tl(r));return{data:u,cachedAt:l,prevPage:xe(i.previous),nextPage:xe(i.next)}};Ku.locally=e=>{var t;const n=Xe();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:a}=e,s=zn(e,["page"]),o=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},a)})],{data:i,cachedAt:r}=null!==(t=ot(o))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=ot(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:r,prevPage:xe(null==i?void 0:i.paging.previous),nextPage:xe(null==i?void 0:i.paging.next)}};const Nu=e=>{const t=Xe();return Nt(t,"onMessageFlagged","message.flagged",(async t=>{const n=await Ia(t);Hn(n),e(n.messages[0])}))},Fu=e=>{const t=Xe();return Nt(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await Ia(t);Hn(n),e(n.messages[0])}))},_u=e=>{const t=Xe();return Nt(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await Ia(t);Hn(n),e(n.messages[0])}))},Bu=e=>{const t=Xe();return Nt(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await Ia(t,"message.reactionAdded");Hn(n),e(n.messages[0])}))},$u=e=>{const t=Xe();return Nt(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await Ia(t,"message.reactionRemoved");Hn(n),e(n.messages[0])}))},Lu=e=>{const t=Xe();return Nt(t,"message/onMessageFetched","local.message.fetched",(t=>{Hn(t),e(t.messages[0])}))},Qu=e=>{const t=Xe();return Nt(t,"stream/onStreamViewerDidBan","video-streaming.viewerDidBan",(t=>{var n;const{list:a}=t;a.forEach((e=>{var t;rt(["stream","get",e.streamId],{watcherUrl:null});const n=null===(t=st(["message","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.creatorId===e.userId));null==n||n.forEach((e=>{rt(e.key,{isDeleted:!0})}))}));const s=null===(n=ot(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))};class Vu extends zr{constructor(e,t,n,a,s){super(e,t),this.notifyChange=n,this.preparePayload=a,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.messages.map(tt("message")),query:this.query});else{const n=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,o=null!==(s=null==n?void 0:n.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...o,...e.messages.map(tt("message"))])]:[...new Set([...e.messages.map(tt("message")),...o])]}))}}reactor(e){return t=>{var n,a,s,o;if("onCreate"===e){const e=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:o}=t;if(!e)return;if(this.query.subChannelId!==(null==t?void 0:t.subChannelId)||!e)return;if(this.query.type&&this.query.type!==t.dataType)return;if(this.query.excludingTags&&(null===(a=this.query.excludingTags)||void 0===a?void 0:a.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;if(!!this.query.hasFlags!=!!t.flagCount)return;if(this.query.parentId&&this.query.parentId!==t.parentId)return;if(this.query.hasOwnProperty("includeDeleted")&&!this.query.includeDeleted&&t.isDeleted)return;if(this.query.includingTags&&!(null===(s=this.query.includingTags)||void 0===s?void 0:s.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;this.query.sortBy&&"segmentDesc"!==this.query.sortBy||this.paginationController.getPrevToken()||(e.data=[...new Set([null!=o?o:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=o?o:t.messageId])]),it(this.cacheKey,e)}if("onDelete"===e&&"error"===t.syncState){const e=null===(o=ot(this.cacheKey))||void 0===o?void 0:o.data;if(!e)return;if(e.data.includes(t.messageId)){const n=e.data.filter((e=>e!==t.messageId));it(this.cacheKey,Object.assign(Object.assign({},e),{data:n}))}}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ju extends Hr{async getRequest(e,t){const n=wa(e),{data:a}=await this.http.get("/api/v5/messages",{params:Object.assign(Object.assign({},n),{options:t?{token:t}:Object.assign({},n.options)})});return a}}class Hu extends Zr{constructor(e,t){const n=P.default(e),a=["message","collection",n];super(new Ju(e),n,a,t),this.query=e,this.queryStreamController=new Vu(this.query,this.cacheKey,this.notifyChange.bind(this),Ia,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ji,action:"onCreate"},{fn:Hi,action:"onCreate"},{fn:Cu,action:"onDelete"},{fn:Su,action:"onUpdate"},{fn:Nu,action:"onFlagged"},{fn:Fu,action:"onUnflagged"},{fn:_u,action:"onFlagCleared"},{fn:Bu,action:"onReactionAdded"},{fn:$u,action:"onReactionRemoved"},{fn:yl(Ar,"contentId","message"),action:"onUpdate"},{fn:yl(Tr,"contentId","message"),action:"onUpdate"},{fn:yl(Qu,"channelId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ha(e))).filter(Boolean).map((e=>el.message(e))))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=lt(t,"isDeleted",!1)),t=t.sort(((e,t)=>"segmentAsc"===this.query.sortBy?e.channelSegment-t.channelSegment:"segmentDesc"===this.query.sortBy?t.channelSegment-e.channelSegment:0)),t}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],query:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}}class Wu extends Hr{async getRequest(e,t){const{query:n,exactMatch:a,channelId:s,messageFeedId:o,userIds:i,tags:r,types:c,sortBy:d,orderBy:l,limit:u=pe}=e,h=t?{token:t}:{limit:u,sortBy:d,orderBy:l},{data:m}=await this.http.get("/api/v2/search/messages",{params:{query:n,exactMatch:a,channelId:s,messageFeedId:o,userIds:i,tags:r,types:c,options:h}});return m}}class zu extends zr{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){var t;const n=await Ia(e),a=Xe(),s=a.cache&&Date.now();a.cache&&(Hn(n,{cachedAt:s}),(null===(t=e.channels)||void 0===t?void 0:t.length)&&e.channels.forEach((e=>{it(["channel","get",e.channelId],e,{cachedAt:s})})))}appendToQueryStream(e,t,n=!1){var a,s;if(n)return void it(this.cacheKey,{data:e.messages.map(tt("message"))});const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,i=null!==(s=null==o?void 0:o.data)&&void 0!==s?s:[],r=e.messages.map(tt("message"));it(this.cacheKey,Object.assign(Object.assign({},o),{data:"prev"===t?[...new Set([...r,...i])]:[...new Set([...i,...r])]}))}}class Gu extends Zr{constructor(e,t){const n=P.default(e),a=["message","search",n];super(new Wu(e),n,a,t),this.queryStreamController=new zu(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>ha(e))).filter(ec).map((e=>el.message(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}}var Yu=Object.freeze({__proto__:null,createMessage:async e=>{const t=Xe();t.log("message/createMessage",e);const n=(e=>{var t,n;const a=Xe();if(!a.cache)return;Du=e.referenceId||ku();const s=Object.assign({messageId:Du,uniqueId:Du},e);a.log("message/createMessage.optimistically",s);const o=ot(["subChannel","get",e.subChannelId]);if(o&&(ct(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},o.data),{messageCount:o.data.messageCount+1})),o.data.channelId===o.data.subChannelId)){const e=ot(["channel","get",o.data.channelId]);(null==e?void 0:e.data)&&ct(["channel","get",o.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const i=(new Date).toISOString(),r=Object.assign({creatorId:a.userId,creatorPrivateId:jt()._id,channelSegment:(null!==(n=null==o?void 0:o.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:i,updatedAt:i,syncState:"syncing",isDeleted:!1},s);return it(["message","get",r.messageId],r,{cachedAt:-5}),Ft("local.message.created",{messages:[r]}),r})(e),a=e.referenceId||Du||ku();Du=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},Ca(e)),{referenceId:a})),s=await Ia(n),{messages:o}=s,i=t.cache&&Date.now();return t.cache&&Hn(s,{cachedAt:i}),Ft("local.message.created",{messages:[Object.assign(Object.assign({},o[0]),{syncState:"synced"})]}),{data:el.message(o[0]),cachedAt:i}}catch(e){throw Ft("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:Uu,editMessage:ju,deleteMessage:Eu,softDeleteMessage:Mu,pinMessage:async e=>{const t=Xe();let n;t.log("message/pinMessage",e);try{({data:n}=await t.http.post(`/api/v5/messages/${encodeURIComponent(e)}/pin`))}catch(t){throw 400301===(null==t?void 0:t.code)&&qu(e),t}const a=await Na(n);return t.cache&&Hn(a),Ft("local.channel.updated",a),Ws(a.channels[0])},unpinMessage:async e=>{const t=Xe();let n;t.log("message/unpinMessage",e);try{({data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/pin`))}catch(t){throw 400301===(null==t?void 0:t.code)&&qu(e),t}const a=await Na(n);return t.cache&&Hn(a),Ft("local.channel.updated",a),Ws(a.channels[0])},markAsDelivered:async(e,t)=>{const n=Xe();n.log("message/markAsDelivered",e,t);const{data:a}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:s,userEntityMarkers:o,userFeedMarkers:i}=a,r=zn(a,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Hn(Object.assign({userMarkers:s,userEntityMarkers:Zn(o),userFeedMarkers:ea(i)},r),{cachedAt:c}),!0},getReadUsers:xu,getDeliveredUsers:Ku,flagMessage:async(t,n)=>{const a=Xe();a.log("message/flag",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),o={reason:s?n:e.ContentFlagReasonEnum.Others,detail:s?"":n},{data:i}=await a.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`,o);if(a.cache){const e=await Ia(i);Hn(e)}return Ft("message.flagged",i),!!i},unflagMessage:async e=>{const t=Xe();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Ia(n);Hn(e)}return Ft("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=Xe();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:Ji,onMessageCreatedLocal:Hi,onMessageUpdated:Su,onMessageDeleted:Cu,onMessageFlagged:Nu,onMessageUnflagged:Fu,onMessageFlagCleared:_u,onMessageReactionAdded:Bu,onMessageReactionRemoved:$u,onMessageFetched:Lu,getMessage:(e,t)=>rc(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?el.message(e.data):n}))}),"messageId",El,[Lu,Su,Cu,Nu,Fu,_u,Bu,$u,yl(Ar,"contentId","message"),yl(Tr,"contentId","message"),yl(Qu,"channelId","message")]),getMessages:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getMessages(tmpid: ${o}) > listen`);const i=new Hu(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{dt(c)})),()=>{a(`getMessages(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchMessage:(e,t)=>{if(!e.query||0===e.query.trim().length)throw new Error("Query is required for message search");const{log:n,cache:a}=Xe();a||console.log(fe);const s=Date.now();n(`searchMessage(tmpid: ${s}) > listen`);const o=new Gu(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{dt(r)})),()=>{n(`searchMessage(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},convertFromRaw:fa,prepareMessagePayload:Ia,convertParams:Ca,convertQueryParams:wa});const Xu=e=>{const t=Xe();return Nt(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class Zu extends Hr{async getRequest(e,t){var n;const{limit:a=pe}=e,s=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=zn(e,["excludeDefaultSubChannel"]);const a=Object.assign({},n);return void 0!==t&&(a.excludeDefaultMessageFeed=t),a}(zn(e,["limit"])))&&void 0!==n?n:{},{channelId:o,includeDeleted:i}=s,r=zn(s,["channelId","includeDeleted"]),c=t?{token:t}:{limit:a},{data:d}=await this.http.get(`/api/v5/message-feeds/channel/${o}`,{params:Object.assign(Object.assign({},r),{isDeleted:ma(i),options:c})});return d}}class eh extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.messageFeeds.map((({messageFeedId:e})=>e))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(!Array.isArray(t)){if(this.query.channelId!==t.channelId)return;"onCreate"===e&&(a.data=[...new Set([t.subChannelId,...a.data])]),it(this.cacheKey,a)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class th extends Zr{constructor(e,t){const n=P.default(e),a=["subChannel","collection",n];super(new Zu(e),n,a,t),this.query=e,this.queryStreamController=new eh(this.query,this.cacheKey,this.notifyChange.bind(this),Ta),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[]})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Pu,action:"onCreate"},{fn:Wi,action:"onCreate"},{fn:zi,action:"onDelete"},{fn:e=>Ou((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=Xe();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=aa(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&na(t.updatedAt)>na(e.subChannelUpdatedAt)&&it(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:yl((e=>Ji((async t=>{this.isRelatedCollection(t.subChannelId)&&(await ka(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:yl((e=>Hi((async t=>{this.isRelatedCollection(t.subChannelId)&&(await ka(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>Sr((t=>{var n;const a=null!==(n=t.map((({feedId:e})=>ot(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==a.length&&e(a)})),action:"onUpdate"},{fn:yl(wr,"feedId","subChannel"),action:"onUpdate"},{fn:yl((e=>Su((async t=>{var n;const a=Xe();if("no-message-preview"===await a.getMessagePreviewSetting(!1))return;const s=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;s&&s.data.includes(t.subChannelId)&&(Da(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:yl((e=>Cu((async t=>{const n=Xe(),a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===a?await Ra(t.subChannelId):await Da(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:yl(Xu,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(sa))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=lt(e,"isDeleted",!1)),t.sort(Pt),t}isRelatedCollection(e){var t;const n=null===(t=ot(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const nh={},ah=async e=>{const t=await(async e=>{const t=Ra.locally(e);if(t)return t.data.channelId;const{data:n}=await Ra(e);return n.channelId})(e),n=Gt({channelId:t,subChannelId:e});nh[e]=nn(n)};var sh=Object.freeze({__proto__:null,getSubChannelByIds:no,createSubChannel:async e=>{const t=Xe();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),a=await Ta(n.data),s=t.cache&&Date.now();return t.cache&&Hn(a,{cachedAt:s}),Ft("message-feed.created",n.data),{data:a.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const n=Xe();n.log("channel/updateSubChannel",e,t);const a=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await Ta(a.data),o=n.cache&&Date.now();return n.cache&&Hn(s,{cachedAt:o}),Ft("message-feed.updated",a.data),{data:s.messageFeeds[0],cachedAt:o}},deleteSubChannel:Ru,hardDeleteSubChannel:async e=>{Xe().log("channel/hardDeleteSubChannel",e);return await Ru(e,!0)},softDeleteSubChannel:async e=>{Xe().log("channel/softDeleteSubChannel",e);return await Ru(e,!1)},onSubChannelCreated:Wi,onSubChannelUpdated:Ou,onSubChannelDeleted:zi,getSubChannel:(e,t)=>{const n=Xe();let a;return rc(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:sa(e.data)}),s=zn(n,["origin"]);return Ga(a,s)?void 0:(a=s,t(n))}),"subChannelId",Ra,[Pu,t=>Ou((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Ea(a),a.subChannelId===e&&t(a))})),zi,yl(wr,"feedId","subChannel"),t=>Sr((n=>{var a;if(!n.find((({feedId:t})=>t===e)))return;const s=null===(a=ot(["subChannel","get",e]))||void 0===a?void 0:a.data;s&&t(s)})),yl((t=>Ji((async n=>{n.subChannelId===e&&(await ka(n),t(n))}))),"subChannelId","subChannel"),yl((t=>Hi((async n=>{n.subChannelId===e&&(await ka(n),t(n))}))),"subChannelId","subChannel"),yl((t=>Su((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&a.subChannelId===e&&(Da(a),t(a))}))),"subChannelId","subChannel"),yl((t=>Cu((async a=>{const s=await n.getMessagePreviewSetting(!1);"no-message-preview"!==s&&a.subChannelId===e&&("message-preview-include-deleted"===s&&await Da(a),"message-preview-not-include-deleted"===s&&await Ra(a.subChannelId),t(a))}))),"subChannelId","subChannel"),yl(Xu,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:a,cache:s}=Xe(),o=Date.now();a(`getSubChannels(tmpid: ${o}) > listen`),s||console.log(fe);const i=new th(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{dt(c)})),()=>{a(`getSubChannels(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},markReadEngineOnLoginHandler:to,startMessageReceiptSync:async e=>(await ah(e),!0),stopMessageReceiptSync:e=>(nh[e]&&nh[e](),!0)});const oh=e=>{const t=Xe();return Nt(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},ih=e=>{const t=Xe();return Nt(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class rh extends Hr{async getRequest(e,t){const{limit:n=pe,displayName:a,membership:s}=e,o=zn(e,["limit","displayName","membership"]),i=t?{token:t}:{limit:n},{data:r}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},o),{keyword:a,filter:s,options:i})});return r}}class ch extends Xr{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class dh extends zr{constructor(e,t,n,a,s){super(e,t),this.notifyChange=n,this.preparePayload=a,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.channels.map(tt("channel"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(tt("channel"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(this.paginationController instanceof ch)return this.notifyChange({origin:"event",loading:!1});if(["onCreate","onJoin","onResolveChannel","onUnarchived"].includes(e)&&(Array.isArray(t)?a.data=[...new Set([...t.map(tt("channel")),...a.data])]:a.data=[...new Set([t.channelInternalId,...a.data])]),"onArchived"===e){const e=Array.isArray(t)?t.map(tt("channel")):[tt("channel")(t)];a.data=a.data.filter((t=>!e.includes(t)))}it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const lh=e=>{const t=Xe();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){Yo().resolve(e.channelId,"userMessageFeedMarker")}},uh=e=>{const t=Xe();return Nt(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))},hh=e=>{const t=Xe();return Nt(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))};class mh extends Zr{constructor(e,t){const n=P.default(e),a=["channel","collection",n],s=mh.getPaginationController(e);super(s,n,a,t),this.query=e,this.queryStreamController=new dh(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=Xe();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Qa(e)}catch(e){console.error("Error while preparing unread count info",e)}return Na(e)}),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;let i=null!==(s=o.data.map((e=>ot(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Ws))&&void 0!==s?s:[];this.paginationController instanceof rh&&(i=this.applyFilter(i)),(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof rh?()=>this.loadPage({direction:"next"}):void 0,data:i,hasNextPage:this.paginationController instanceof rh&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Xe();let n=e;switch(n=lt(n,"isDeleted",this.query.isDeleted),n=ut(n,"displayName",this.query.displayName),this.query.types&&(n=n.filter((e=>{var t;return null===(t=this.query.types)||void 0===t?void 0:t.includes(e.type)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.excludeTags&&(n=n.filter((e=>{var t;return!(null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.excludeTags)||void 0===t?void 0:t.includes(e)})))}))),this.query.membership&&t&&(n=mt(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(St);break;case"lastCreated":n=n.sort(At);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Ct);break;default:n=n.sort(Pt)}return n}shouldAbort(e){var t,n;const a=null===(t=ot(this.cacheKey))||void 0===t?void 0:t.data;if(!a)return!0;return!(null===(n=null==a?void 0:a.data)||void 0===n?void 0:n.find((t=>t===e)))}static getMessagePreviewSetting(){return Xe().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new ch(e):new rh(e)}getSubscriptions(){const e=[{fn:yl((e=>Ji((t=>{var n,a;const s=Yo();(null===(n=ot(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||s.resolve(t.subChannelId,"userMessageFeedMarker");const o=null===(a=ot(["channel","get",t.channelId]))||void 0===a?void 0:a.data;o?(Au(o,{lastActivity:t.createdAt}),e(t)):s.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:yl((e=>Hi((t=>{var n;const a=null===(n=ot(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Au(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:cs,action:"onDelete"},{fn:as,action:"onUpdate"},{fn:vs,action:"onMute"},{fn:e=>us((t=>{lh(t),e(t)})),action:"onJoin"},{fn:e=>gs(((t,n)=>{var a,s;const{userId:o}=Xe();if("member"===this.query.membership&&o===n.userId){const e=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;it(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(s=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==s?s:[]}))}return e(t)})),action:"onLeft"},{fn:Ts,action:"onMemberAdded"},{fn:ks,action:"onMemberRemoved"},{fn:e=>$s((t=>{const n=t.archives.map((e=>{var t;return null===(t=ot(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>Ls((t=>{const n=t.archives.map((e=>{var t;return null===(t=ot(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:yl(Cr,"entityId","channel"),action:"onUpdate"},{fn:yl(Tu,"entityId","channel"),action:"onUpdate"},{fn:yl((e=>Ji((async t=>{var n;if("no-message-preview"===await mh.getMessagePreviewSetting())return;if(Ua(t),this.shouldAbort(t.channelId))return;const a=null===(n=ot(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Au(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:yl((e=>Hi((async t=>{var n;if("no-message-preview"===await mh.getMessagePreviewSetting())return;if(Ua(t),this.shouldAbort(t.channelId))return;const a=null===(n=ot(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Au(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:yl((e=>Su((async t=>{"no-message-preview"!==await mh.getMessagePreviewSetting()&&(await ja(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:yl((e=>Cu((async t=>{const n=await mh.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await ja(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&(dt(["messagePreviewChannel","get",t.channelId]),await Lc(t.channelId)),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:yl((e=>zi((async t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;a.data.find((e=>{const n=ta(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await Lc(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:yl((e=>Ou((async t=>{var n;if("no-message-preview"===await mh.getMessagePreviewSetting())return;(null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data)&&(await Ea(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:yl(Wi,"channelId","channel"),action:"onUpdate"},{fn:uh,action:"onResolveChannel"},{fn:e=>hh((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=ot(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:yl(oh,"channelId","channel"),action:"onUpdate"},{fn:yl((e=>ih((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof Hr?[...e,{fn:e=>es((t=>{lh(t),e(t)})),action:"onCreate"}]:e}}const gh=()=>{var e;const t=Xe();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=st(["channelUnread","get"]))||void 0===e?void 0:e.filter((({data:e})=>!e.isDeleted)))||[];return{data:(null==n?void 0:n.reduce(((e,{data:t})=>(e.unreadCount+=t.unreadCount,e.isMentioned=e.isMentioned||t.isMentioned,e)),{unreadCount:0,isMentioned:!1}))||{unreadCount:0,isMentioned:!1},cachedAt:t.cache&&Date.now()}};class ph extends Hr{async getRequest(e,t){var n,a;const s=null!==(n=e.limit)&&void 0!==n?n:pe,o=t?Number.parseInt(t,10):0;0===o&&await Iu();const i=(null!==(a=st(["archivedChannel","get"]))&&void 0!==a?a:[]).map((e=>e.data)).slice().sort(((e,t)=>Number(new Date(t.archivedAt))-Number(new Date(e.archivedAt)))),r=o*s,c=r+s,d=i.slice(r,c),l=c<i.length;return d.length>0&&await zs(d.map((e=>e.channelId))),{archives:d,paging:{next:l?String(o+1):void 0,previous:void 0}}}}class yh extends zr{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){}appendToQueryStream(e,t,n=!1){var a,s;const o=e.archives.map((e=>e.channelId));if(n)return void it(this.cacheKey,{data:o,params:{}});const i=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,r=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},i),{data:"prev"===t?[...new Set([...o,...r])]:[...new Set([...r,...o])]}))}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(a){if("onArchived"===e){const e=a.data.filter((e=>!t.includes(e)));a.data=[...t,...e]}"onUnarchived"!==e&&"onDelete"!==e||(a.data=a.data.filter((e=>!t.includes(e)))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class vh extends Zr{constructor(e,t){const n=P.default(e),a=["archivedChannel","collection",n];super(new ph(e),n,a,t),this.queryStreamController=new yh(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:e=>$s((t=>e(t.archives.map((e=>e.channelId))))),action:"onArchived"},{fn:e=>Ls((t=>e(t.archives.map((e=>e.channelId))))),action:"onUnarchived"},{fn:e=>as((t=>e([t.channelId]))),action:"onUpdate"},{fn:e=>cs((t=>e([t.channelId]))),action:"onDelete"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>ot(["channel","get",e]))).filter((e=>Boolean(e))).map((({data:e})=>e)).map(Ws))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class fh extends Hr{async getRequest(e,t){const{query:n,exactMatch:a,isMemberOnly:s,types:o,tags:i,sortBy:r,orderBy:c,limit:d=ye}=e,l=t?{token:t}:{limit:Math.min(100,Math.max(1,d))},{data:u}=await this.http.get("/api/v2/search/channels",{params:{query:n,exactMatch:a,isMemberOnly:s,types:o,tags:i,sortBy:r,orderBy:c,options:l}});return u}}class bh extends zr{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){const t=await Na(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)return void it(this.cacheKey,{data:e.channels.map(tt("channel"))});const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,i=null!==(s=null==o?void 0:o.data)&&void 0!==s?s:[],r=e.channels.map(tt("channel"));it(this.cacheKey,Object.assign(Object.assign({},o),{data:"prev"===t?[...new Set([...r,...i])]:[...new Set([...i,...r])]}))}reactor(){return()=>this.notifyChange({origin:"event",loading:!1})}subscribeRTE(e){return e.map((e=>e.fn(this.reactor())))}}const Ih=()=>Xe().getMessagePreviewSetting(!1);class Ch extends Zr{constructor(e,t){const n=P.default(e),a=["channel","search",n];super(new fh(e),n,a,t),this.queryStreamController=new bh(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>ot(["channel","get",e]))).filter(Boolean).map((e=>Ws(e.data))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}shouldAbort(e){var t;const n=null===(t=ot(this.cacheKey))||void 0===t?void 0:t.data;return!n||!n.data.find((t=>t===e))}getSubscriptions(){return[{fn:yl((e=>Ji((t=>{var n;const a=null===(n=ot(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Au(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:yl((e=>Hi((t=>{var n;const a=null===(n=ot(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Au(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:cs,action:"onDelete"},{fn:as,action:"onUpdate"},{fn:vs,action:"onMute"},{fn:e=>$s((t=>{const n=t.archives.map((e=>{var t;return null===(t=ot(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>Ls((t=>{const n=t.archives.map((e=>{var t;return null===(t=ot(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:yl(Cr,"entityId","channel"),action:"onUpdate"},{fn:yl(Tu,"entityId","channel"),action:"onUpdate"},{fn:yl((e=>Ji((async t=>{var n;if("no-message-preview"===await Ih())return;if(Ua(t),this.shouldAbort(t.channelId))return;const a=null===(n=ot(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Au(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:yl((e=>Hi((async t=>{var n;if("no-message-preview"===await Ih())return;if(Ua(t),this.shouldAbort(t.channelId))return;const a=null===(n=ot(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Au(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:yl((e=>Su((async t=>{"no-message-preview"!==await Ih()&&(await ja(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:yl((e=>Cu((async t=>{const n=await Ih();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await ja(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&(dt(["messagePreviewChannel","get",t.channelId]),await Lc(t.channelId)),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:yl((e=>zi((async t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;a.data.find((e=>{const n=ta(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await Lc(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:yl((e=>Ou((async t=>{var n;if("no-message-preview"===await Ih())return;(null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data)&&(await Ea(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:e=>hh((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=ot(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:yl(oh,"channelId","channel"),action:"onUpdate"},{fn:yl((e=>ih((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}]}}class wh extends Hr{async getRequest(e,t){const{limit:n=pe,includeDeleted:a}=e,s=zn(e,["limit","includeDeleted"]),o=t?{token:t}:{limit:n},i=!1!==a&&void 0,{data:r}=await this.http.get(`/api/v4/channels/${encodeURIComponent(s.channelId)}/users`,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:i})});return r}}class Sh extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>tt("channelUsers")({channelId:e,userId:t})))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>tt("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;const s=tt("channelUsers")({channelId:this.query.channelId,userId:t.userId}),o=this.query.memberships,i=!o||o.includes(t.membership);"none"!==t.membership&&i?a.data.includes(s)||(a.data=[s,...a.data]):a.data=a.data.filter((e=>e!==s)),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Oh extends Zr{constructor(e,t){const n=P.default(e),a=["channelUsers","collection",n];super(new wh(e),n,a,t),this.query=e,this.queryStreamController=new Sh(this.query,this.cacheKey,this.notifyChange.bind(this),Na),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:us,action:"onJoin"},{fn:gs,action:"onLeft"},{fn:Ts,action:"onMemberAdded"},{fn:ks,action:"onMemberRemoved"},{fn:js,action:"onChannelMemberBanned"},{fn:qs,action:"onChannelMemberUnbanned"},{fn:Ns,action:"onChannelMemberRoleAdded"},{fn:Bs,action:"onChannelMemberRoleRemoved"},{fn:Js,action:"onChannelSetUserMuted"},{fn:(e=this.query.channelId,t=>{const n=Xe();return Nt(n,"user.deleted","user.deleted",(n=>{var a,s;const o=bo(n);if(0===o.users.length)return;const i=o.users[0];Hn(o);const r=tt("channelUsers")({channelId:e,userId:i.userId}),c=null===(a=ot(["channelUsers","get",r]))||void 0===a?void 0:a.data;ct(["channelUsers","get",r],Object.assign(Object.assign({},c),{user:i}));const d=null===(s=ot(["channel","get",e]))||void 0===s?void 0:s.data;d&&t(d,c)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(el.channelMember))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=ht(e,"roles",this.query.roles);this.query.memberships&&(t=t.filter((e=>{var t,n;return!(!(null===(t=this.query.memberships)||void 0===t?void 0:t.includes("muted"))||!e.isMuted)||"none"!==e.membership&&(null===(n=this.query.memberships)||void 0===n?void 0:n.includes(e.membership))}))),!1===this.query.includeDeleted&&(t=t.filter((e=>{var t;return!0!==(null===(t=e.user)||void 0===t?void 0:t.isDeleted)})));const n=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===n?At:St),t}}const Ah=(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new Oh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{dt(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}};var Th=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Xe();n.log("channel/addMembers",e,t);const{data:a}=await n.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users`,{channelId:e,userIds:t});t.forEach((e=>Ft("channel.membersAdded",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const s=await Na(a);n.cache&&Hn(s);const{channelUsers:o}=s;return!!o.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=Xe();n.log("channel/removeMembers",e,t);const{data:a}=await n.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users`,{data:{channelId:e,userIds:t}});t.forEach((e=>Ft("channel.membersRemoved",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const s=await Na(a);n.cache&&Hn(s);const{channelUsers:o}=s;return!!o.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=ht(e,"roles",t.roles);t.memberships&&(n=n.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership))));const a=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===a?At:St),n},getMembers:Ah,searchMembers:(e,t,n)=>Ah(e,t)});var Rh=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const a=Xe();a.log("channel/addRole",e,t,n);const{data:s}=await a.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),o=await Na(s);a.cache&&Hn(o),Ft("local.channel-moderator.role-added",o);const{channelUsers:i}=o;return!!i.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const a=Xe();a.log("channel/removeRole",e,t,n);const{data:s}=await a.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),o=await Na(s);a.cache&&Hn(o),Ft("local.channel-moderator.role-removed",o);const{channelUsers:i}=o;return!!i.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=Xe();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:a}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),s=await Na(a),{channelUsers:o}=s,i=n.cache&&Date.now();return n.cache&&Hn(s,{cachedAt:i}),Ft("channel.banned",a),{data:null==o?void 0:o.filter((e=>"banned"===e.membership)),cachedAt:i}},unbanMembers:async(e,t)=>{const n=Xe();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:a}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),s=await Na(a),o=n.cache&&Date.now();n.cache&&Hn(s,{cachedAt:o}),Ft("channel.unbanned",a);const{channelUsers:i}=s;return{data:null==i?void 0:i.filter((e=>"member"===e.membership)),cachedAt:o}},muteMembers:async(e,t,n=-1)=>{var a;const s=Xe();s.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:o}=await s.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:i}=o,r=-1===n?new Date("9999-12-31T23:59:59.999Z").toISOString():new Date(Date.now()+1e3*n).toISOString();return Ft("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:r,actor:null!==(a=s.userId)&&void 0!==a?a:""}),i},unmuteMembers:async(e,t)=>{var n;const a=Xe();a.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:s}=await a.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:o}=s;return Ft("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:new Date(0).toISOString(),actor:null!==(n=a.userId)&&void 0!==n?n:""}),o}}),Ph=Object.freeze({__proto__:null,Membership:Th,Moderation:Rh,getChannelByIds:zs,createChannel:$c,updateChannel:async(e,t)=>{const n=Xe();n.log("channel/updateChannel",e,t);const{data:a}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await Na(a),o=n.cache&&Date.now();n.cache&&Hn(s,{cachedAt:o});const{channels:i}=s;return{data:Wa(i.find((t=>t.channelId===e))),cachedAt:o}},deleteChannel:async e=>{const t=Xe();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await Lc(e);return Wa(n.data)},joinChannel:async e=>{const t=Xe();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),a=await Na(n);t.cache&&Hn(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=Xe();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),a=await Na(n);t.cache&&Hn(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=Xe();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new Je("Mute Period can only be positive numbers or -1(mute forever)",800110,"error");const{data:a}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:t}),{success:s}=a;return s},unmuteChannel:async e=>{const t=Xe();t.log("channel/unmuteChannel",e);const{data:n}=await t.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:0}),{success:a}=n;return a},archiveChannel:async e=>{const t=Xe();t.log("channel/archiveChannel",e),await t.http.post(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const n={channelId:e,archivedAt:(new Date).toISOString()};t.cache&&it(["archivedChannel","get",tt("archivedChannel")(n)],n),Ft("local.channel.archived",{archives:[n]})},unarchiveChannel:async e=>{var t;const n=Xe();n.log("channel/unarchiveChannel",e),await n.http.delete(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const a=null===(t=ot(["archivedChannel","get",e]))||void 0===t?void 0:t.data,s=null!=a?a:{channelId:e,archivedAt:(new Date).toISOString()};n.cache&&dt(["archivedChannel","get",e],!0),Ft("local.channel.unarchived",{archives:[s]})},getArchivedChannelIds:Iu,onChannelCreated:es,onChannelUpdated:as,onChannelDeleted:cs,onChannelJoined:us,onChannelLeft:gs,onChannelSetMuted:vs,onChannelMessagePinned:Is,onChannelMessageUnpinned:Ss,onChannelMemberAdded:Ts,onChannelMemberRemoved:ks,onChannelMemberBanned:js,onChannelMemberUnbanned:qs,onChannelMemberRoleAdded:Ns,onChannelMemberRoleRemoved:Bs,onChannelArchived:$s,onChannelUnarchived:Ls,getChannel:(e,t)=>{const n=Xe();let a;return rc(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Ws(e.data)}),s=zn(n,["origin"]);return Ga(a,s)?void 0:(a=s,t(n))}),"channelId",Lc,[as,cs,us,gs,Ts,ks,js,qs,Ns,Bs,vs,Is,Ss,wu,yl(Cr,"entityId","channel"),yl(Tu,"entityId","channel"),yl((t=>Ji((async a=>{await(async a=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Ua(a),a.channelId!==e)return;const o=null===(s=ot(["channel","get",e]))||void 0===s?void 0:s.data;o&&(Au(o,{messagePreviewId:a.messageId}),t(a))})(a),t(a)}))),"channelId","channel"),yl((t=>Hi((async a=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Ua(a),a.channelId!==e)return;const o=null===(s=ot(["channel","get",e]))||void 0===s?void 0:s.data;o&&(Au(o,{messagePreviewId:a.messageId}),t(a))}))),"channelId","channel"),yl((t=>Su((async a=>{var s;const o=null===(s=ot(["channel","get",e]))||void 0===s?void 0:s.data;if(!o||o.messagePreviewId!==a.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await ja(a),t(a))}))),"channelId","channel"),yl((t=>Cu((async a=>{var s;const o=null===(s=ot(["channel","get",e]))||void 0===s?void 0:s.data;if(!o||o.messagePreviewId!==a.messageId)return;const i=await n.getMessagePreviewSetting(!1);"no-message-preview"!==i&&("message-preview-not-include-deleted"===i?(dt(["messagePreviewChannel","get",e]),await Lc(a.channelId)):await ja(a),t(a))}))),"channelId","channel"),yl((e=>zi((async t=>{var a,s;const{channelId:o,subChannelId:i}=t,r=null===(a=ot(["messagePreviewChannel","get",o]))||void 0===a?void 0:a.data;if(!r||r.subChannelId!==i)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await Lc(o);(null===(s=ot(["channel","get",o]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),yl((t=>Ou((async a=>{var s,o;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Ea(a);const i=null===(s=ot(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!i||i.subChannelId!==a.subChannelId)return;(null===(o=ot(["channel","get",e]))||void 0===o?void 0:o.data)&&t(a)}))),"channelId","channel"),yl(Wi,"channelId","channel"),yl(oh,"channelId","channel"),yl((e=>ih((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:a,cache:s,userId:o}=Xe();s||console.log(fe);const i=Date.now();a(`getChannels(tmpid: ${i}) > listen`);const r=new mh(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{dt(d)})),()=>{a(`getChannels(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=jt();if(!t)throw new Je("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=Xe();a||console.log("For using Live Object feature you need to enable Cache!");n(`liveTotalChannelsUnread(tmpid: ${Date.now()}) > listen`);const s=[];let o,i=!1;const r=t=>{const{data:n}=t,a=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;o=a?Pr(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return s.push(ih((e=>{const{data:t}=gh();Ga(o,t)||r({loading:!1,data:t})}))),(()=>{const e=$e((async()=>gh()));Qe(e,(({error:e,data:t,loading:n,origin:a,cachedAt:o})=>{o===Ie?(r({data:t,origin:a,loading:!1,error:new He(be,800800,"error")}),i=!0,s.forEach((e=>e()))):i||r({loading:n,data:t,origin:a,error:e}),e&&s.forEach((e=>e()))}))})(),()=>{s.forEach((e=>e()))}},getArchivedChannels:(e,t)=>{const{log:n,cache:a}=Xe();a||console.log(fe);const s=Date.now();n(`getArchivedChannels(tmpid: ${s}) > listen`);const o=new vh(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{dt(r)})),()=>{n(`getArchivedChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchChannels:(e,t)=>{const{log:n,cache:a}=Xe();a||console.log(fe);const s=Date.now();n(`searchChannels(tmpid: ${s}) > listen`);const o=new Ch(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{dt(r)})),()=>{n(`searchChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Ma,isUnreadCountSupport:qa,convertFromRaw:xa,preUpdateChannelCache:Ka,prepareChannelPayload:Na,findCachedChannelByAnyId:Fa,findCachedChannelForPin:_a,updatePinnedMessageCache:Ba,applyChannelRolePayload:$a});const kh=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));it(["communityUsers","collection",e],n)}))},Dh=async(e,t)=>{const n=Xe();n.log("community/getCommunities",e);const a=e.map((e=>encodeURIComponent(e))),{data:s}=await n.http.get("/api/v3/communities/list",{params:{communityIds:a,includeDiscoverablePrivateCommunity:null==t||t}}),o=hc(s),i=n.cache&&Date.now();return n.cache&&(Hn(o,{cachedAt:i}),kh(o.communities,o.communityUsers)),{data:o.communities.map((e=>el.community(e))),cachedAt:i}};Dh.locally=e=>{const t=Xe();if(t.log("community/getCommunities.locally",e),!t.cache)return;const n=e.map((e=>ot(["community","get",e]))).filter(Boolean),a=n.map((({data:e})=>e)),s=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1))[0];return n.length<e.length?void 0:{data:a,cachedAt:s.cachedAt}};const Uh=async e=>{const t=Xe();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),a=hc(n),s=t.cache&&Date.now();t.cache&&(Hn(a,{cachedAt:s}),kh(a.communities,a.communityUsers));const{communities:o}=a;return{data:o.find((t=>t.communityId===e)),cachedAt:s}};Uh.locally=e=>{const t=Xe();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=ot(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const jh=(e,t)=>{const n=Xe();return Nt(n,e,e,(e=>{const a=hc(e);if(n.cache){Hn(a);const e=ot(["community","get",a.communities[0].communityId]);t(e.data)}else t(a.communities[0])}))},Eh=e=>jh("community.created",e),Mh=e=>jh("community.updated",e),qh=e=>jh("community.deleted",e);class xh extends Hr{async getRequest(e,t){var n;const{limit:a=pe}=e,s=zn(e,["limit"]),o=t?{token:t}:{limit:a},{data:i}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:ma(s.includeDeleted),keyword:s.displayName,filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return i}}class Kh extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.communities.map(tt("community"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(tt("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=ot(this.cacheKey))||void 0===t?void 0:t.data;n&&(it(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Nh,Fh;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Nh||(Nh={})),function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned",e.OnMemberCountChanged="OnMemberCountChanged",e.OnCommunityUserAdded="OnCommunityUserAdded",e.onCommunityUserRemoved="onCommunityUserRemoved",e.OnUserDeleted="OnUserDeleted",e.OnLocalCommunityJoin="OnLocalCommunityJoin"}(Fh||(Fh={}));class _h extends Hr{async getRequest(e,t){const{limit:n=pe,includeDeleted:a,excludingRoles:s}=e,o=zn(e,["limit","includeDeleted","excludingRoles"]),i=t?{token:t}:{limit:n},r=!1!==a&&void 0,{data:c}=await this.http.get(`/api/v3/communities/${o.communityId}/users`,{params:Object.assign(Object.assign({},o),{options:i,isDeleted:r})});return c}}class Bh extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>tt("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>tt("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{var t;const n=tt("communityUsers")({communityId:this.query.communityId,userId:e.userId});if("none"===e.communityMembership)a.data=a.data.filter((e=>e!==n));else if(!a.data.includes(n)){if(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length){if((e.roles||[]).some((e=>this.query.excludingRoles.includes(e))))return}a.data=[n,...a.data]}})),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function $h(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function Lh(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers:"community.userRemoved"===e||"local.community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership)):"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership)):"community.userUnbanned"===e?t.communityUsers.filter((e=>!$h(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!$h(e,t,"ADD_COMMUNITY_USER")))}const Qh=(e,t)=>{const n=Xe();return Nt(n,e,e,(a=>{const s=hc(a),{communities:o,communityUsers:i}=s,r=dc(o,i);if(s.communities=r,n.cache){Hn(s,void 0,!1);const n=ot(["community","get",s.communities[0].communityId]),a=Lh(e,s).map((e=>{const t=ot(["communityUsers","get",tt("communityUsers")(e)]);return null==t?void 0:t.data})).filter(ec);t(n.data,a)}else t(s.communities[0],Lh(e,s))}))},Vh=(e,t)=>{const n=Xe();return Nt(n,e,e,(a=>{const s=hc(a),{communities:o,communityUsers:i}=s,r=dc(o,i);if(s.communities=r,n.cache){Hn(s,void 0,!1);const n=ot(["community","get",s.communities[0].communityId]),a=Lh(e,s).map((e=>{const t=ot(["communityUsers","get",tt("communityUsers")(e)]);return null==t?void 0:t.data})).filter(ec);t(n.data,a)}else t(s.communities[0],Lh(e,s))}))},Jh=e=>Qh("community.userBanned",e),Hh=e=>Qh("community.userChanged",e),Wh=e=>Qh("community.userUnbanned",e),zh=e=>Qh("community.roleAdded",e),Gh=e=>Qh("community.roleRemoved",e),Yh=e=>Vh("local.community.userAdded",e),Xh=e=>Vh("local.community.userRemoved",e),Zh=e=>Qh("community.joined",e),em=e=>Qh("community.left",e),tm=e=>Vh("local.community.joined",e),nm=e=>Vh("local.community.left",e),am=e=>{const t=Xe(),n=[Nt(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},sm=e=>{const t=Xe();return Nt(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:a}=t;e(n[0],a.filter((e=>"member"===e.communityMembership)))}))},om=e=>{const t=Xe();return Nt(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:a}=t;e(n[0],a.filter((e=>"member"===e.communityMembership)))}))},im=e=>t=>{const n=Xe();return Nt(n,"user.deleted","user.deleted",(n=>{var a,s;const o=bo(n);if(0===o.users.length)return;const i=o.users[0];Hn(o);const r=tt("communityUsers")({communityId:e,userId:i.userId}),c=null===(a=ot(["communityUsers","get",r]))||void 0===a?void 0:a.data;it(["communityUsers","get",r],Object.assign(Object.assign({},c),{user:i}));const d=null===(s=ot(["community","get",e]))||void 0===s?void 0:s.data;t(d,[Object.assign(Object.assign({},c),{user:i})])}))};class rm extends Zr{constructor(e,t){const n=P.default(e),a=["communityUsers","collection",n];super(new _h(e),n,a,t),this.query=e,this.queryStreamController=new Bh(this.query,this.cacheKey,this.notifyChange.bind(this),hc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Zh,action:Fh.OnCommunityJoined},{fn:tm,action:Fh.OnCommunityJoined},{fn:em,action:Fh.OnCommunityLeft},{fn:nm,action:Fh.OnCommunityLeft},{fn:Jh,action:Fh.OnCommunityUserBanned},{fn:Hh,action:Fh.OnCommunityUserChanged},{fn:zh,action:Fh.OnCommunityUserRoleAdded},{fn:Gh,action:Fh.OnCommunityUserRoleRemoved},{fn:om,action:Fh.OnCommunityUserRoleAdded},{fn:sm,action:Fh.OnCommunityUserRoleRemoved},{fn:Wh,action:Fh.OnCommunityUserUnbanned},{fn:Yh,action:Fh.OnCommunityUserAdded},{fn:Xh,action:Fh.onCommunityUserRemoved},{fn:im(this.query.communityId),action:Fh.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["communityUsers","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=ht(e,"roles",this.query.roles);if(this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length)&&(n=n.filter((e=>!(e.roles||[]).some((e=>this.query.excludingRoles.includes(e)))))),!1===this.query.includeDeleted&&(n=n.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),"firstCreated"===this.query.sortBy)n=n.sort(St);else n=n.sort(At);return n}}class cm extends Hr{async getRequest(e,t){const{limit:n=pe,includeDeleted:a,excludingRoles:s}=e,o=zn(e,["limit","includeDeleted","excludingRoles"]),i=t?{token:t}:{limit:n},r=!1!==a&&void 0,{data:c}=await this.http.get(`/api/v3/communities/${o.communityId}/users`,{params:Object.assign(Object.assign({},o),{options:i,isDeleted:r})});return c}}class dm extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>tt("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>tt("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{const t=tt("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(a.data=a.data.filter((e=>e!==t)))})),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var lm;!function(e){e.OnCommunityJoined="onCommunityJoined",e.OnLocalCommunityJoin="onLocalCommunityJoin",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned"}(lm||(lm={}));class um extends Zr{constructor(e,t){const n=P.default(e),a=["communityUsers","collection",n];super(new cm(e),n,a,t),this.query=e,this.queryStreamController=new dm(this.query,this.cacheKey,this.notifyChange.bind(this),hc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Zh,action:lm.OnCommunityJoined},{fn:tm,action:lm.OnCommunityJoined},{fn:em,action:lm.OnCommunityLeft},{fn:nm,action:lm.OnCommunityLeft},{fn:Jh,action:lm.OnCommunityUserBanned},{fn:Hh,action:lm.OnCommunityUserChanged},{fn:sm,action:lm.OnCommunityUserRoleRemoved},{fn:Gh,action:lm.OnCommunityUserRoleRemoved},{fn:Wh,action:lm.OnCommunityUserUnbanned},{fn:im(this.query.communityId),action:lm.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["communityUsers","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=ht(e,"roles",this.query.roles);return this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(n=vt(n,this.query.search)),(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length)&&(n=n.filter((e=>!(e.roles||[]).some((e=>this.query.excludingRoles.includes(e)))))),!1===this.query.includeDeleted&&(n=n.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),n}}var hm=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Xe();n.log("community/moderation/addMembers",e,t);const{data:a}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});Ft("local.community.userAdded",a);const s=Yn(a,"communityUsers");n.cache&&Hn(s);const{communityUsers:o}=s;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=Xe();n.log("community/moderation/removeMembers",e,t);const{data:a}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});Ft("local.community.userRemoved",a);const s=Yn(a,"communityUsers");n.cache&&Hn(s);const{communityUsers:o}=s;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{var n;let a=ht(e,"roles",t.roles);t.memberships&&(a=a.filter((({communityMembership:e})=>t.memberships.includes(e)))),(null===(n=t.excludingRoles)||void 0===n?void 0:n.length)&&(a=a.filter((e=>!(e.roles||[]).some((e=>t.excludingRoles.includes(e))))));const s=t.sortBy?t.sortBy:"lastCreated";return a=a.sort("lastCreated"===s?At:St),a},getMembers:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new rm(e,(e=>{t(e)})),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{dt(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new um(e,(e=>{t(e)})),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{dt(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},onCommunityUserAdded:e=>Qh("community.userAdded",e),onCommunityUserRemoved:e=>Qh("community.userRemoved",e),onCommunityUserBanned:Jh,onCommunityUserChanged:Hh,onCommunityUserUnbanned:Wh,onCommunityUserRoleAdded:zh,onCommunityUserRoleRemoved:Gh,onLocalCommunityUserAdded:Yh,onLocalCommunityUserRemoved:Xh,onCommunityJoined:Zh,onCommunityLeft:em,onLocalCommunityJoined:tm,onLocalCommunityLeft:nm,onLocalCommunityJoin:am});class mm extends Zr{constructor(e,t){const n=P.default(e),a=["community","collection",n];super(new xh(e),n,a,t),this.query=e,this.queryStreamController=new Kh(this.query,this.cacheKey,this.notifyChange.bind(this),hc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qh,action:Nh.OnCommunityDeleted},{fn:Mh,action:Nh.OnCommunityUpdated},{fn:Zh,action:Fh.OnCommunityJoined},{fn:em,action:Fh.OnCommunityLeft},{fn:Hh,action:Fh.OnMemberCountChanged},{fn:tm,action:Fh.OnCommunityJoined},{fn:nm,action:Fh.OnCommunityLeft},{fn:yl(am,"targetId","community"),action:Nh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["community","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Xe();let n=e;return this.query.includeDeleted||(n=lt(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.membership&&t&&(n=pt(n,this.query.membership,t)),n}}class gm extends Hr{async getRequest(e,t){var n;const{limit:a=pe}=e,s=zn(e,["limit"]),o=t?{token:t}:{limit:a},{data:i}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:ma(s.includeDeleted),filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return i}}class pm extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&(Hn(t,{cachedAt:a}),kh(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.communities.map(tt("community"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(tt("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=ot(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],it(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var ym;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(ym||(ym={}));class vm extends Zr{constructor(e,t){const n=P.default(e),a=["community","collection",n];super(new gm(e),n,a,t),this.query=e,this.queryStreamController=new pm(this.query,this.cacheKey,this.notifyChange.bind(this),hc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Eh,action:ym.OnCommunityCreated},{fn:qh,action:ym.OnCommunityDeleted},{fn:Mh,action:ym.OnCommunityUpdated},{fn:Zh,action:Fh.OnCommunityJoined},{fn:em,action:Fh.OnCommunityLeft},{fn:Hh,action:Fh.OnMemberCountChanged},{fn:tm,action:Fh.OnCommunityJoined},{fn:nm,action:Fh.OnCommunityLeft},{fn:yl(am,"targetId","community"),action:ym.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>ot(["community","get",e]))).filter(ec).map((({data:e})=>Fc(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Xe();let n=e;this.query.includeDeleted||(n=lt(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.membership&&t&&(n=pt(n,this.query.membership,t));const a=(()=>"firstCreated"===this.query.sortBy?St:At)();return n=n.sort(a),n}}class fm extends Hr{async getRequest(e,t){const{limit:n=pe,includeDiscoverablePrivateCommunity:a}=e,s=zn(e,["limit","includeDiscoverablePrivateCommunity"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},s),{options:o,includeDiscoverablePrivateCommunity:null==a||a})});return i}}class bm extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&(Hn(t,{cachedAt:a}),kh(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.communities.map(tt("community"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(tt("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=ot(this.cacheKey))||void 0===t?void 0:t.data;n&&(it(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Im;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Im||(Im={}));class Cm extends Zr{constructor(e,t){const n=P.default(e),a=["trendingCommunity","collection",n];super(new fm(e),n,a,t),this.query=e,this.queryStreamController=new bm(this.query,this.cacheKey,this.notifyChange.bind(this),hc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qh,action:Im.OnCommunityDeleted},{fn:Mh,action:Im.OnCommunityUpdated},{fn:Zh,action:Fh.OnCommunityJoined},{fn:em,action:Fh.OnCommunityLeft},{fn:Hh,action:Fh.OnMemberCountChanged},{fn:tm,action:Fh.OnCommunityJoined},{fn:nm,action:Fh.OnCommunityLeft},{fn:yl(am,"targetId","community"),action:Im.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>ot(["community","get",e]))).filter(ec).map((({data:e})=>Fc(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class wm extends Hr{async getRequest(e,t){const{limit:n=pe,includeDiscoverablePrivateCommunity:a}=e,s=zn(e,["limit","includeDiscoverablePrivateCommunity"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},s),{options:o,includeDiscoverablePrivateCommunity:null==a||a})});return i}}class Sm extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&(Hn(t,{cachedAt:a}),kh(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.communities.map(tt("community"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(tt("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=ot(this.cacheKey))||void 0===t?void 0:t.data;n&&(it(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Om;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(Om||(Om={}));class Am extends Zr{constructor(e,t){const n=P.default(e),a=["community","collection",n];super(new wm(e),n,a,t),this.query=e,this.queryStreamController=new Sm(this.query,this.cacheKey,this.notifyChange.bind(this),hc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qh,action:Om.OnCommunityDeleted},{fn:Mh,action:Om.OnCommunityUpdated},{fn:Zh,action:Fh.OnCommunityJoined},{fn:em,action:Fh.OnCommunityLeft},{fn:Hh,action:Fh.OnMemberCountChanged},{fn:tm,action:Fh.OnCommunityJoined},{fn:nm,action:Fh.OnCommunityLeft},{fn:yl(am,"targetId","community"),action:Om.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>ot(["community","get",e]))).filter(ec).map((({data:e})=>Fc(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Tm extends Hr{async getRequest(e,t){var n;const{limit:a=pe,communityMembershipStatus:s}=e,o=zn(e,["limit","communityMembershipStatus"]),i={type:e.limit?"pagination":void 0},r=t?Object.assign(Object.assign({},i),{token:t}):Object.assign(Object.assign({},i),{limit:a}),{data:c}=await this.http.get("/api/v1/semantic-search/communities",{params:Object.assign(Object.assign({},o),{filter:null!=s?s:"all",options:r,includeDiscoverablePrivateCommunity:null===(n=o.includeDiscoverablePrivateCommunity)||void 0===n||n})});return c}}function Rm(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class Pm extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:Rm(e)});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Rm(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=ot(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],it(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var km;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(km||(km={}));class Dm extends Zr{constructor(e,t){const n=P.default(e),a=["community","collection",n];super(new Tm(e),n,a,t),this.query=e,this.queryStreamController=new Pm(this.query,this.cacheKey,this.notifyChange.bind(this),yc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Eh,action:km.OnCommunityCreated},{fn:qh,action:km.OnCommunityDeleted},{fn:Mh,action:km.OnCommunityUpdated},{fn:Zh,action:Fh.OnCommunityJoined},{fn:em,action:Fh.OnCommunityLeft},{fn:Hh,action:Fh.OnMemberCountChanged},{fn:tm,action:Fh.OnCommunityJoined},{fn:nm,action:Fh.OnCommunityLeft},{fn:yl(am,"targetId","community"),action:km.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>{const[t,n]=e.split(":");return{communityId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({communityId:e})=>ot(["community","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Xe();let n=e;return this.query.categoryIds&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.some((e=>!this.query.categoryIds||(0===this.query.categoryIds.length||this.query.categoryIds.includes(e))))}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.communityMembershipStatus&&t&&(n=pt(n,this.query.communityMembershipStatus,t)),n}}class Um extends Hr{async getRequest(e,t){const{limit:n=pe,communityIds:a}=e,s=zn(e,["limit","communityIds"]),o=t?{token:t}:{limit:n},i=a.map((e=>encodeURIComponent(e))),{data:r}=await this.http.get("/api/v4/communities/join/requests",{params:Object.assign(Object.assign({},s),{options:o,communityIds:i})});return r}}var jm;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(jm||(jm={}));class Em extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.joinRequests.map((e=>tt("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>tt("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;const s=(Array.isArray(t)?t:[t]).map((e=>e.joinRequestId));if(e===jm.OnLocalJoinRequestUpdated){if(!a.data.find((e=>s.includes(e))))return}e===jm.OnLocalJoinRequestCreated&&(a.data=[...new Set([...s,...a.data])]),e===jm.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>!s.includes(e)))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Mm extends Zr{constructor(e,t){const n=P.default(e),a=["joinRequestList","collection",n];super(new Um(e),n,a,t),this.query=e,this.queryStreamController=new Em(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const a=e;this.queryStreamController.appendToQueryStream(a,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Cc,action:jm.OnLocalJoinRequestCreated},{fn:wc,action:jm.OnLocalJoinRequestUpdated},{fn:Sc,action:jm.OnLocalJoinRequestUpdated},{fn:am,action:jm.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(s.data.map((e=>ot(["joinRequest","get",e]))).filter(ec).map((({data:e})=>e)).map(vc));(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.communityIds&&this.query.communityIds.length>0&&(t=t.filter((e=>this.query.communityIds.some((t=>t===e.targetId)))));const n=(()=>"firstCreated"===this.query.sortBy?St:At)();return t=t.sort(n),t}}var qm;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(qm||(qm={}));var xm=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const a=Xe();a.log("community/moderation/addRoles",e,t,n);const{data:s}=await a.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),o=gc(s);a.cache&&Hn(o),Ft("local.community.roleAdded",o);const{communityUsers:i}=o;return!!i.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const a=Xe();a.log("community/moderation/removeRoles",e,t,n);const{data:s}=await a.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),o=gc(s);a.cache&&Hn(o),Ft("local.community.roleRemoved",o);const{communityUsers:i}=o;return!!i.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=Xe();n.log("community/banMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=Yn(a,"communityUsers"),o=n.cache&&Date.now();n.cache&&Hn(s,{cachedAt:o});const{communityUsers:i}=s;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:o}},unbanMembers:async(e,t)=>{const n=Xe();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=Yn(a,"communityUsers"),o=n.cache&&Date.now();n.cache&&Hn(s,{cachedAt:o});const{communityUsers:i}=s;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:o}}}),Km=Object.freeze({__proto__:null,Moderation:xm,Membership:hm,getCommunityByIds:Dh,createCommunity:async e=>{const t=Xe();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",pc(e));Ft("community.created",n);const a=hc(n),s=t.cache&&Date.now();t.cache&&(Hn(a,{cachedAt:s}),kh(a.communities,a.communityUsers));const{communities:o}=a;return{data:el.community(o[0]),cachedAt:s}},updateCommunity:async(e,t)=>{const n=Xe();n.log("community/updateCommunity",e,t);const{data:a}=await n.http.put(`/api/v3/communities/${e}`,pc(t));Ft("community.updated",a);const s=hc(a),o=n.cache&&Date.now();n.cache&&(Hn(s,{cachedAt:o}),kh(s.communities,s.communityUsers));const{communities:i}=s;return{data:el.community(i.find((t=>t.communityId===e))),cachedAt:o}},deleteCommunity:async e=>{const t=Xe();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await Uh(e);return Ft("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),el.community(n.data)},joinCommunity:async e=>{const t=Xe();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);Ft("local.community.joined",n);const a=hc(n),s=t.cache&&Date.now();t.cache&&Hn(a,{cachedAt:s});const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=Xe();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);Ft("local.community.left",n);const a=hc(n),s=t.cache&&Date.now();t.cache&&Hn(a,{cachedAt:s});const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:Eh,onCommunityUpdated:Mh,onCommunityDeleted:qh,searchCommunities:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`searchCommunities(tmpid: ${o}) > listen`);const i=new mm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`searchCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getCommunities(tmpid: ${o}) > listen`);const i=new vm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunity:(e,t)=>rc(e,t,"communityId",Uh,[Mh,qh,Zh,em,tm,nm,Jh,Wh,Hh,yl(am,"targetId","community")],{callbackDataSelector:e=>e?el.community(e):e}),getTrendingCommunities:(e,t,n)=>{const{log:a,cache:s,userId:o}=Xe();s||console.log(fe);const i=Date.now();a(`getTrendingCommunities(tmpid: ${i}) > listen`);const r=new Cm(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>dt(d))),()=>{a(`getTrendingCommunities(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:a,cache:s,userId:o}=Xe();s||console.log(fe);const i=Date.now();a(`getRecommendedCommunities(tmpid: ${i}) > listen`);const r=new Am(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>dt(d))),()=>{a(`getRecommendedCommunities(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`semanticSearchCommunities(tmpid: ${o}) > listen`);const i=new Dm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`semanticSearchCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getJoinRequestList: (tmpid: ${o}) > listen`);const i=new Mm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{dt(c)})),()=>{a(`getJoinRequestList (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return qm}});const Nm=async e=>{const t=Xe();t.log("category/getCategory",e);const{data:n}=await t.http.get(`/api/v3/community-categories/${encodeURIComponent(e)}`),a=t.cache&&Date.now();t.cache&&Hn(n,{cachedAt:a});const{categories:s}=n;return{data:el.category((null!=s?s:[]).find((t=>t.categoryId===e))),cachedAt:a}};Nm.locally=e=>{const t=Xe();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=ot(["category","get",e]);return n?{data:el.category(n.data),cachedAt:n.cachedAt}:void 0};const Fm=async e=>{const t=Xe();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:a,limit:s,includeDeleted:o}=n,i=zn(n,["page","limit","includeDeleted"]),r=a?{token:a}:s?{limit:s}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},i),{isDeleted:ma(o),options:r})}),{paging:d}=c,l=zn(c,["paging"]),{categories:u}=l,h=t.cache&&Date.now();if(t.cache){Hn(l,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},i),{includeDeleted:o,options:r})];it(e,{categories:null==u?void 0:u.map(tt("category")),paging:d})}return{data:null!=u?u:[],cachedAt:h,paging:d}};Fm.locally=e=>{var t,n;const a=Xe();if(a.log("category/queryCategories.locally",e),!a.cache)return;const s=null!=e?e:{},{page:o,limit:i=10}=s,r=zn(s,["page","limit"]),c=o?{token:o}:i?{limit:i}:void 0,d=["category","query",Object.assign(Object.assign({},r),{options:c})],{data:l,cachedAt:u}=null!==(t=ot(d))&&void 0!==t?t:{};if(!(null==l?void 0:l.categories.length))return;const h=l.categories.map((e=>ot(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:m}=l;return h.length===(null===(n=null==l?void 0:l.categories)||void 0===n?void 0:n.length)?{data:h,cachedAt:u,paging:m}:void 0};var _m=Object.freeze({__proto__:null,getCategory:Nm,getCategories:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getCategories(tmpid: ${o}) > listen`);const{limit:i}=e,r=zn(e,["limit"]),c=null!=i?i:pe,{policy:d=ve}=null!=n?n:{},l=[],u=["category","collection",{}],h=(n=!1)=>{var a,s;const o=null===(a=ot(u))||void 0===a?void 0:a.data,i=null!==(s=null==o?void 0:o.data)&&void 0!==s?s:[];if(!n&&i.length>0&&!(null==o?void 0:o.params.page))return;const l=$e(Fm,Object.assign(Object.assign({},r),{limit:n?c:void 0,page:n||null==o?void 0:o.params.page}));Qe(l,(({data:n,error:a,loading:s,paging:o})=>{const r={loading:s,error:a,params:{page:null==o?void 0:o.next},data:i};n&&(r.data=[...new Set([...i,...n.map(tt("category"))])]),it(u,r),(n=>{var a,s;let o=null!==(a=n.data.map((e=>ot(["category","get",e]))).filter(Boolean).map((({data:e})=>el.category(e))))&&void 0!==a?a:[];switch(e.includeDeleted||(o=lt(o,"isDeleted",!1)),e.sortBy){case"firstCreated":o=o.sort(St);break;case"lastCreated":o=o.sort(At);break;default:o=o.sort(wt)}t({onNextPage:h,data:o,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})})(r)}),Le(d))};return l.push((()=>{})),h(!0),()=>{a(`getCategories(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}}});const Bm=async e=>{const t=Xe();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:a,dataTypes:s}=n,o=zn(n,["queryToken","dataTypes"]),i=(()=>{if(a)return{token:a}})(),{data:r}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},o),{dataTypes:s,resolveParent:!!(s&&s.length>0)||void 0,options:i})}),{paging:c}=r,d=zn(r,["paging"]),l=Yn(d,"communityUsers"),{posts:u}=l,{communities:h}=hc(l),m=t.cache&&Date.now();if(t.cache){Hn(Object.assign(Object.assign({},l),{communitis:h}));const e=["globalFeed","query",Object.assign(Object.assign({},o),{options:i})];it(e,{posts:u.map(tt("post")),paging:c})}return{data:u.map(el.post),cachedAt:m,paging:c}};Bm.locally=e=>{var t;const n=Xe();if(n.log("post/queryGlobalFeed.locally",e),!n.cache)return;const a=zn(null!=e?e:{},[]),s=["globalFeed","query",Object.assign({},a)],{data:o,cachedAt:i}=null!==(t=ot(s))&&void 0!==t?t:{};if(!(null==o?void 0:o.posts.length))return;const r=o.posts.map((e=>ot(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(el.post),{paging:c}=o;return r.length===o.posts.length?{data:r,cachedAt:i,paging:c}:void 0};class $m extends Hr{async getRequest(e,t){const{limit:n}=e,a=zn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},a),{options:s})});return o}}var Lm;!function(e){e.OnPostCreated="onPostCreated",e.OnPostUpdated="onPostUpdated",e.OnPostDeleted="onPostDeleted",e.OnPostFlagged="onPostFlagged",e.OnPostUnflagged="onPostUnflagged",e.OnPostReactionAdded="onPostReactionAdded",e.OnPostReactionRemoved="onPostReactionRemoved",e.OnPostApproved="onPostApproved",e.OnPostDeclined="onPostDeclined",e.OnPostPinProduct="onPostPinProduct",e.OnPostUnpinProduct="onPostUnpinProduct",e.OnPostUpdateProductTags="onPostUpdateProductTags"}(Lm||(Lm={}));class Qm extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.posts.map(tt("post"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(tt("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===Lm.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===Lm.OnPostCreated||e===Lm.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;a.data=[...new Set([t.postId,...a.data])]}e===Lm.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Vm=async e=>{const t=Xe();t.log("comment/getCommentByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/comments/list",{params:{commentIds:n}})).data}catch(t){throw e.forEach((e=>{De(null==t?void 0:t.code)&&Wn("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&Hn(a,{cachedAt:s}),{data:a.comments.map((e=>el.comment(e))),cachedAt:s}};Vm.locally=e=>{var t;const n=Xe();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const a=e.map((e=>ot(["comment","get",e]))).filter(Boolean),s=a.map((({data:e})=>e)),o=null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==a?void 0:a.length)<e.length?void 0:{data:s.map((e=>el.comment(e))),cachedAt:o.cachedAt}};const Jm=e=>{const t=Xe();if(!t.cache)return;const n=un();t.log("comment/createComment.optimistically",Object.assign({commentId:n},e));const a=(new Date).toISOString(),s={commentId:n,userId:t.userId,parentId:e.parentId,rootId:e.parentId||n,childrenNumber:0,children:[],segmentNumber:0,editedAt:a,referenceId:e.referenceId,referenceType:e.referenceType,data:e.data,metadata:e.metadata,mentionees:e.mentionees,attachments:e.attachments,links:e.links,createdAt:a,updatedAt:a,isDeleted:!1,flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,myReactions:[],path:"",targetId:"",targetType:"community",dataType:"text",syncState:"syncing",approvalStatus:fd(e)?"pending":"approved"};return it(["comment","get",s.commentId],s,{cachedAt:-5}),Ft("local.comment.created",{comments:[s],commentChildren:[],users:[],files:[],communityUsers:[]}),s},Hm=(e,t=!1)=>{const{stories:n}=e,a=n.map((e=>((e,t=!1)=>{const{storyId:n,referenceId:a}=e;return!t&&a?Object.assign(Object.assign({},e),{syncState:"synced"}):Object.assign(Object.assign({},e),{syncState:"synced",referenceId:n})})(e,t)));return Object.assign(Object.assign({},e),{stories:a})},Wm=async e=>{const t=Xe();t.log("story/getStoryByStoryId",e);const n=ot(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;ca("story",e)}let a;try{const n=await t.http.get(`/api/v4/stories/${e}`);a=Hm(n.data)}catch(t){throw De(null==t?void 0:t.code)&&Wn("story",e),t}const s=t.cache&&Date.now();return t.cache&&Hn(a,{cachedAt:s}),{data:a.stories[0],cachedAt:s}};Wm.locally=e=>{const t=Xe();t.log("story/getStorybyStoryId",e);const n=ot(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;ca("story",e)}const a=t.cache&&Date.now(),s=ot(["story","get",e]);if(s)return{data:s.data,cachedAt:a}};const zm=async(e,t=!1)=>{var n,a,s;const o=Xe(),i=null===(n=ot(["comment","get",e]))||void 0===n?void 0:n.data;if("error"===(null==i?void 0:i.syncState)){const t=Object.assign(Object.assign({},i),{isDeleted:!0});return dt(["comment","get",e]),Ft("local.comment.deleted",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]}),t}const r=await Kl(e);await o.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const c=Object.assign(Object.assign({},r.data),{isDeleted:!0});if(t?xt((()=>Wn("comment",e))):ct(["comment","get",e],{isDeleted:!0}),"story"===r.data.referenceType){const e=await Wm(r.data.referenceId);Ft("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const t=null===(a=ot(["post","get",r.data.referenceId]))||void 0===a?void 0:a.data;if(t){const n=Oi();pd(r.data)?n.removePendingAuthoredComment(t.postId,e):n.queueCommentChangeTask(new Ii(t.postId,e)),!c.parentId&&(null===(s=c.children)||void 0===s?void 0:s.length)>0&&c.children.forEach((e=>{n.queueCommentChangeTask(new Ii(t.postId,e))}))}}return Ft("local.comment.deleted",{comments:[c],commentChildren:[],files:[],users:[],communityUsers:[]}),c},Gm=e=>Object.assign(Object.assign({},e),{approvalStatus:"rejected",isDeleted:!0}),Ym=async e=>{var t;const n=Xe();let a;n.log("comment/getComment",e),ca("comment",e);try{a=(await n.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(n){const a=null===(t=ot(["comment","get",e]))||void 0===t?void 0:t.data;throw!(!!a&&pd(a))&&De(null==n?void 0:n.code)&&Wn("comment",e),n}const s=n.cache&&Date.now();n.cache&&Hn(a,{cachedAt:s});const{comments:o}=a;return{data:o.find((t=>t.commentId===e)),cachedAt:s}};Ym.locally=e=>{const t=Xe();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=ot(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Xm=e=>ou("local.comment.deleted",e),Zm=e=>{const t=Xe();return Nt(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(ct(["comment","get",n.commentId],n),e(Gc(n))):e(n)}))},eg=e=>{const t=Xe();return Nt(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(ct(["comment","get",n.commentId],n),e(Gc(n))):e(n)}))},tg=e=>ou("local.comment.created",e);var ng;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentApproved="onCommentApproved",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(ng||(ng={}));class ag extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;const o=e.comments.filter(yd).map(tt("comment"));if(n)it(this.cacheKey,{data:o});else{const e=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.referenceId===t.referenceId&&this.query.referenceType===t.referenceType&&a&&(!this.query.parentId||this.query.parentId===t.parentId)&&(this.query.parentId||!t.parentId)){if(e===ng.OnCommentCreated){if(!yd(t))return;a.data=[...new Set([t.commentId,...a.data])]}e===ng.OnCommentApproved&&(a.data=[...new Set([t.commentId,...a.data])]),e===ng.OnCommentUpdated&&pd(t)&&(a.data=a.data.filter((e=>e!==t.commentId))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class sg extends Hr{async getRequest(e,t){var n;const{pageSize:a,limit:s,includeDeleted:o}=e,i=zn(e,["pageSize","limit","includeDeleted"]),r=null!==(n=null!=a?a:s)&&void 0!==n?n:pe,c={type:i.sortBy||e.limit||e.pageSize?"pagination":void 0},d=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{pageSize:r,limit:r}),{data:l}=await this.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},i),{isDeleted:ma(o),options:d})});return l}}class og extends Zr{constructor(e,t){const n=P.default(e),a=["comments","collection",n];super(new sg(e),n,a,t),this.query=e,this.queryStreamController=new ag(this.query,this.cacheKey,this.notifyChange.bind(this),zc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){const e=this.queryStreamController.subscribeRTE([{fn:tg,action:ng.OnCommentCreated},{fn:Xm,action:ng.OnCommentDeleted},{fn:iu,action:ng.OnCommentCreated},{fn:ru,action:ng.OnCommentUpdated},{fn:cu,action:ng.OnCommentDeleted},{fn:du,action:ng.OnCommentApproved},{fn:lu,action:ng.OnCommentFlagged},{fn:uu,action:ng.OnCommentUnflagged},{fn:hu,action:ng.OnCommentReactionAdded},{fn:mu,action:ng.OnCommentReactionRemoved},{fn:Zm,action:ng.OnCommentReactionAdded},{fn:eg,action:ng.OnCommentReactionRemoved}]);if(this.query.excludeBlockUserComments){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(gi(t),pi(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["comment","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.comment);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e.filter(yd);if(this.query.includeDeleted||(t=lt(t,"isDeleted",!1)),this.query.parentId&&(t=t.filter((e=>e.parentId===this.query.parentId))),"boolean"==typeof this.query.hasFlag&&(t=this.query.hasFlag?t.filter((e=>null!=e.hashFlag)):t.filter((e=>null==e.hashFlag))),this.query.dataTypes&&("exact"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t,n;const a=(null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.sort())||[],s=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return s.length===a.length&&a.every(((e,t)=>e===s[t]))}))),"any"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t;return null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.some((t=>{var n;return null===(n=e.dataTypes)||void 0===n?void 0:n.includes(t)}))})))),this.query.excludeBlockUserComments&&(t=It(t)),"firstCreated"===this.query.sortBy)t=t.sort(St);else t=t.sort(At);return t}}class ig extends Hr{async getRequest(e,t){const{communityId:n,limit:a}=e,s=zn(e,["communityId","limit"]),o=Math.min(null!=a?a:10,100),i=t?{token:t}:{limit:o},{data:r}=await this.http.get(Oe(n),{params:Object.assign(Object.assign({},s),{options:i})});return r}}class rg extends zr{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){const t=zc(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;const o=e.comments.map(tt("comment"));if(n)it(this.cacheKey,{data:o});else{const e=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o])]}))}}matchesQuery(e){return"community"===e.targetType&&e.targetId===this.query.communityId&&(!this.query.postId||e.referenceId===this.query.postId)}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(!a||!this.matchesQuery(t))return;const s=a.data.includes(t.commentId),o=!this.query.startDate&&!this.query.endDate;switch(e){case ng.OnCommentCreated:case ng.OnCommentUpdated:if(pd(t)&&!t.isDeleted){if(s||!o)return;a.data=[...a.data,t.commentId]}else{if(!s)return;a.data=a.data.filter((e=>e!==t.commentId))}break;case ng.OnCommentApproved:case ng.OnCommentDeleted:if(!s)return;a.data=a.data.filter((e=>e!==t.commentId));break;default:return}it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class cg extends Zr{constructor(e,t){const n=P.default(e),a=["commentReviewQueue","collection",n];super(new ig(e),n,a,t),this.query=e,this.queryStreamController=new rg(this.query,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:iu,action:ng.OnCommentCreated},{fn:ru,action:ng.OnCommentUpdated},{fn:du,action:ng.OnCommentApproved},{fn:cu,action:ng.OnCommentDeleted},{fn:Xm,action:ng.OnCommentDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a;400301===(null==n?void 0:n.code)&&it(this.cacheKey,{data:[],params:{}});const s=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=s.data.map((e=>ot(["comment","get",e]))).filter(ec).map((({data:e})=>e)).filter((e=>pd(e)&&!e.isDeleted)).map(el.comment);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var dg=Object.freeze({__proto__:null,getCommentByIds:Vm,createComment:async(e,t=!0)=>{const n=Xe();n.log("comment/createComment",Object.assign(Object.assign({},e),{isOptimistic:t}));const a=t?Jm(e):void 0,s=null==a?void 0:a.commentId;try{const{data:t}=await n.http.post("/api/v3/comments",Object.assign(Object.assign({},e),{commentId:s}));if(0===t.comments.length)throw new Error("Comment not created");const a=zc(t),o=Object.assign(Object.assign({},a),{comments:a.comments.map((e=>e.commentId===(null!=s?s:e.commentId)?Object.assign(Object.assign({},e),{syncState:"synced"}):e))}),{comments:i}=o,r=n.cache&&Date.now();if(n.cache&&Hn(o,{cachedAt:r}),["post","content"].includes(e.referenceType))pd(i[0])?bd(i[0]):Oi().queueCommentChangeTask(new fi(e.referenceId,i[0].commentId,i[0].createdAt));else if("story"===e.referenceType){const n=ot(["story-reference",e.referenceId]);if(null==n?void 0:n.data){const e=ot(["story","get",n.data]);(null==e?void 0:e.data)&&Ft("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,i[0].commentId])]})],categories:[],comments:i,communities:[],communityUsers:t.communityUsers,files:t.files,users:t.users})}}return Ft("local.comment.created",{comments:[Object.assign(Object.assign({},i[0]),{syncState:"synced"})],commentChildren:o.commentChildren,users:t.users,files:t.files,communityUsers:t.communityUsers}),{data:el.comment(i[0]),cachedAt:r}}catch(e){if(a){const e=Object.assign(Object.assign({},a),{syncState:"error"});it(["comment","get",e.commentId],e,{cachedAt:Ie}),Ft("local.comment.created",{comments:[e],commentChildren:[],users:[],files:[],communityUsers:[]})}throw e}},updateComment:async(e,t)=>{var n;const a=Xe();a.log("user/updateComment",t);const s=null===(n=ot(["comment","get",e]))||void 0===n?void 0:n.data,{data:o}=await a.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),i=zc(o),r=i.comments.find((t=>t.commentId===e)),c=a.cache&&Date.now();return a.cache&&Hn(i,{cachedAt:c}),pd(r)&&s&&yd(s)&&(Od(r),wd(r)),Ft("comment.updated",o),{data:el.comment(r),cachedAt:c}},deleteComment:zm,softDeleteComment:async e=>{Xe().log("comment/softDeleteComment",e);return zm(e)},hardDeleteComment:async e=>{Xe().log("comment/hardDeleteComment",e);return zm(e,!0)},approveComment:async e=>{const t=Xe();t.log("comment/approveComment",e);const{data:n}=await t.http.post(`/api/v3/comments/${encodeURIComponent(e)}/approve`),a=zc(Yn(n,"communityUsers")),s=a.comments.find((t=>t.commentId===e)),o=t.cache&&Date.now();return t.cache&&Hn(a,{cachedAt:o}),Sd(s),Cd(s),Ft("comment.approved",n),{data:el.comment(s),cachedAt:o}},declineComment:async(e,t)=>{var n,a,s,o,i,r;const c=Xe();c.log("comment/declineComment",e,t);const d=null===(n=ot(["comment","get",e]))||void 0===n?void 0:n.data,{data:l}=await c.http.post(`/api/v3/comments/${encodeURIComponent(e)}/decline`,t?{reason:t}:void 0),u=null===(a=null==l?void 0:l.comments)||void 0===a?void 0:a.some((t=>t.commentId===e));if(!u&&!d)throw new Error("Comment not found after decline");const h={comments:u?l.comments.map((t=>t.commentId===e?Gm(t):t)):[Gm(d)],commentChildren:null!==(s=null==l?void 0:l.commentChildren)&&void 0!==s?s:[],users:null!==(o=null==l?void 0:l.users)&&void 0!==o?o:[],files:null!==(i=null==l?void 0:l.files)&&void 0!==i?i:[],communityUsers:null!==(r=null==l?void 0:l.communityUsers)&&void 0!==r?r:[]},m=zc(Yn(h,"communityUsers")),g=m.comments.find((t=>t.commentId===e)),p=c.cache&&Date.now();return c.cache&&Hn(m,{cachedAt:p}),Od(g),Id(g),Ft("comment.deleted",h),{data:el.comment(g),cachedAt:p}},flagComment:async(t,n)=>{const a=Xe();a.log("comment/flagComment",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),o={reason:n&&s?n:e.ContentFlagReasonEnum.Others,detail:n&&!s?n:""},{data:i}=await a.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`,o);return a.cache&&Hn(i),Ft("comment.flagged",i),!!i},unflagComment:async e=>{const t=Xe();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Hn(n),Ft("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=Xe();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:iu,onCommentUpdated:ru,onCommentDeleted:cu,onCommentApproved:du,onCommentFlagged:lu,onCommentUnflagged:uu,onCommentReactionAdded:hu,onCommentReactionRemoved:mu,getComment:(e,t)=>rc(e,t,"commentId",Ym,[du,Xm,cu,lu,hu,mu,uu,ru,Zm,eg]),getComments:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();a(`getComments(tmpid: ${o}) > listen`);const i=new og(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getComments(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommentReviewQueue:(e,t)=>{const{log:n,cache:a}=Xe();a||console.log(fe);const s=Date.now();n(`getCommentReviewQueue(tmpid: ${s}) > listen`);const o=new cg(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>dt(r))),()=>{n(`getCommentReviewQueue(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const lg=e=>Hl("local.post.deleted",e),ug=e=>{const t=Xe();return Nt(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(ct(["post","get",n.postId],n),e(n)):e(n)}))},hg=e=>{const t=Xe();return Nt(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(ct(["post","get",n.postId],n),e(n)):e(n)}))},mg=e=>Hl("local.post.updated",e),gg=e=>[iu,cu,tg,Xm].map((t=>({fn:yl((n=>((e,t,n)=>t((async t=>{var a;const s=null===(a=ot(n))||void 0===a?void 0:a.data;s&&s.data.includes(t.referenceId)&&e(t)})))(n,t,e)),"referenceId","post"),action:Lm.OnPostUpdated}))),pg=e=>[{fn:Wl,action:Lm.OnPostCreated},{fn:zl,action:Lm.OnPostUpdated},{fn:mg,action:Lm.OnPostUpdated},{fn:Gl,action:Lm.OnPostDeleted},{fn:Zl,action:Lm.OnPostFlagged},{fn:eu,action:Lm.OnPostUnflagged},{fn:Yl,action:Lm.OnPostApproved},{fn:Xl,action:Lm.OnPostDeclined},{fn:tu,action:Lm.OnPostReactionAdded},{fn:nu,action:Lm.OnPostReactionRemoved},{fn:ug,action:Lm.OnPostReactionAdded},{fn:hg,action:Lm.OnPostReactionRemoved},{fn:lg,action:Lm.OnPostDeleted},...gg(e)];class yg extends Zr{constructor(e,t){const n=P.default(e),a=["customRankingGlobalFeed","collection",n];super(new $m(e),n,a,t),this.query=e,this.queryStreamController=new Qm(this.query,this.cacheKey,this.notifyChange.bind(this),Ml),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(pg(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>ot(["post","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class vg extends Hr{async getRequest(e,t){const{limit:n,dataTypes:a}=e,s=zn(e,["limit","dataTypes"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},s),{dataTypes:a,resolveParent:!!(a&&a.length>0)||void 0,options:o})});return i}}class fg extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.posts.map(tt("post"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(tt("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===Lm.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===Lm.OnPostCreated||e===Lm.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;a.data=[...new Set([t.postId,...a.data])]}e===Lm.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class bg extends Zr{constructor(e,t){const n=P.default(e),a=["globalFeed","collection",n];super(new vg(e),n,a,t),this.query=e,this.queryStreamController=new fg(this.query,this.cacheKey,this.notifyChange.bind(this),Ml),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(pg(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>ot(["post","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Ig extends Hr{async getRequest(e,t){const{userId:n,feedSources:a,dataTypes:s,includeDeleted:o,matchingOnlyParentPost:i,limit:r=pe,untilAt:c}=e,d=zn(e,["userId","feedSources","dataTypes","includeDeleted","matchingOnlyParentPost","limit","untilAt"]),l=t?{token:t}:{limit:r},{data:u}=await this.http.get(`/api/v4/user-feeds/${n}`,{params:Object.assign(Object.assign({},d),{options:l,dataTypes:(null==s?void 0:s.length)?s:void 0,includePostedFeed:a,isDeleted:ma(o),matchingOnlyParentPost:null!=i?i:!(null==s?void 0:s.length)})});return u}}class Cg extends zr{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?kt(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;let o=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated",t=o.filter((t=>!Dt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)it(this.cacheKey,{data:o.map(tt("post"))});else{const e=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(tt("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(s&&(this.query.dataTypes&&0!==this.query.dataTypes.length||s.data.includes(t.parentPostId?t.parentPostId:t.postId))){if(void 0!==this.validatedUntilAt&&(e===Lm.OnPostCreated||e===Lm.OnPostApproved||e===Lm.OnPostUpdated)){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Dt(t.createdAt,this.validatedUntilAt,e))return}if(e===Lm.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=ot(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),it(["post","get",e.postId],e)}if(e===Lm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e===Lm.OnPostCreated||e===Lm.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;s.data=[...new Set([t.postId,...s.data])]}it(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const wg=async e=>{const t=Xe();let n;t.log("post/getPost",e),ca("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw De(null==t?void 0:t.code)&&Wn("post",e),t}const a=Yn(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Hn(a,{cachedAt:s});const{posts:o}=a;return{data:o.find((t=>t.postId===e)),cachedAt:s}};wg.locally=e=>{const t=Xe();if(t.log("post/getPost.locally",e),!t.cache)return;const n=ot(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Sg extends Zr{constructor(e,t){const n=P.default(e),a=["userFeed","collection",n];super(new Ig(e),n,a,t),this.query=e,this.queryStreamController=new Cg(this.query,this.cacheKey,this.notifyChange.bind(this),Ml),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Wl,action:Lm.OnPostCreated},{fn:zl,action:Lm.OnPostUpdated},{fn:mg,action:Lm.OnPostUpdated},{fn:Gl,action:Lm.OnPostDeleted},{fn:Zl,action:Lm.OnPostFlagged},{fn:eu,action:Lm.OnPostUnflagged},{fn:Yl,action:Lm.OnPostApproved},{fn:Xl,action:Lm.OnPostDeclined},{fn:tu,action:Lm.OnPostReactionAdded},{fn:nu,action:Lm.OnPostReactionRemoved},{fn:ug,action:Lm.OnPostReactionAdded},{fn:hg,action:Lm.OnPostReactionRemoved},{fn:lg,action:Lm.OnPostDeleted},{fn:yl((e=>iu((async t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await wg(t.referenceId),e(t))}))),"referenceId","post"),action:Lm.OnPostUpdated},{fn:yl((e=>cu((async t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await wg(t.referenceId),e(t))}))),"referenceId","post"),action:Lm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>ot(["post","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[],r=this.applyFilter(i).map(el.post);if(!this.shouldNotify(r)&&"event"===e)return;const c=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:r,hasNextPage:c,loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=lt(n,"isDeleted",!1)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=yt(n,this.query.dataTypes)),this.query.untilAt){const e=kt(this.query.untilAt),t="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";n=n.filter((n=>!Dt(n.createdAt,e,t)))}if("firstCreated"===this.query.sortBy)n=n.sort(St);else n=n.sort(At);return n}}class Og extends Hr{async getRequest(e,t){const{limit:n=pe,includeDeleted:a,communityId:s,untilAt:o}=e,i=zn(e,["limit","includeDeleted","communityId","untilAt"]),r=t?{token:t}:{limit:n},{data:c}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},i),{targetId:s,targetType:"community",isDeleted:ma(a),matchingOnlyParentPost:!0,options:r})});return c}}class Ag extends zr{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?kt(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;let o=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated",t=o.filter((t=>!Dt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)it(this.cacheKey,{data:o.map(tt("post"))});else{const e=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(tt("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===Lm.OnPostCreated||e===Lm.OnPostApproved)&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Dt(t.createdAt,this.validatedUntilAt,e))return}if(e===Lm.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=ot(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),it(["post","get",e.postId],e)}e===Lm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==Lm.OnPostCreated&&e!==Lm.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),it(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const Tg=({cacheKey:e,resolveId:t})=>[iu,cu,tg,Xm].map((n=>({fn:yl((a=>((e,t,n,a)=>t((async t=>{var s;const o=null===(s=ot(n))||void 0===s?void 0:s.data;o&&o.data.includes(a?a(t.referenceId):t.referenceId)&&e(t)})))(a,n,e,t)),"referenceId","post"),action:Lm.OnPostUpdated}))),Rg=e=>[{fn:Wl,action:Lm.OnPostCreated},{fn:zl,action:Lm.OnPostUpdated},{fn:mg,action:Lm.OnPostUpdated},{fn:Gl,action:Lm.OnPostDeleted},{fn:Zl,action:Lm.OnPostFlagged},{fn:eu,action:Lm.OnPostUnflagged},{fn:Yl,action:Lm.OnPostApproved},{fn:Xl,action:Lm.OnPostDeclined},{fn:tu,action:Lm.OnPostReactionAdded},{fn:nu,action:Lm.OnPostReactionRemoved},{fn:ug,action:Lm.OnPostReactionAdded},{fn:hg,action:Lm.OnPostReactionRemoved},{fn:lg,action:Lm.OnPostDeleted},...Tg({cacheKey:e})],Pg=(e,t)=>{var n;return null!==(n=e.map((e=>{const n=t.find((t=>t.postId===e.referenceId));return n?tt("post")({postId:null==n?void 0:n.postId}):void 0})).filter(ec))&&void 0!==n?n:[]};class kg extends Zr{constructor(e,t){const n=P.default(e),a=["communityFeed","collection",n];super(new Og(e),n,a,t),this.query=e,this.queryStreamController=new Ag(this.query,this.cacheKey,this.notifyChange.bind(this),Ml),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(Rg(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["post","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.post);if(!this.shouldNotify(i)&&"event"===e)return;const r=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:r,loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=lt(t,"isDeleted",!1)),this.query.tags&&(t=t.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.untilAt&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e=kt(this.query.untilAt),n="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";t=t.filter((t=>!Dt(t.createdAt,e,n)))}switch(this.query.sortBy){case"firstCreated":t=t.sort(St);break;case"firstUpdated":t=t.sort(Tt);break;case"lastUpdated":t=t.sort(Rt);break;default:t=t.sort(At)}return t}}class Dg extends He{constructor(e="For You feed is not enabled for this network"){super(e,400400,"error"),this.type="AmityForYouFeedDisabledError"}}class Ug extends Hr{constructor(e){super(e),this.checkedDisk=!1,this.hasDeliveredPost=!1,this.cursor=yi.current()}async getRequest(e,t){var n,a,s,o,i;const r=void 0===t;let c=null;if(r&&!this.checkedDisk&&this.cursor&&(this.checkedDisk=!0,c=await this.cursor.get(),c&&yi.isExpired(c.expiredAt)&&(await this.cursor.clear(),c=null)),r&&(null==c?void 0:c.reachedEndOfFeed)){const e=await this.fetch(),t=Date.parse(null!==(a=null===(n=e.paging)||void 0===n?void 0:n.expiredAt)&&void 0!==a?a:"");return!Number.isNaN(t)&&t!==c.expiredAt?(await this.persistCursor(e),e.posts.length>0&&(this.hasDeliveredPost=!0),e):Object.assign(Object.assign({},e),{posts:[],paging:{}})}const d=r&&c?c.cursor:t,l=await this.fetch(d);if(l.posts.length>0&&(this.hasDeliveredPost=!0),null===(s=l.paging)||void 0===s?void 0:s.next)await this.persistCursor(l);else if(this.hasDeliveredPost&&this.cursor){const e=Date.parse(null!==(i=null===(o=l.paging)||void 0===o?void 0:o.expiredAt)&&void 0!==i?i:"");Number.isNaN(e)||await this.cursor.markReachedEndOfFeed(e)}return l}async fetch(e){const t={limit:ye};e&&(t.token=e);try{const{data:e}=await this.http.get(Se,{params:{options:t}});return e}catch(t){if(t instanceof He&&400300===t.code)throw new Dg;if(t instanceof He&&400322===t.code&&void 0!==e){this.cursor&&await this.cursor.clear();const{data:e}=await this.http.get(Se,{params:{options:{limit:ye}}});return e}throw t}}async persistCursor(e){var t,n;if(!this.cursor)return;const a=null===(t=e.paging)||void 0===t?void 0:t.next,s=null===(n=e.paging)||void 0===n?void 0:n.expiredAt;if(!a||!s)return;const o=Date.parse(s);Number.isNaN(o)||await this.cursor.set({cursor:a,expiredAt:o})}}class jg extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.posts.map(tt("post"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(tt("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.parentPostId&&!a.data.includes(t.parentPostId)||(e!==Lm.OnPostDeleted&&e!==Lm.OnPostDeclined||(a.data=a.data.filter((e=>e!==t.postId))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Eg=["forYouFeed","collection"];class Mg extends Zr{constructor(e){const t=`for-you-feed-${Xe().userId}`,n={};super(new Ug(n),t,Eg,e),this.queryStreamController=new jg(n,this.cacheKey,this.notifyChange.bind(this),Ml),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(pg(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>ot(["post","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var qg=Object.freeze({__proto__:null,queryGlobalFeed:Bm,getCustomRankingGlobalFeed:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getCustomRankingGlobalFeed(tmpid: ${o}) > listen`);const i=new yg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getCustomRankingGlobalFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getGlobalFeed:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getGlobalFeed(tmpid: ${o}) > listen`);const i=new bg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getGlobalFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getUserFeed:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getUserFeed(tmpid: ${o}) > listen`);const i=new Sg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getUserFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunityFeed:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getCommunityFeed(tmpid: ${o}) > listen`);const i=new kg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getCommunityFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getForYouFeed:e=>{const{log:t,cache:n}=Xe();n||console.log(fe);const a=Date.now();t(`getForYouFeed(tmpid: ${a}) > listen`);const s=new Mg(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>dt(i))),()=>{t(`getForYouFeed(tmpid: ${a}) > dispose`),o.forEach((e=>e()))}},AmityForYouFeedDisabledError:Dg});const xg=async e=>{const t=Xe();t.log("post/getPostByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/posts/list",{params:{postIds:n}})).data}catch(t){throw e.forEach((e=>{De(null==t?void 0:t.code)&&Wn("post",e)})),t}const s=Yn(a,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Hn(s,{cachedAt:o}),{data:s.posts.map(el.post),cachedAt:o}};xg.locally=e=>{var t;const n=Xe();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const a=e.map((e=>ot(["post","get",e]))).filter(Boolean),s=a.map((({data:e})=>e)),o=null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==a?void 0:a.length)<e.length?void 0:{data:s.map(el.post),cachedAt:o.cachedAt}};const Kg=async(e,t=!1)=>{var n;const a=Xe(),s=await xl(e);if(await a.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await Uh(s.data.targetId),t=(null!==(n=st(["communityUsers","get"]))&&void 0!==n?n:[]).filter((({key:t})=>"communityUsers"===t[0]&&("get"===t[1]&&("string"==typeof t[2]&&t[2].includes(e.data.communityId))))).map((({data:e})=>e));Ft("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const o=Object.assign(Object.assign({},s.data),{isDeleted:!0});return t?setTimeout((()=>{Wn("post",e)}),0):ct(["post","get",e],{isDeleted:!0}),Ft("local.post.deleted",{posts:[o],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),el.post(o)};class Ng extends Hr{async getRequest(e,t){const{limit:n=pe,includeDeleted:a,matchingOnlyParentPost:s,untilAt:o}=e,i=zn(e,["limit","includeDeleted","matchingOnlyParentPost","untilAt"]),{dataTypes:r}=i,c={type:i.sortBy||e.limit?"pagination":void 0},d=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{limit:n}),{data:l}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},i),{isDeleted:ma(a),matchingOnlyParentPost:null!=s?s:!(null==r?void 0:r.length),options:d})});return l}}class Fg extends zr{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?kt(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;let o=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e=this.query.sortBy||"lastCreated",t=o.filter((t=>!Dt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)it(this.cacheKey,{data:o.map(tt("post"))});else{const e=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(tt("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===Lm.OnPostCreated||e===Lm.OnPostApproved)){const e=this.query.sortBy||"lastCreated";if(Dt(t.createdAt,this.validatedUntilAt,e))return}if(t.parentPostId&&t.isDeleted){const e=null===(a=ot(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),it(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===Lm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==Lm.OnPostCreated&&e!==Lm.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),it(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}class _g extends Zr{constructor(e,t){const n=P.default(e),a=["posts","collection",n];super(new Ng(e),n,a,t),this.query=e,this.queryStreamController=new Fg(this.query,this.cacheKey,this.notifyChange.bind(this),Ml),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){const e=this.queryStreamController.subscribeRTE(Rg(this.cacheKey));if(this.query.excludeBlockUserPosts){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(gi(t),pi(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["post","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.post);if(!this.shouldNotify(i)&&"event"===e)return;const r=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:r,loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=lt(n,"isDeleted",!1)),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),"community"===this.query.targetType&&this.query.feedType&&(n=gt(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=yt(n,this.query.dataTypes)),this.query.untilAt){const e=kt(this.query.untilAt),t=this.query.sortBy||"lastCreated";n=n.filter((n=>!Dt(n.createdAt,e,t)))}if(this.query.excludeBlockUserPosts&&(n=bt(n)),"firstCreated"===this.query.sortBy)n=n.sort(St);else n=n.sort(At);return n}}class Bg extends Hr{async getRequest(e,t){const n=zn(e,["limit"]),{communityId:a,placement:s}=n,o=zn(n,["communityId","placement"]),i=s?`/api/v1/pinned-posts/communities/${a}/${s}`:`/api/v1/pinned-posts/communities/${a}`,{data:r}=await this.http.get(i,{params:Object.assign({},o)});return r}}class $g extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=Xe(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(Sa):[]});Hn(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.pins.map(tt("pin"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(tt("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Lm.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Lg extends Zr{constructor(e,t){const n=P.default(e),a=["pinnedPosts","collection",n];super(new Bg(e),n,a,t),this.query=e,this.queryStreamController=new $g(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(Tg({cacheKey:this.cacheKey,resolveId:e=>`${this.query.placement}#${e}`}))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;let i=(null!==(s=o.data.map((e=>ot(["pin","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.pinnedPost);i=this.applyFilter(i),(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>At({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class Qg extends Hr{async getRequest(e,t){const n=zn(e,["limit"]),{data:a}=await this.http.get("/api/v1/pinned-posts/global",{params:Object.assign({},n)});return a}}class Vg extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=Xe(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(Sa)});Hn(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.pins.map(tt("pin"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(tt("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Lm.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Jg extends Zr{constructor(e,t){const n=P.default(e),a=["pinnedPosts","collection",n];super(new Qg(e),n,a,t),this.query=e,this.queryStreamController=new Vg(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:lg,action:Lm.OnPostDeleted},{fn:Gl,action:Lm.OnPostDeleted},...Tg({cacheKey:this.cacheKey,resolveId:e=>`global#${e}`})])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>ot(["pin","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.pinnedPost);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}}class Hg extends Hr{async getRequest(e,t){const{limit:n=pe}=e,a=zn(e,["limit"]),s={type:e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:n}),{data:i}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},a),{options:o})});return i}}function Wg(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function zg(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class Gg extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:Wg(e)});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Wg(e)])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(a=ot(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),it(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===Lm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==Lm.OnPostCreated&&e!==Lm.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),it(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Yg extends Zr{constructor(e,t){const n=Object.assign(Object.assign({},e),{matchingOnlyParentPost:null==e.matchingOnlyParentPost||e.matchingOnlyParentPost,dataTypes:null==e.dataTypes?["text","image"]:e.dataTypes}),a=P.default(n),s=["posts","collection",a];super(new Hg(n),a,s,t),this.query=n,this.queryStreamController=new Gg(this.query,this.cacheKey,this.notifyChange.bind(this),ql),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:zl,action:Lm.OnPostUpdated},{fn:Gl,action:Lm.OnPostDeleted},{fn:Zl,action:Lm.OnPostFlagged},{fn:eu,action:Lm.OnPostUnflagged},{fn:Yl,action:Lm.OnPostApproved},{fn:Xl,action:Lm.OnPostDeclined},{fn:tu,action:Lm.OnPostReactionAdded},{fn:nu,action:Lm.OnPostReactionRemoved},{fn:yl((e=>iu((async t=>{const n=ot(this.cacheKey);zg(null==n?void 0:n.data).includes(t.referenceId)||(await xl(t.referenceId),e(t))}))),"referenceId","post"),action:Lm.OnPostUpdated},{fn:yl((e=>cu((async t=>{const n=ot(this.cacheKey);zg(null==n?void 0:n.data).includes(t.referenceId)||(await xl(t.referenceId),e(t))}))),"referenceId","post"),action:Lm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>{const[t,n]=e.split(":");return{postId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({postId:e})=>ot(["post","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.dataTypes&&this.query.dataTypes.length>0&&(t=yt(t,this.query.dataTypes)),t}}class Xg extends Hr{async getRequest(e,t){const{limit:n=pe,matchingOnlyParentPost:a,hashtags:s,dataTypes:o,targetType:i="all"}=e,r=zn(e,["limit","matchingOnlyParentPost","hashtags","dataTypes","targetType"]),c={type:r.sortBy||e.limit?"pagination":void 0},d=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{limit:n}),{data:l}=await this.http.get("/api/v1/search/posts",{params:Object.assign(Object.assign({},r),{hashtags:s,dataTypes:o,targetType:i,matchingOnlyParentPost:null!=a?a:!(null==o?void 0:o.length),options:d})});return l}}class Zg extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.posts.map(tt("post"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(tt("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(a=ot(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),it(["post","get",e.postId],e)}e===Lm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==Lm.OnPostCreated&&e!==Lm.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),it(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ep extends Zr{constructor(e,t){const n=P.default(e),a=["posts","collection",n];super(new Xg(e),n,a,t),this.query=e,this.queryStreamController=new Zg(this.query,this.cacheKey,this.notifyChange.bind(this),Ml),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Wl,action:Lm.OnPostCreated},{fn:zl,action:Lm.OnPostUpdated},{fn:mg,action:Lm.OnPostUpdated},{fn:Gl,action:Lm.OnPostDeleted},{fn:Zl,action:Lm.OnPostFlagged},{fn:eu,action:Lm.OnPostUnflagged},{fn:Yl,action:Lm.OnPostApproved},{fn:Xl,action:Lm.OnPostDeclined},{fn:tu,action:Lm.OnPostReactionAdded},{fn:nu,action:Lm.OnPostReactionRemoved},{fn:ug,action:Lm.OnPostReactionAdded},{fn:hg,action:Lm.OnPostReactionRemoved},{fn:lg,action:Lm.OnPostDeleted},{fn:yl((e=>iu((async t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await wg(t.referenceId),e(t))}))),"referenceId","post"),action:Lm.OnPostUpdated},{fn:yl((e=>cu((async t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await wg(t.referenceId),e(t))}))),"referenceId","post"),action:Lm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["post","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if((null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=yt(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(St);else n=n.sort(At);return n}}class tp extends Xr{async getRequest(e){const{limit:t=100}=e,{data:n}=await this.http.get("/api/v1/rooms/lives",{params:{targetTypes:["all"],options:{limit:t,sortBy:"lastCreated"}}});return n}}class np extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:Pg(e.rooms,e.posts)});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Pg(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=ot(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&it(this.cacheKey,Object.assign(Object.assign({},n),{data:n.data.filter((t=>e.referenceId!==t))})),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const ap=e=>{const t=Xe();return Nt(t,"room/onRoomStartBroadcasting","room.startBroadcasting",(t=>{Hn(t),e(t.rooms[0])}))},sp=e=>{const t=Xe();return Nt(t,"room/onRoomWaitingReconnect","room.waitingReconnect",(t=>{Hn(t),e(t.rooms[0])}))},op=e=>{const t=Xe();return Nt(t,"room/onRoomEndBroadcasting","room.endBroadcasting",(t=>{Hn(t),e(t.rooms[0])}))},ip=e=>{const t=Xe();return Nt(t,"room/onRoomRecordedAvailable","room.recordedAvailable",(t=>{Hn(t),e(t.rooms[0])}))},rp=e=>{const t=Xe();return Nt(t,"room/onRoomCoHostInvited","room.didCohostInvite",(t=>{const n=Pc(t);Hn(n),e(n.invitations)}))},cp=async e=>{const t=Xe();let n;t.log("room/getRoomById",e),ca("room",e);try{n=(await t.http.get(`/api/v1/rooms/${e}`)).data}catch(t){throw De(null==t?void 0:t.code)&&Wn("room",e),t}const a=t.cache&&Date.now();return t.cache&&Hn(n,{cachedAt:a}),{data:n.rooms[0],cachedAt:a}};cp.locally=e=>{const t=Xe();t.log("room/getRoomById.locally",e),ca("room",e);const n=t.cache&&Date.now(),a=ot(["room","get",e]);if(a)return{data:a.data,cachedAt:n}};const dp=e=>{const t=Xe();return Nt(t,"room/onRoomCoHostInviteAccepted","room.didCohostInviteAccept",(async t=>{var n;const a=Pc(t);await cp(null===(n=a.invitations)||void 0===n?void 0:n[0].targetId),Hn(a),e(a.invitations[0])}))},lp=e=>{const t=Xe();return Nt(t,"room/onRoomCoHostInviteRejected","room.didCohostInviteReject",(t=>{const n=Pc(t);Hn(n),e(n.invitations)}))},up=e=>{const t=Xe();return Nt(t,"room/onRoomCoHostInviteCanceled","room.didCohostInviteCancel",(t=>{const n=Pc(t);Hn(n),e(n.invitations)}))},hp=e=>{const t=Xe();return Nt(t,"room/onRoomParticipantJoined","room.participantJoined",(t=>{const{rooms:n,users:a}=t;Hn({rooms:n,users:a}),e({room:ud(n[0]),actorInternalId:t.eventActor.userInternalId})}))},mp=e=>{const t=Xe();return Nt(t,"room/onRoomParticipantLeft","room.participantLeft",(t=>{var n;const{rooms:a,users:s}=t;Hn({rooms:a,users:s});const o=t.eventActor.userInternalId;e({room:ud(a[0]),actorInternalId:o,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===o)))||void 0===n?void 0:n.userId})}))},gp=e=>{const t=Xe();return Nt(t,"room/onRoomParticipantStageJoined","room.participantStageJoined",(t=>{const{rooms:n,users:a}=t;Hn({rooms:n,users:a}),e({room:ud(n[0]),actorInternalId:t.eventActor.userInternalId})}))},pp=e=>{const t=Xe();return Nt(t,"room/onRoomTerminated","room.terminated",(t=>{Hn(t),e(t.rooms[0])}))},yp=e=>{const t=Xe();return Nt(t,"room/onRoomDidUpdate","local.room.didUpdate",(t=>{Hn(t),e(t.rooms[0])}))},vp=e=>{const t=Xe();return Nt(t,"room/onRoomParticipantRemoved","room.participantRemoved",(t=>{var n;const{rooms:a,users:s}=t;Hn({rooms:a,users:s});const o=t.eventActor.userInternalId;e({room:ud(a[0]),actorInternalId:o,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===o)))||void 0===n?void 0:n.userId})}))},fp=e=>{const t=Xe();return Nt(t,"room/onLocalRoomDidUpdate","room.didUpdate",(t=>{Hn(t),e(t.rooms[0])}))},bp=e=>{const t=Xe();return Nt(t,"room/onRoomParticipantRemoved","local.room.participantRemoved",(t=>{Hn(t),e(t.rooms[0])}))};var Ip;!function(e){e.OnRoomCreated="OnRoomCreated",e.OnRoomUpdated="OnRoomUpdated",e.OnRoomDeleted="OnRoomDeleted",e.OnRoomStartBroadcasting="OnRoomStartBroadcasting",e.OnRoomEndBroadcasting="OnRoomEndBroadcasting",e.OnRoomParticipantJoined="OnRoomParticipantJoined",e.OnRoomParticipantLeft="OnRoomParticipantLeft",e.OnRoomDidUpdate="OnRoomDidUpdate"}(Ip||(Ip={}));const Cp=e=>t=>e((e=>{t(e.room)}));class wp extends Hr{async getRequest(e,t){const{limit:n=pe,includeDeleted:a}=e,s=zn(e,["limit","includeDeleted"]),o={type:s.sortBy||e.limit?"pagination":void 0},i=t?Object.assign(Object.assign({},o),{token:t}):Object.assign(Object.assign({},o),{limit:n}),{data:r}=await this.http.get("/api/v1/rooms",{params:Object.assign(Object.assign({},s),{isDeleted:ma(a),options:i})});return r}}class Sp extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.rooms.map(tt("room"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.rooms.map(tt("room"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Ip.OnRoomDeleted&&(a.data=a.data.filter((e=>e!==t._id))),e===Ip.OnRoomCreated&&(a.data=[...new Set([t._id,...a.data])]),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Op extends Zr{constructor(e,t){const n=P.default(e),a=["rooms","collection",n];super(new wp(e),n,a,t),this.query=e,this.queryStreamController=new Sp(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ap,action:Ip.OnRoomStartBroadcasting},{fn:op,action:Ip.OnRoomEndBroadcasting},{fn:ip,action:Ip.OnRoomUpdated},{fn:sp,action:Ip.OnRoomUpdated},{fn:pp,action:Ip.OnRoomUpdated},{fn:Cp(hp),action:Ip.OnRoomUpdated},{fn:Cp(mp),action:Ip.OnRoomUpdated},{fn:Cp(vp),action:Ip.OnRoomUpdated},{fn:bp,action:Ip.OnRoomUpdated},{fn:Cp(gp),action:Ip.OnRoomUpdated},{fn:yl(dp,"targetId","room"),action:Ip.OnRoomUpdated},{fn:yp,action:Ip.OnRoomDidUpdate},{fn:fp,action:Ip.OnRoomDidUpdate}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["room","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(ud);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=lt(t,"isDeleted",!1)),this.query.statuses&&this.query.statuses.length>0&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.type&&(t=lt(t,"type",this.query.type)),"firstCreated"===this.query.sortBy)t=t.sort(St);else t=t.sort(At);return t}}var Ap=Object.freeze({__proto__:null,createRoom:async e=>{const t=Xe();t.log("room/createRoom",e);const{data:n}=await t.http.post("/api/v1/rooms",e);Ft("local.room.created",n);const a=t.cache&&Date.now();t.cache&&Hn(n,{cachedAt:a});const{rooms:s}=n;return{data:ud(s[0]),cachedAt:a}},updateRoom:async(e,t)=>{const n=Xe();n.log("room/updateRoom",{roomId:e,bundle:t});const{data:a}=await n.http.put(`/api/v1/rooms/${e}`,t);Ft("local.room.updated",a);const s=n.cache&&Date.now();n.cache&&Hn(a,{cachedAt:s});const{rooms:o}=a;return{data:ud(o[0]),cachedAt:s}},deleteRoom:async e=>{const t=Xe();t.log("room/deleteRoom",{roomId:e}),await t.http.delete(`/api/v1/rooms/${e}`),Ft("local.room.deleted",{rooms:[{_id:e}]})},stopRoom:async e=>{const t=Xe();t.log("room/stopRoom",{roomId:e});const{data:n}=await t.http.post(`/api/v1/rooms/${e}/stop`);Ft("local.room.stopped",n);const a=t.cache&&Date.now();t.cache&&Hn(n,{cachedAt:a});const{rooms:s}=n;return{data:s[0],cachedAt:a}},getBroadcasterData:async e=>{const t=Xe();t.log("room/getBroadcasterData",{roomId:e});const{data:n}=await t.http.get(`/api/v1/rooms/${e}/token`);return n},getRecordedUrl:async e=>{const t=Xe();t.log("room/getRecordedUrl",{roomId:e});const{data:n}=await t.http.get(`/api/v1/rooms/${e}/recorded`);return n},removeParticipant:async(e,t)=>{const n=Xe();n.log("room/removeParticipant",{roomId:e,participantUserId:t}),await n.http.delete(`/api/v1/rooms/${e}/participants/${t}`),Ft("local.room.participantRemoved",{rooms:[{_id:e}],users:[{_id:t}]})},leaveRoom:async e=>{const t=Xe();t.log("room/leaveRoom",{roomId:e}),await t.http.post(`/api/v1/rooms/${e}/leave`),Ft("local.room.left",{rooms:[{_id:e}]})},AmityRoomAnalytics:ld,WatchSessionStorage:Zc,getWatchSessionStorage:td,syncWatchSessions:cd,updateCohostPermission:async(e,t,n)=>{const a=Xe();a.log("room/updatedCoHostPermission",{roomId:e,cohostId:t,canManageProductTags:n});const{data:s}=await a.http.put(`/api/v1/rooms/${e}/participants/${t}`,{canManageProductTags:n});Ft("local.room.didUpdate",s);const o=a.cache&&Date.now();a.cache&&Hn(s,{cachedAt:o});const{rooms:i}=s;return{data:ud(i[0]),cachedAt:o}},onRoomStartBroadcasting:ap,onRoomWaitingReconnect:sp,onRoomEndBroadcasting:op,onRoomRecordedAvailable:ip,onRoomCoHostInvited:rp,onRoomCoHostInviteAccepted:dp,onRoomCoHostInviteRejected:lp,onRoomCoHostInviteCanceled:up,onRoomParticipantJoined:hp,onRoomParticipantLeft:mp,onRoomParticipantStageLeft:e=>{const t=Xe();return Nt(t,"room/onRoomParticipantStageLeft","room.participantStageLeft",(t=>{const{rooms:n,users:a}=t;Hn({rooms:n,users:a}),e({room:ud(n[0]),actorInternalId:t.eventActor.userInternalId})}))},onRoomParticipantStageJoined:gp,onRoomTerminated:pp,onRoomDidUpdate:yp,onRoomCreated:e=>{const t=Xe();return Nt(t,"room/onRoomCreated","local.room.created",(t=>{Hn(t),e(t.rooms[0])}))},onRoomUpdated:e=>{const t=Xe();return Nt(t,"room/onRoomUpdated","local.room.updated",(t=>{Hn(t),e(t.rooms[0])}))},onRoomDeleted:e=>{const t=Xe();return Nt(t,"room/onRoomDeleted","local.room.deleted",(t=>{Hn(t),e(t.rooms[0])}))},onRoomStopped:e=>{const t=Xe();return Nt(t,"room/onRoomStopped","local.room.stopped",(t=>{Hn(t),e(t.rooms[0])}))},onRoomParticipantRemoved:vp,onRoomLeft:e=>{const t=Xe();return Nt(t,"room/onRoomLeft","local.room.left",(t=>{Hn(t),e(t.rooms[0])}))},onLocalRoomDidUpdate:fp,getRoom:(e,t)=>rc(e,t,"_id",cp,[op,ap,sp,pp,ip,Cp(hp),Cp(mp),Cp(vp),bp,Cp(gp),yl(dp,"targetId","room"),yp,fp],{callbackDataSelector:e=>e?el.room(e):e}),getRooms:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getRooms(tmpid: ${o}) > listen`);const i=new Op(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getRooms(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});class Tp extends Zr{constructor(e){const t={limit:100},n=P.default(t),a=["liveRoomPosts","collection",n];super(new tp(t),n,a,e),this.query=t,this.queryStreamController=new np(this.query,this.cacheKey,this.notifyChange.bind(this),Ml),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:op,action:Lm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["post","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){return e}}class Rp extends Xr{async getRequest(e){const{limit:t=100,communityIds:n}=e,{data:a}=await this.http.get("/api/v1/rooms/lives",{params:{targetTypes:["community"],targetIds:n,options:{limit:t,sortBy:"lastCreated"}}});return a}}class Pp extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:Pg(e.rooms,e.posts)});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Pg(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=ot(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&it(this.cacheKey,Object.assign(Object.assign({},n),{data:n.data.filter((t=>e.referenceId!==t))})),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class kp extends Zr{constructor(e,t){const n=P.default(e),a=["communityLiveRoomPosts","collection",n];super(new Rp(e),n,a,t),this.query=e,this.queryStreamController=new Pp(this.query,this.cacheKey,this.notifyChange.bind(this),Ml),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:op,action:Lm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["post","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){return e}}var Dp=Object.freeze({__proto__:null,getPostByIds:xg,createPost:async e=>{const t=Xe();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{attachments:n,attachmentProductTags:a}=e,s=zn(e,["attachments","attachmentProductTags"]),o=n&&n.length>0&&e.attachmentProductTags?n.map((t=>{var n;const a=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return a?Object.assign(Object.assign({},t),{productTags:a}):t})):n,{data:i}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:o}));Ft("post.created",i);const r=Ml(i),c=t.cache&&Date.now();t.cache&&Hn(r,{cachedAt:c});const{posts:d}=r;return{data:el.post(d[0]),cachedAt:c}},editPost:async(e,t)=>{const n=Xe();n.log("user/editPost",t);const{attachments:a}=t,s=a&&a.length>0&&t.attachmentProductTags?a.map((e=>{var n;const a=null===(n=t.attachmentProductTags)||void 0===n?void 0:n.get(e.fileId);return a?Object.assign(Object.assign({},e),{productTags:a}):e})):a,{data:o}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,Object.assign(Object.assign({},t),{attachments:s})),i=Yn(o,"communityUsers"),r=n.cache&&Date.now();n.cache&&Hn(i,{cachedAt:r}),Ft("local.post.updated",i);const{posts:c}=i;return{data:el.post(c.find((t=>t.postId===e))),cachedAt:r}},deletePost:Kg,softDeletePost:async e=>{Xe().log("post/softDeletePost",e);const t=await Kg(e,!1);return el.post(t)},hardDeletePost:async e=>{Xe().log("post/hardDeletePost",e);const t=await Kg(e,!0);return el.post(t)},approvePost:async e=>{const t=Xe();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);Ft("post.approved",n),"community"===n.posts[0].targetType&&Ft("community.updated",n);const a=Yn(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Hn(a,{cachedAt:s}),{data:el.post(a.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=Xe();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&Ft("community.updated",n),Ft("post.declined",n);const a=Yn(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Hn(a,{cachedAt:s}),{data:el.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async(t,n)=>{const a=Xe();a.log("post/flagPost",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),o={reason:n&&s?n:e.ContentFlagReasonEnum.Others,detail:n&&!s?n:""},{data:i}=await a.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`,o);return a.cache&&Hn(Yn(i,"communityUsers")),Ft("post.flagged",i),!!i},unflagPost:async e=>{const t=Xe();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Hn(Yn(n,"communityUsers")),Ft("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=Xe();t.log("post/isPostFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return n},createClipPost:async e=>{const t=Xe();t.log("post/createPost",e);const{attachments:n,attachmentProductTags:a}=e,s=zn(e,["attachments","attachmentProductTags"]),o=n&&n.length>0&&e.attachmentProductTags?n.map((t=>{var n;const a=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return a?Object.assign(Object.assign({},t),{productTags:a}):t})):n,{data:i}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:o}));Ft("post.created",i);const r=Yn(i,"communityUsers"),c=t.cache&&Date.now();t.cache&&Hn(r,{cachedAt:c});const{posts:d}=r;return{data:el.post(d[0]),cachedAt:c}},createAudioPost:async e=>{const t=Xe();t.log("post/createAudioPost",e);const{attachments:n,attachmentProductTags:a}=e,s=zn(e,["attachments","attachmentProductTags"]),o=n&&n.length>0&&a?n.map((e=>{const t=null==a?void 0:a.get(e.fileId);return t?Object.assign(Object.assign({},e),{productTags:t}):e})):n,{data:i}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:o}));Ft("post.created",i);const r=Ml(i),c=t.cache&&Date.now();return t.cache&&Hn(r,{cachedAt:c}),{data:Rd(null==r?void 0:r.posts[0]),cachedAt:c}},createMixedMediaPost:async e=>{var t;const n=Xe();n.log("post/createMixedMediaPost",e);const{attachments:a,attachmentProductTags:s}=e,o=zn(e,["attachments","attachmentProductTags"]),i=a&&a.length>0&&e.attachmentProductTags?a.map((t=>{var n;const a=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return a?Object.assign(Object.assign({},t),{productTags:a}):t})):a,{data:r}=await n.http.post("/api/v4/posts",Object.assign(Object.assign({},o),{attachments:i}));Ft("post.created",r);const c=Ml(r),d=n.cache&&Date.now();return n.cache&&Hn(c,{cachedAt:d}),{data:Rd(null===(t=null==c?void 0:c.posts)||void 0===t?void 0:t[0]),cachedAt:d}},createRoomPost:async e=>{const t=Xe();t.log("post/createRoomPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"room"}));Ft("post.created",n);const a=Ml(n),s=t.cache&&Date.now();t.cache&&Hn(a,{cachedAt:s});const{posts:o}=a;return{data:el.post(o[0]),cachedAt:s}},createEventPost:async e=>{const t=Xe();t.log("post/createEventPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"event"}));Ft("post.created",n);const a=Ml(n),s=t.cache&&Date.now();t.cache&&Hn(a,{cachedAt:s});const{posts:o}=a;return{data:el.post(o[0]),cachedAt:s}},pinProduct:async(e,t)=>{const n=Xe();n.log("post/pinProduct",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:t}),s=Ml(a),o=n.cache&&Date.now();return n.cache&&Hn(a,{cachedAt:o}),Ft("local.post.updated",a),{data:Rd(null==s?void 0:s.posts[0]),cachedAt:o}},unpinProduct:async e=>{const t=Xe();t.log("post/unpinProduct",e);const{data:n}=await t.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:null}),a=Ml(n),s=t.cache&&Date.now();return t.cache&&Hn(n,{cachedAt:s}),Ft("local.post.updated",n),{data:Rd(null==a?void 0:a.posts[0]),cachedAt:s}},updateProductTags:async(e,t)=>{const n=Xe();n.log("post/updateProductTags",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{productTags:t}),s=Ml(a),o=n.cache&&Date.now();return n.cache&&Hn(a,{cachedAt:o}),Ft("local.post.updated",a),{data:Rd(null==s?void 0:s.posts[0]),cachedAt:o}},onPostCreated:Wl,onPostUpdated:zl,onPostDeleted:Gl,onPostApproved:Yl,onPostDeclined:Xl,onPostFlagged:Zl,onPostUnflagged:eu,onPostReactionAdded:tu,onPostReactionRemoved:nu,getPost:(e,t)=>rc(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?el.post(e.data):n}))}),"postId",xl,[Yl,Xl,ug,hg,t=>Gl((n=>{var a;let s=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(a=ot(["post","get",n.parentPostId]))||void 0===a?void 0:a.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),it(["post","get",e.postId],e),s=e)}t(s)})),Zl,e=>tu((t=>{e(t)})),e=>nu((t=>{e(t)})),eu,zl,mg,lg,yl((t=>iu((async n=>{n.referenceId===e&&(await xl(e),t(n))}))),"referenceId","post"),yl((t=>cu((async n=>{n.referenceId===e&&(await xl(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getPosts(tmpid: ${o}) > listen`);const i=new _g(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getPinnedPosts(tmpid: ${o}) > listen`);const i=new Lg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getPinnedPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:a,cache:s}=Xe(),o=Date.now();a(`getGlobalPinnedPosts(tmpid: ${o}) > listen`);const i=new Jg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getGlobalPinnedPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`semanticSearchPosts(tmpid: ${o}) > listen`);const i=new Yg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`semanticSearchPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchPostsByHashtag:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`searchPostsByHashtag(tmpid: ${o}) > listen`);const i=new ep(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`searchPostsByHashtag(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getLiveRoomPosts:e=>{const{log:t,cache:n}=Xe();n||console.log(fe);const a=Date.now();t(`getLiveRoomPosts(tmpid: ${a}) > listen`);const s=new Tp(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>dt(i))),()=>{t(`getLiveRoomPosts(tmpid: ${a}) > dispose`),o.forEach((e=>e()))}},getCommunityLiveRoomPosts:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getCommunityLiveRoomPosts(tmpid: ${o}) > listen`);const i=new kp(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getCommunityLiveRoomPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});const Up=async e=>{const t=Xe();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),a=t.cache&&Date.now();t.cache&&Hn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:a}};Up.locally=e=>{const t=Xe();if(t.log("stream/getStream",e),!t.cache)return;const n=ot(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const jp=e=>{const t=Xe();return Nt(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Hn(t),e(t.videoStreamings[0])}))},Ep=e=>{const t=Xe();return Nt(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Hn(t),e(t.videoStreamings[0])}))},Mp=e=>{const t=Xe();return Nt(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Hn(t),e(t.videoStreamings[0])}))},qp=e=>{const t=Xe();return Nt(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Hn(t),e(t.videoStreamings[0])}))},xp=e=>{const t=Xe();return Nt(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Hn(t),e(t.videoStreamings[0])}))},Kp=(e,t)=>rc(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?el.stream(e.data):n}))}),"streamId",Up,[Mp,jp,Ep,qp,xp,Qu]);Kp.locally=e=>{const t=Xe();if(t.log("stream/getStreamById",e),!t.cache)return;const n=ot(["stream","get",e]);return n?{data:el.stream(n.data),cachedAt:n.cachedAt}:void 0};const Np=async e=>{const t=Xe();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:a,limit:s}=n,o=zn(n,["page","limit"]),i=a?{token:a}:s?{limit:s}:void 0,{data:r}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},o),{options:i})}),{paging:c,results:d}=r,{videoStreamings:l}=d,u=t.cache&&Date.now();return t.cache&&Hn(d,{cachedAt:u}),{data:l,cachedAt:u,paging:c}};var Fp=Object.freeze({__proto__:null,createStream:async e=>{const t=Xe();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),a=t.cache&&Date.now();t.cache&&Hn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:el.stream(s[0]),cachedAt:a}},updateStream:async(e,t)=>{const n=Xe();n.log("stream/updateStream",e,t);const{data:a}=await n.http.put(`/api/v3/video-streaming/${e}`,t),s=n.cache&&Date.now();n.cache&&Hn(a,{cachedAt:s});const{videoStreamings:o}=a;return{data:el.stream(o.find((t=>t.streamId===e))),cachedAt:s}},deleteStream:async e=>{const t=Xe();t.log("stream/deleteStream",e);const n=await Up(e),{data:a}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:s}=a,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return ct(["stream","get",e],o),s},disposeStream:async e=>{const t=Xe();t.log("stream/disposeStream",e);const{data:n}=await t.http.delete(`/api/v3/video-streaming/${e}/streaming-url`),a=t.cache&&Date.now();t.cache&&Hn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:a}},editStream:async(e,t)=>{const n=Xe();n.log("stream/updateStream",e,t);const{data:a}=await n.http.put(`/api/v3/video-streaming/${e}`,t),s=n.cache&&Date.now();n.cache&&Hn(a,{cachedAt:s});const{videoStreamings:o}=a;return{data:el.stream(o.find((t=>t.streamId===e))),cachedAt:s}},onStreamStarted:jp,onStreamStopped:Ep,onStreamRecorded:Mp,onStreamFlagged:qp,onStreamTerminated:xp,onStreamViewerBanned:Qu,onStreamViewerUnbanned:e=>{const t=Xe();return Nt(t,"stream/onStreamViewerDidUnban","video-streaming.viewerDidUnban",(async t=>{var n;const{list:a}=t;await Promise.all(a.map((({streamId:e})=>Up(e))));const s=null===(n=ot(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))},getStreamById:Kp,getStreams:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getStreams(tmpid: ${o}) > listen`);const{limit:i}=e,r=zn(e,["limit"]),c=null!=i?i:pe,{policy:d=ve}=null!=n?n:{},l=[],u=["streams","collection",e],h=t=>{let n=lt(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?At:St),n},m=(e,n=!1)=>{var a,s;const o=null!==(a=e.data.map((e=>ot(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==a?a:[];t({onNextPage:p,data:n?h(o):o,hasNextPage:!!(null===(s=e.params)||void 0===s?void 0:s.page),loading:e.loading,error:e.error})},g=e=>e=>{var t;const n=null===(t=ot(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],it(u,n),m(n,!0))},p=(e=!1)=>{var t,n;const a=null===(t=ot(u))||void 0===t?void 0:t.data,s=null!==(n=null==a?void 0:a.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==a?void 0:a.params.page))return;const o=$e(Np,Object.assign(Object.assign({},r),{limit:e?c:void 0,page:e||null==a?void 0:a.params.page}));Qe(o,(({data:e,error:t,loading:n,paging:a})=>{const o={loading:n,error:t,params:{page:null==a?void 0:a.next},data:s};e&&(o.data=[...new Set([...s,...e.map(tt("stream"))])]),it(u,o),m(o)}),Le(d))};return l.push(Mp(g()),jp(g()),Ep(g())),p(!0),()=>{a(`getStreams(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}}});const _p=async()=>{const e=Xe();e.log("presence/getPresenceSetting");const{data:t}=await e.http.get("/api/v1/presence/settings");return it(["get","presenceSetting"],t),t};class Bp{constructor(e){this.isEnabled=!1,this.config={heartbeatInterval:3e4},this.roomId=e,this.initializeConfig().catch((e=>{console.error("Failed to initialize RoomPresenceSyncEngine config in constructor:",e)}))}async initializeConfig(){try{const e=await Bp.getPresenceSettingWithRetry();e?this.config={heartbeatInterval:60*(e.network.heartbeatInterval||5)*1e3}:this.config.heartbeatInterval=3e5}catch(e){console.error("Failed to initialize RoomPresenceSyncEngine config:",e),this.config.heartbeatInterval=3e5}}static async getPresenceSettingWithRetry(e=5){for(let t=0;t<e;t+=1)try{return await _p()}catch(n){if(t>=e-1)return console.error(`Failed to get presence setting after ${e} attempts:`,n),null;const a=2e4+5e3*Math.random();console.warn(`Failed to get presence setting (attempt ${t+1}/${e}), retrying in ${Math.round(a/1e3)}s:`,n),await new Promise((e=>{setTimeout(e,a)}))}return null}start(){this.isEnabled||(this.isEnabled=!0,this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>{this.sendHeartbeat()}),this.config.heartbeatInterval))}stop(){this.isEnabled=!1,this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async sendHeartbeat(){try{const e=Xe();await e.http.post(`/api/v1/presence/rooms/${this.roomId}/heartbeat`)}catch(e){console.error(`Heartbeat failed for room ${this.roomId}:`,e)}}getRoomId(){return this.roomId}isActive(){return this.isEnabled}destroy(){this.stop()}onSessionDestroyed(){this.destroy()}onTokenExpired(){this.stop()}}const $p=new Map,Lp=e=>{let t=$p.get(e);return t||(t=new Bp(e),$p.set(e,t)),t};var Qp=Object.freeze({__proto__:null,getRoomOnlineUsers:async e=>{var t,n,a;const s=Xe();s.log("room/getWatchingUsers",{roomId:e});const{data:o}=await s.http.get(`/api/v1/presence/rooms/${e}/users`),i=null!==(t=null==o?void 0:o.viewers.map((e=>e.userId)))&&void 0!==t?t:[],r=[];for(let e=0;e<i.length;e+=100)r.push(i.slice(e,e+100));const c=await Promise.all(r.map((e=>tl(e)))),d=[];return c.forEach((e=>{e.data&&d.push(...e.data)})),{data:d,cachedAt:null!==(a=null===(n=c[0])||void 0===n?void 0:n.cachedAt)&&void 0!==a?a:Date.now()}},getRoomUserCount:async e=>{const t=Xe();t.log("roomPresence/getRoomUserCount",{roomId:e});const{data:n}=await t.http.get(`/api/v1/presence/rooms/${e}/users/count`);return it(["get","watchingCount",e],n),n},startHeartbeat:e=>{Lp(e).start()},stopHeartbeat:e=>{Lp(e).stop(),(e=>{const t=$p.get(e);t&&(t.destroy(),$p.delete(e))})(e)}});const Vp=async e=>{const t=Xe();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),a=t.cache&&Date.now();t.cache&&Hn(n,{cachedAt:a});const{polls:s}=n,o=s.find((t=>t.pollId===e));return{data:hd(o),cachedAt:a}};Vp.locally=e=>{const t=Xe();if(t.log("poll/getPoll",e),!t.cache)return;const n=ot(["poll","get",e]);return n?{data:hd(n.data),cachedAt:n.cachedAt}:void 0};const Jp=e=>{const t=Xe();return Nt(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Hn(n),e(n.polls[0])}))},Hp=e=>{const t=Xe();return Nt(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Hn(n),e(n.polls[0])}))};var Wp=Object.freeze({__proto__:null,createPoll:async e=>{const t=Xe();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),a=t.cache&&Date.now();t.cache&&Hn(n,{cachedAt:a});const{polls:s}=n;return{data:hd(s[0]),cachedAt:a}},closePoll:async e=>{const t=Xe();t.log("user/closePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}`,{status:"closed"}),a=t.cache&&Date.now();t.cache&&Hn(n,{cachedAt:a}),Ft("poll.updated",n);const{polls:s}=n,o=s.find((t=>t.pollId===e));return{data:hd(o),cachedAt:a}},deletePoll:async e=>{const t=Xe();t.log("poll/deletePoll",e);const n=await Vp(e),{data:a}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=a,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return ct(["poll","get",e],o),Ft("poll.deleted",{polls:[o],users:[]}),s},votePoll:async(e,t)=>{const n=Xe();n.log("user/votePoll",e);const{data:a}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),s=n.cache&&Date.now();n.cache&&Hn(a,{cachedAt:s});const{polls:o}=a,i=o.find((t=>t.pollId===e));return Ft("poll.updated",a),{data:hd(i),cachedAt:s}},unvotePoll:async e=>{const t=Xe();t.log("user/unvotePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:[]}),a=t.cache&&Date.now();t.cache&&Hn(n,{cachedAt:a}),Ft("poll.updated",n)},onPollUpdated:Jp,onPollDeleted:Hp,getPoll:(e,t)=>rc(e,t,"pollId",Vp,[Jp,Hp])});class zp{constructor(){this._unsyncedData=[],this._syncBuffer=[],this._activeStreams=[],this._startInterval(),this._syncInterval=null}registerStream(e){this._activeStreams.push(e)}getActiveStreams(){return this._activeStreams}unregisterStream(e){this._activeStreams=this._activeStreams.filter((t=>t!==e))}updateUsage(e){this._unsyncedData.push(e)}bufferCurrentUsage(){const e=this._unsyncedData;return this._unsyncedData=[],e}dispose(){this._syncInterval&&clearInterval(this._syncInterval)}_startInterval(){this._syncInterval=setInterval((()=>{!async function({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:a}){const s=e();if(s.length)try{const n=(new Date).toISOString(),o=await rd({timestamp:n,streams:s});if(!o||!o.signature)throw new Error("Signature is undefined");const i={signature:o.signature,nonceStr:o.nonceStr,timestamp:n,streams:s},r=Xe();await r.http.post("/api/v3/user-event/video-streaming",i),t().length||e().length||a()}catch(e){return s.forEach((e=>n(e))),!1}}({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let Gp=null;class Yp{constructor(e,t,n){this._SDKUnsubscribers=[],this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=Gp||(Gp=new zp,Gp),this._usageCollector.registerStream(e.id),this._sessionId=String(O.default.v4()),this._controller=new AbortController,this._observer=new MutationObserver((t=>{t.forEach((t=>{t.removedNodes.forEach((t=>{t===e&&(this._unregisterEvents(),this._SDKUnsubscribers.forEach((e=>null==e?void 0:e())))}))}))})),this._SDKUnsubscribers.push(Qu((e=>{e.watcherUrl||(this.player.pause(),this.player.removeAttribute("src"),this.player.load(),this.player.remove())})))}_resetStartTime(){this._startTime=Date.now()}_shouldUpdateCollector(){return!!this._startTime&&Date.now()-this._startTime>2e4}_sendUsageToCollector(){if(!this._startTime)return;const e=Date.now(),t=e-this._startTime,n=Math.round(t/1e3);n&&this._usageCollector.updateUsage({streamId:this.player.id,sessionId:this._sessionId,startTime:this._startTime?new Date(this._startTime).toISOString():null,endTime:new Date(e).toISOString(),watchSeconds:n,resolution:this.resolution})}registerEvents(){this.player.addEventListener("play",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("playing",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("timeupdate",(()=>{this._shouldUpdateCollector()&&(this._sendUsageToCollector(),this._resetStartTime())}),{signal:this._controller.signal}),this.player.addEventListener("pause",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal}),this.player.addEventListener("ended",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal})}_unregisterEvents(){this._usageCollector.unregisterStream(this.player.id),this._controller.abort(),this._observer.disconnect()}}var Xp=Object.freeze({__proto__:null,getPlayer:async e=>{const{streamId:t}=e;if(!document)throw new Error("This method can be invoked within the browser enviornment only");if(!k.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await Up(t),{watcherUrl:a,status:s,recordings:o=[],resolution:i}=n;if(!a.hls)throw new Error("This stream does not support hls. Unable to play");const r=document.createElement("video");r.id=t,r.controls=!0;const c=new k.default;if(c.attachMedia(r),"recorded"!==s){let{url:e}=a.hls;e=e.replace("http:","https:"),c.loadSource(e)}else{const e=o.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");r.src=e.mp4.url}return new Yp(r,i,t).registerEvents(),r}});const Zp=e=>{const t=(e=>{var t;const n=Xe(),a=new Date,s=a.getTime()+31536e6,o=new Date(s).toISOString();let i=null===(t=ot(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return i||(i={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:o,targetPublicId:e.targetId,targetUpdatedAt:a.toISOString()},Hn({storyTargets:[i]})),{stories:[Object.assign({createdAt:a.toISOString(),updatedAt:a.toISOString(),flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,storyId:e.referenceId,path:"",creatorId:n.userId||"",creatorPublicId:n.userId||"",targetPublicId:e.targetId,comments:[],commentsCount:0,isDeleted:!1,hasFlaggedComment:!1,mentionedUsers:[],impression:0,reach:0,expiresAt:new Date(s).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Hn(t),t},ey=({payload:e,formData:t,isVideo:n=!1},a)=>{if(t){const s=t.getAll("files")[0]||void 0;if(!s)return;const o=Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:s.uri})});return n&&(o.data.videoFileId={original:void 0}),a(Zp(o))}return a(Zp(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},ty=async e=>{const t=Xe();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),a=Hm(n.data);t.cache&&Hn(a),it(["story-sync-state",e.targetId],"synced"),Ft("local.story.created",a);const s=t.cache&&Date.now();return{data:a.stories.length>0?a.stories[0]:void 0,cachedAt:s}},ny=async({targetId:e,targetType:t})=>{var n,a;if(!ot(["storyTarget","get",e])){let s={targetId:e,targetType:t};if("community"===t){const t=await Uh(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.communityId,targetUpdatedAt:null!==(n=t.data.updatedAt)&&void 0!==n?n:(new Date).toISOString()})}if("user"===t){const t=await cl(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(a=t.data.updatedAt)&&void 0!==a?a:(new Date).toISOString()})}it(["storyTarget","get",e],s)}},ay=e=>e?ot(["story","get",e]):{data:void 0,cachedAt:void 0},sy=async(e,t=!1)=>{var n,a,s;const o=Xe();let i;if(o.log("story/deleteStory",e),o.cache&&(i=ay(e),null==i?void 0:i.data)){const{data:o}=i;if(Ft("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},o),{isDeleted:!0})]}),"synced"!==o.syncState){t?dt(["story","get",e]):it(["story","get",e],Object.assign(Object.assign({},i.data),{isDeleted:!0}));const a=null===(n=st(["story","get"]))||void 0===n?void 0:n.filter((e=>"synced"!==e.data.syncState&&e.data.targetId===o.targetId&&!0!==e.data.isDeleted));if(a&&a.length>0){const e=a.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0));it(["story-expire",i.data.targetId],e.toISOString())}else dt(["story-expire",i.data.targetId]);return!0}const r=null===(a=ot(["storyTarget","get",o.targetId]))||void 0===a?void 0:a.data,c=null===(s=st(["story","get"]))||void 0===s?void 0:s.filter((e=>"synced"===e.data.syncState&&e.data.targetId===o.targetId&&!0!==e.data.isDeleted));let d;c&&c.length>0&&(d=null==c?void 0:c.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0))),r&&it(["storyTarget","get",o.targetId],Object.assign(Object.assign({},r),{lastStoryExpiresAt:d}))}return(await o.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},oy=e=>{const t=Xe(),n=[Nt(t,"onStoryUpdated","story.updated",(async t=>{const n=Hm(t);Hn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},iy=e=>{const t=Xe(),n=[Nt(t,"onStoryUpdated","local.story.updated",(async t=>{Hn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},ry=e=>{const t=Xe(),n=[Nt(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,a=zn(t,["reactions"]),s=Hm(a),o=$l("story.reactionAdded",Object.assign(Object.assign({},s),{reactions:n}));Hn(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},cy=e=>{const t=Xe(),n=[Nt(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Hn({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},dy=e=>{const t=Xe(),n=[Nt(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,a=zn(t,["reactions"]),s=Hm(a),o=$l("story.reactionRemoved",Object.assign(Object.assign({},s),{reactions:n}));Hn(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},ly=e=>{const t=Xe(),n=[Nt(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Hn({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},uy=e=>{e.forEach((e=>{const t=ot(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||it(["story-expire",e.targetId],n.toISOString())}))},hy=e=>{e.forEach((e=>{it(["story-reference",e.storyId],e.referenceId)}))},my=async({targetType:e,targetId:t,options:n})=>{const a=Xe();a.log("story/getActiveStoriesByTarget");const s=a.cache&&Date.now(),o=await a.http.get("/api/v4/stories",{params:{targetType:e,targetId:t,options:{sortBy:(null==n?void 0:n.sortBy)||"createdAt",orderBy:(null==n?void 0:n.orderBy)||"desc"}}}),i=Hm(o.data);return a.cache&&(Hn(i),uy(i.stories),hy(i.stories)),{data:i.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},gy=e=>{const t=Xe(),n=[Nt(t,"onStoryCreated","story.created",(async t=>{const n=Hm(t,!0);Hn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},py=e=>{const t=Xe(),n=[Nt(t,"onStoryCreated","local.story.created",(async t=>{Hn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},yy=e=>{const t=Xe(),n=[Nt(t,"onStoryDeleted","story.deleted",(async t=>{const n=Hm(t);Hn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},vy=e=>{const t=Xe(),n=[Nt(t,"onStoryDeleted","local.story.deleted",(async t=>{Hn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},fy=e=>{const t=Xe();return Nt(t,"onStoryError","local.story.error",(async t=>{Hn(t),e(t.stories)}))},by=e=>t=>e((e=>t(e[0]))),Iy=async e=>{const t=Xe();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:a}=n;return t.cache&&Hn(n.data),{data:a.storyTargets,cachedAt:Date.now()}};class Cy extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.paginationController=a}saveToMainDB(e){const t=Xe(),n=t.cache&&Date.now(),a=Hm(e);t.cache&&(Hn(a,{cachedAt:n}),uy(a.stories),hy(a.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.stories.map(this.getStoryReferenceIds)])]}))}}reactor(e){return e=>{var t;const n=null===(t=ot(this.cacheKey))||void 0===t?void 0:t.data;if(!n)return;const a=e.map((({referenceId:e})=>e));n.data=[...new Set([...a,...n.data])],it(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class wy extends Xr{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class Sy extends Zr{constructor(e,t){const n=P.default(e),a=["story-target-ids","collection",n],s=new wy(e);super(s,n,a,t),this.query=e,this.queryStreamController=new Cy(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;let o=s.data.map((e=>ot(["story","get",e]))).filter(Boolean).map((e=>el.story(e.data)));(this.shouldNotify(o)||"event"!==e)&&(o=this.applyFilter(o),this.callback({onNextPage:void 0,data:o,hasNextPage:!1,loading:t,error:n}))}applyFilter(e){var t,n;const a=e;return"asc"===((null===(n=null===(t=this.query)||void 0===t?void 0:t.options)||void 0===n?void 0:n.orderBy)||"desc")?a.sort(St):a.sort(At)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:gy,action:"onCreate"},{fn:oy,action:"onUpdate"},{fn:yy,action:"onDelete"},{fn:fy,action:"onError"}])}}const Oy=(e,t)=>{var n,a;const s=null===(n=ot(e))||void 0===n?void 0:n.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[];it(e,Object.assign(Object.assign({},s),{data:[...new Set([...o,...t])]}))};class Ay extends zr{constructor(e,t,n,a,s){super(e,t),this.notifyChange=n,this.paginationController=a,this.preparePayload=s}saveToMainDB(e){const t=Xe(),n=t.cache&&Date.now(),a=this.preparePayload(e);t.cache&&Hn(a,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?it(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):Oy(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&Oy(this.cacheKey,t.map((({targetId:e})=>e))),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ty extends Hr{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:a=10,seenState:s="unseen"}=e,o=await this.createRequest({seenState:"smart"===s?this.smartFilterState:s,limit:a,token:t});if(null===(n=o.paging)||void 0===n?void 0:n.next)return o;if("smart"!==s)return o;if("seen"===this.smartFilterState)return o;this.smartFilterState="seen";const i=await this.createRequest({seenState:this.smartFilterState,limit:a});return c=i,{categories:(r=o).categories.concat(c.categories),communities:r.communities.concat(c.communities),communityUsers:r.communityUsers.concat(c.communityUsers),files:r.files.concat(c.files),storyTargets:r.storyTargets.concat(c.storyTargets),users:r.users.concat(c.users),paging:c.paging};var r,c}async createRequest(e){const{data:t}=await this.http.get("/api/v5/me/global-story-targets",{params:e});return n=t,a=e.seenState,Object.assign(Object.assign({},n),{storyTargets:n.storyTargets.map((e=>Object.assign(Object.assign({},e),{localFilter:a})))||[]});var n,a}}class Ry extends Zr{constructor(e,t){const n=P.default(e),a=["story-global-feed","collection",n],s=new Ty(e);super(s,n,a,t),this.query=e,this.queryStreamController=new Ay(this.query,this.cacheKey,this.notifyChange.bind(this),s,(e=>{const t=zn(hc(Object.assign(Object.assign({},e),{feeds:[]})),["feeds"]);return Object.assign(Object.assign({},e),t)})),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=s.data,i=st(["storyTarget"]);i&&(null==i?void 0:i.length)>0&&(null==i||i.forEach((({key:e})=>{s.data.includes(e[2])||o.push(e[2])})));let r=o.map((e=>ot(["storyTarget","get",e]))).filter(Boolean).map((e=>el.storyTarget(e.data)));(this.shouldNotify(r)||"event"!==e)&&(r=this.applyFilter(r).filter((({localSortingDate:e})=>!!e)).map((e=>zn(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:r,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n}))}applyFilter(e){if("smart"!==this.query.seenState)return e.filter((({hasUnseen:e})=>"all"===this.query.seenState||("seen"===this.query.seenState&&!e||"unseen"===this.query.seenState&&e))).sort(Ot);const t=e.reduce(((e,t)=>("unseen"===t.localFilter?e.unseen.push(t):"seen"===t.localFilter?e.seen.push(t):e.unknown.push(t),e)),{unseen:[],seen:[],unknown:[]}),n=t.unknown.sort(Ot)||[],a=t.unseen.sort(Ot)||[],s=t.seen.sort(Ot)||[];return n.concat(a,s)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:gy,action:"onCreate"},{fn:oy,action:"onUpdate"},{fn:yy,action:"onDelete"},{fn:py,action:"onCreate"},{fn:iy,action:"onUpdate"},{fn:vy,action:"onDelete"},{fn:fy,action:"onError"}])}}var Py=Object.freeze({__proto__:null,createImageStory:async(e,t,n,a={},s="fit",o=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let i={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:s},syncState:"syncing",referenceId:un(),dataType:"image",items:o,targetType:e,targetId:t,metadata:a};const r=new Date;it(["story-sync-state",t],"syncing"),it(["story-expire",t],new Date(r.setFullYear(r.getFullYear()+1))),ey({payload:i,formData:n},(e=>{Ft("local.story.created",e)}));try{const{data:a}=await kl(n);if(0===a.length)throw new Error("Failed to upload image");const{fileId:s}=a[0];i=Object.assign(Object.assign({},i),{data:Object.assign(Object.assign({},i.data),{fileId:s})}),ny({targetId:t,targetType:e}),ey({payload:i,formData:n},(e=>{Ft("local.story.created",e)}));const o=await ty(i);return o.data?Object.assign(Object.assign({},o),{data:el.story(o.data)}):o}catch(e){throw it(["story-sync-state",t],"error"),ey({payload:Object.assign(Object.assign({},i),{syncState:"error"}),formData:n},(e=>{Ft("local.story.error",e)})),e}},createVideoStory:async(e,t,n,a={},s=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let o={data:{text:"",fileId:void 0,fileData:null},syncState:"syncing",referenceId:un(),dataType:"video",items:s,targetType:e,targetId:t,metadata:a};const i=new Date;it(["story-sync-state",t],"syncing"),it(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),ny({targetId:t,targetType:e}),ey({payload:o,formData:n,isVideo:!0},(e=>{Ft("local.story.created",e)}));try{const{data:e}=await Pl(n,_.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];o=Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{fileId:t,videoFileId:{original:t}})}),ey({payload:o,formData:n,isVideo:!0},(e=>{Ft("local.story.created",e)}));const a=await ty(o);return a.data?Object.assign(Object.assign({},a),{data:el.story(a.data)}):a}catch(e){throw it(["story-sync-state",t],"error"),ey({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n,isVideo:!0},(e=>{Ft("local.story.error",e)})),e}},hardDeleteStory:async e=>await sy(e,!0),softDeleteStory:async e=>await sy(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:a}=Xe(),s=[],o=["story-target","collection",e],i=Date.now();n(`getActiveStoriesByTarget(tmpid: ${i}) > listen`),a||console.log(fe);const r=t=>{var n,a;const s=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",o=(null===(a=e.options)||void 0===a?void 0:a.orderBy)||"desc";return 0===t.length?[]:"createdAt"===s?"asc"===o?t.sort(St):t.sort(At):"asc"===o?t.sort(Tt):t.sort(Rt)},c=e=>{var n;const a=e.data.map((e=>{const t=ay(e);if(null==t?void 0:t.data)return el.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),s=[];if(a.length>0){const e=a.reduce(((e,t)=>{if(!t)return e;const{syncState:n}=t;if(!n)return e;let a=e.get(n);return a||(a=[]),a.push(t),e.set(n,a),e}),new Map);if(e.has("error")){const t=r(e.get("error")||[]);s.push(...t)}if(e.has("syncing")){const t=r(e.get("syncing")||[]);s.push(...t)}if(e.has("synced")){const t=r(e.get("synced")||[]);s.push(...t)}}t({onNextPage:()=>!1,data:s||a,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},d=(t,n,a=!1,s=!1,i=!1)=>{var r;const d=ot(o),l={loading:s,error:i,params:{page:void 0},data:(null==d?void 0:d.data)||[]};if(t)if("onDelete"===n){const e=t.map((({referenceId:e})=>e));l.data=l.data.filter((t=>!e.includes(t)))||[]}else l.data=a?t.map(tt("story")):[...new Set([...l.data,...t.map(tt("story"))])];const u=null===(r=st(["story","get"]))||void 0===r?void 0:r.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>tt("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{l.data.includes(e)||l.data.push(e)})),it(o,l.data),c(l)},l=e=>t=>{d(t,e)};return(t=>{const n=$e(my,e);Qe(n,(({data:e,error:n,loading:a})=>{d(e,"fetch",t,a,n)}))})(!0),s.push(gy(l("onCreate")),oy(l("onUpdate")),yy(l("onDelete")),ry(l("onReactionAdded")),dy(l("onReactionRemoved")),fy(l("onError")),py(l("onCreate")),iy(l("onUpdate")),vy(l("onDelete")),cy(l("onReactionAdded")),ly(l("onReactionRemoved")),(e=>{const t=Xe();return Nt(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=ot(o);if(!t)return;if(0===e.referenceIds.length||0===(null==t?void 0:t.data.length))return;if(!(null==t?void 0:t.data.find((t=>e.referenceIds.includes(t)))))return;const n={loading:!1,error:!1,params:{page:void 0},data:(null==t?void 0:t.data)||[]};c(n)})),(()=>dt(o))),()=>{n(`getActiveStoriesByTarget(tmpid: ${i}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>rc(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:el.story(e.data)})):t(e)}),"storyId",Wm,[by(oy),by(yy),by(ry),by(dy),by(fy),by(iy),by(vy),by(cy),by(ly)]),getTargetById:(e,t)=>rc(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:el.storyTarget(e.data[0])})):t(e)}),"query",(e=>Iy([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:a}=Xe(),s=[],o=["storyTargets","collection",e],i=Date.now();n(`getTargetsByTargetIds(tmpid: ${i}) > listen`),a||console.log(fe);const r=(e,n=!1,a=!1,s=!1)=>{const i=ot(o),r={loading:a,error:s,params:{page:void 0},data:[]};e&&(r.data=n?e.map(tt("storyTarget")):[...new Set([...(null==i?void 0:i.data)||[],...e.map(tt("storyTarget"))])]),it(o,r.data),(e=>{var n;const a=e.data.map((e=>{const t=ot(["storyTarget","get",e]);if(null==t?void 0:t.data)return el.storyTarget(t.data)})).filter(Boolean);t({onNextPage:void 0,data:a,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})})(r)};return(t=>{const n=$e(Iy,e);Qe(n,(({data:e,error:n,loading:a})=>{r(e,t,a,n)}))})(!0),s.push((()=>dt(o))),()=>{n(`getTargetsByTargetIds(tmpid: ${i}) > dispose`),s.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:a,cache:s,userId:o}=Xe();s||console.log(fe);const i=Date.now();a(`getStoriesByTargetIds(tmpid: ${i}) > listen`);const r=new Sy(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{dt(d)})),()=>{a(`getStoriesByTargetIds(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:a,cache:s,userId:o}=Xe();s||console.log(fe);const i=Date.now();a(`getGlobalStoryTarget(tmpid: ${i}) > listen`);const r=new Ry(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{dt(d)})),()=>{a(`getGlobalStoryTarget(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}}});const ky=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),Dy=e=>Object.assign({},e);var Uy=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=Xe(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(ky),a=t.advertisers.map(Dy);return Hn({ads:n,advertisers:a,files:t.files}),it(["ad","setting"],t.settings),{ads:n.map(el.ad),settings:t.settings}}});const jy=async()=>{const e=Xe();e.log("notificationTray/getNotificationTraySeen",{});const{data:t}=await e.http.get("api/v1/notification-tray/tray/seen"),n=e.cache&&Date.now();if(e.cache){const n=["notificationTraySeen","get",e.userId];it(n,{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccuredAt:t.lastTrayOccurredAt})}return{data:{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccurredAt:t.lastTrayOccurredAt,isSeen:t.lastTraySeenAt>t.lastTrayOccurredAt},cachedAt:n}};jy.locally=()=>{var e;const t=Xe();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:a}=null!==(e=ot(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:a}:void 0};const Ey=e=>{const t=Xe(),n=[Nt(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class My extends Hr{async getRequest(e,t){const{limit:n=pe}=e,a=zn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/notification-tray",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class qy extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.notificationTrayItems.map(tt("notificationTrayItem"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(tt("notificationTrayItem"))])]}))}}}const xy=e=>{const t=e.users.map(Sa);return Object.assign(Object.assign({},e),{users:t})};class Ky extends Zr{constructor(e,t){const n=P.default(e),a=["notificationTrayItem","collection",n];super(new My(e),n,a,t),this.query=e,this.queryStreamController=new qy(this.query,this.cacheKey,this.notifyChange.bind(this),xy),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>ot(["notificationTrayItem","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.notificationTray);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Ny=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=jt();return rc(t,e,"userId",jy,[Ey],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&na(e.lastTraySeenAt)>na(e.lastTrayOccurredAt)),{lastTrayOccurredAt:null==e?void 0:e.lastTrayOccurredAt,lastTraySeenAt:null==e?void 0:e.lastTraySeenAt,isSeen:t}}})},getNotificationTrayItems:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getNotificationTrayItems(tmpid: ${o}) > listen`);const i=new Ky(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getNotificationTrayItems(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},markItemsSeen:async e=>{const t=Xe();t.log("notificationTray/markItemsSeen",{});const{data:n}=await t.http.post("api/v1/notification-tray/items/seen",{trayItems:e.map((e=>({id:e.id,lastSeenAt:e.lastSeenAt})))}),a=n.trayItems.map((e=>{var n;const a=null===(n=ot(["notificationTrayItem","get",e.id]))||void 0===n?void 0:n.data;if(!a)return;const s=Object.assign(Object.assign({},a),{lastSeenAt:e.lastSeenAt});if(t.cache){const e=Date.now();it(["notificationTrayItem","get"],s,{cachedAt:e})}return s})).filter(Boolean);Ft("local.notificationTrayItem.updated",{notificationTrayItems:a})},markTraySeen:async e=>{var t;const n=Xe();n.log("notificationTray/markTraySeen",{});const{data:a}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),s=null===(t=ot(["notificationTraySeen","get"]))||void 0===t?void 0:t.data,o={userId:n.userId,lastTraySeenAt:a.lastSeenAt},i=Object.assign(Object.assign({},s),o),r=n.cache&&Date.now();return n.cache&&it(["notificationTraySeen","get",n.userId],i,{cachedAt:r}),Ft("local.notificationTraySeen.updated",o),{data:a,cachedAt:r}},onNotificationTraySeenUpdated:Ey});class Fy extends Hr{async getRequest(e,t){const{limit:n=pe}=e,a=zn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/invitations/me",{params:Object.assign(Object.assign({},a),{options:s})}),i=o.invitations.filter((e=>"community"===e.targetType&&!!e.communityId)).map((e=>e.communityId));return(null==i?void 0:i.length)>0&&await Dh(i),o}}class _y extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.invitations.map(tt("invitation"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(tt("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Uc.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}if(e===Uc.OnLocalInvitationCreated){const e=Xe(),n=t.filter((t=>t.invitedUserId===e.userId));a.data=[...new Set([...n.map((e=>e.invitationId)),...a.data])]}e===Uc.OnLocalInvitationCanceled&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class By extends Zr{constructor(e,t){const n=P.default(e),a=["invitation","collection",n];super(new Fy(e),n,a,t),this.query=e,this.queryStreamController=new _y(this.query,this.cacheKey,this.notifyChange.bind(this),Pc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Mc,action:Uc.OnLocalInvitationCreated},{fn:qc,action:Uc.OnLocalInvitationUpdated},{fn:xc,action:Uc.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>ot(["invitation","get",e]))).filter(ec).map((({data:e})=>kc(e))))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?St:At)();return t=t.sort(n),t}}var $y=Object.freeze({__proto__:null,cancelInvitation:async e=>{var t;const n=Xe();n.log("invitation/cancelInvitation",e);const{data:a}=await n.http.delete(`/api/v1/invitations/${e}`),s=null===(t=ot(["invitation","get",e]))||void 0===t?void 0:t.data;return Wn("invitation",e),s&&Ft("local.invitation.canceled",[s]),a.success},onLocalInvitationCreated:Mc,onLocalInvitationUpdated:qc,onLocalInvitationCanceled:xc,getMyCommunityInvitations:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getMyCommunityInvitations: (tmpid: ${o}) > listen`);const i=new By(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{dt(c)})),()=>{a(`getInvitations (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getInvitations:(e,t)=>{const{_id:n}=Qt();if(!n)throw new Je("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=Xe(),{targetId:s,targetType:o}=e,i=Date.now();a(`observeInvitations(tmpid: ${i}) > listen for ${o}: ${s}`);const r=[],c=n=>{const a=(Array.isArray(n)?n:[n]).filter((({targetId:t,targetType:n})=>t===e.targetId&&n===e.targetType));(e=>{t(e.map(el.invitation))})(a)};return"room"===o&&(r.push(rp(c)),r.push(dp(c)),r.push(lp(c)),r.push(up(c))),()=>{a(`getInvitations(tmpid: ${i}) > dispose for ${o}: ${s}`),r.forEach((e=>e()))}}});const Ly=e=>{const t=Xe();return Nt(t,"live_reaction/onLiveReactionCreated","liveReaction.created",(n=>{if(n.reactions.length>0){const a=n.reactions.filter((({userId:e})=>e!==t.userId));e(a)}}))};var Qy=Object.freeze({__proto__:null,createReaction:async({referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:s})=>{const o=Xe();if(o.log("live_reaction/createReaction",{referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:s}),!a&&!s)throw new Je("You have to specify either streamId or roomId",800110,"error");const i=ti(),r={reactionName:n,referencePublicId:e,referenceType:t,roomId:s,streamId:a,occurredAt:(new Date).toISOString()};return i.createLiveReaction(r),Ft("local.liveReaction.created",[Object.assign(Object.assign({},r),{userId:o.userId,referenceId:e})]),!0},onLiveReactionCreated:Ly,getReactions:(e,t)=>{const{_id:n}=jt();if(!n)throw new Je("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=Xe();a(`getReactions(tmpid: ${Date.now()}) > listen`);const s=[],o=n=>{(e=>{t(e)})(n.filter((({referenceId:t})=>t===e)))};return s.push(Ly(o)),s.push((e=>{const t=Xe();return Nt(t,"live_reaction/onLiveReactionCreated","local.liveReaction.created",e)})(o)),()=>{s.forEach((e=>e()))}}});const Vy=async e=>{const t=Xe();t.log("event/getEvent",e);try{const{data:n}=await t.http.get(`/api/v1/events/${e}`),a=Md(n),s=t.cache&&Date.now();return t.cache&&Hn(a,{cachedAt:s}),{data:a.events.find((t=>t.eventId===e)),cachedAt:s}}catch(n){if(De(null==n?void 0:n.code)){const a=Vy.locally(e);if(!a)throw n;const s=Object.assign(Object.assign({},null==a?void 0:a.data),{isDeleted:!0});ct(["event","get",e],s);return{data:s,cachedAt:t.cache&&Date.now()}}throw n}};Vy.locally=e=>{const t=Xe();if(t.log("event/getEvent.locally",e),!t.cache)return;const n=ot(["event","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Jy extends Hr{async getRequest(e,t){const{limit:n=pe}=e,a=zn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/events",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class Hy extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.events.map(tt("event"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(tt("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Nd.OnEventCreated&&(a.data=[...new Set([t.eventId,...a.data])]),e===Nd.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Wy extends Zr{constructor(e,t){const n=P.default(e),a=["event","collection",n];super(new Jy(e),n,a,t),this.query=e,this.queryStreamController=new Hy(this.query,this.cacheKey,this.notifyChange.bind(this),Md),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Bd,action:Nd.OnEventCreated},{fn:$d,action:Nd.OnEventUpdated},{fn:Ld,action:Nd.OnEventDeleted},{fn:Qd,action:Nd.OnEventCreated},{fn:Vd,action:Nd.OnEventUpdated},{fn:Jd,action:Nd.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>ot(["event","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.event);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}class zy extends Hr{async getRequest(e,t){const{limit:n=pe}=e,a=zn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/events/me/rsvps",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class Gy extends zr{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Xe(),a=n.cache&&Date.now();n.cache&&Hn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.events.map(tt("event"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(tt("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=ot(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Nd.OnEventCreated){if(Xe().userId!==t.userId)return;a.data=[...new Set([t.eventId,...a.data])]}e===Nd.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),it(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Yy extends Zr{constructor(e,t){const n=P.default(e),a=["event","collection",n];super(new zy(e),n,a,t),this.query=e,this.queryStreamController=new Gy(this.query,this.cacheKey,this.notifyChange.bind(this),Md),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Bd,action:Nd.OnEventCreated},{fn:$d,action:Nd.OnEventUpdated},{fn:Ld,action:Nd.OnEventDeleted},{fn:Qd,action:Nd.OnEventCreated},{fn:Vd,action:Nd.OnEventUpdated},{fn:Jd,action:Nd.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>ot(["event","get",e]))).filter(ec).map((({data:e})=>e)))&&void 0!==s?s:[]).map(el.event);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}var Xy=Object.freeze({__proto__:null,createEvent:async e=>{const t=Xe();t.log("event/createEvent",e);const{data:n}=await t.http.post("/api/v1/events",e);Ft("local.event.created",n);const a=Md(n),s=t.cache&&Date.now();return t.cache&&Hn(a,{cachedAt:s}),{data:Zd(a.events[0]),cachedAt:s}},updateEvent:async(e,t)=>{const n=Xe();n.log("event/updateEvent",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}`,t);Ft("local.event.updated",a);const s=Md(a),o=n.cache&&Date.now();return n.cache&&Hn(s,{cachedAt:o}),{data:Zd(s.events.find((t=>t.eventId===e))),cachedAt:o}},deleteEvent:async e=>{const t=Xe();t.log("event/deleteEvent",e);const n=await Vy(e);await t.http.delete(`/api/v1/events/${e}`);const a=Object.assign(Object.assign({},n.data),{isDeleted:!0});ct(["event","get",e],a),Ft("local.event.deleted",{users:[],files:[],communities:[],posts:[],rooms:[],events:[a]})},onEventCreated:Bd,onEventUpdated:$d,onEventDeleted:Ld,onLocalEventCreated:Qd,onLocalEventUpdated:Vd,onLocalEventDeleted:Jd,onRSVPCreated:Hd,onRSVPUpdated:Wd,onLocalRSVPCreated:zd,onLocalRSVPUpdated:Gd,getEvent:(e,t)=>rc(e,t,"eventId",Vy,[$d,Ld,Vd,Jd],{callbackDataSelector:e=>e?Zd(e):e}),getEvents:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getEvents: (tmpid: ${o}) > listen`);const i=new Wy(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getEvents (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getMyEvents:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`getMyEvents: (tmpid: ${o}) > listen`);const i=new Yy(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`getMyEvents (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getRSVPs:Xd});const Zy=async e=>{const t=Xe();let n;t.log("product/getProduct",e),ca("product",e);try{n=(await t.http.get(`/api/v1/products/${encodeURIComponent(e)}`)).data}catch(t){throw De(null==t?void 0:t.code)&&Wn("product",e),t}const a=t.cache&&Date.now();t.cache&&Hn(n,{cachedAt:a});const{products:s}=n;return{data:s.find((t=>t.productId===e)),cachedAt:a}};Zy.locally=e=>{const t=Xe();if(t.log("product/getProduct.locally",e),!t.cache)return;const n=ot(["product","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class ev extends Hr{async getRequest(e,t){const{limit:n=pe}=e,a=zn(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/products/search",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class tv extends zr{constructor(e,t,n){super(e,t),this.notifyChange=n}saveToMainDB(e){const t=Xe(),n=t.cache&&Date.now();t.cache&&Hn(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var a,s;if(n)it(this.cacheKey,{data:e.products.map(tt("product"))});else{const t=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];it(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.products.map(tt("product"))])]}))}}}class nv extends Zr{constructor(e,t){const n=P.default(e),a=["products","collection",n];super(new ev(e),n,a,t),this.query=e,this.queryStreamController=new tv(this.query,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=ot(this.cacheKey))||void 0===e?void 0:e.data)||it(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=ot(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>ot(["product","get",e]))).filter(ec).map((({data:e})=>e)).map(el.product))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var av=Object.freeze({__proto__:null,getProduct:(e,t)=>rc(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?el.product(n):n}))}),"productId",Zy,[]),searchProducts:(e,t,n)=>{const{log:a,cache:s}=Xe();s||console.log(fe);const o=Date.now();a(`searchProducts(tmpid: ${o}) > listen`);const i=new nv(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>dt(c))),()=>{a(`searchProducts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});var sv=Object.freeze({__proto__:null,getPool:async(e,t)=>{const n=Xe();if(!e)throw new Je("topicId must not be empty",800110,"error");if(void 0!==t&&(t<1||t>100))throw new Je("limit must be between 1 and 100",800110,"error");const{data:a}=await n.http.get("/api/v5/curated-content/pool",{params:{topicId:e,limit:t}}),{topic:s}=a,o=zn(a,["topic"]),i=Ml(o),r=n.cache&&Date.now();return n.cache&&Hn(i,{cachedAt:r}),{topic:el.curatedContentTopic(s),posts:i.posts.map(el.post)}}});return e.API_REGIONS=cn,e.AdRepository=Uy,e.AmityAttachmentProductTags=class{constructor(){this.map=new Map}get(e){return this.map.get(e)||[]}set(e,t){this.map.set(e,t)}},e.CategoryRepository=_m,e.ChannelRepository=Ph,e.Client=Dr,e.CommentRepository=dg,e.CommunityPostSettingMaps=K,e.CommunityPostSettings=x,e.CommunityRepository=Km,e.ContentFeedType=_,e.CuratedContentRepository=sv,e.DefaultCommunityPostSetting=N,e.EventRepository=Xy,e.FeedRepository=qg,e.FileRepository=Dl,e.FileType=D,e.GET_WATCHER_URLS=Qc,e.InvitationRepository=$y,e.LiveReactionRepository=Qy,e.LiveStreamPlayer=Xp,e.MessageContentType=$,e.MessageRepository=Yu,e.PollRepository=Wp,e.PostContentType=L,e.PostRepository=Dp,e.PostStructureType=Q,e.ProductRepository=av,e.ReactionRepository=bu,e.RoomPresenceRepository=Qp,e.RoomRepository=Ap,e.StoryRepository=Py,e.StreamRepository=Fp,e.SubChannelRepository=sh,e.UserRepository=Tl,e.VERSION=ge,e.VideoResolution=U,e.VideoSize=E,e.VideoTranscodingStatus=j,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:a,userId:s}=Xe();if(!a)return!1;n("cache/api/backupCache",{storageKey:e});const o=Object.fromEntries(Object.entries(a.data).filter((([e,n])=>t(n))));return!!Object.keys(o).length&&(localStorage&&await localStorage.setItem(`${e}#${s}`,JSON.stringify(o)),!0)},e.createQuery=$e,e.createReport=async(e,t,n)=>{const a=Xe();return a.log("report/createReport",{referenceType:e,referenceId:t,options:n}),"user"===e?(async({referenceId:e,options:t})=>!!await nl(e,t))({referenceId:t,options:n}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await Ia(n);Hn(e)}return Ft("message.flagged",n),!!n})({client:a,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await Ml(n);Hn(e)}return Ft("post.flagged",n),!!n})({client:a,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await zc(n);Hn(e)}return Ft("comment.flagged",n),!!n})({client:a,referenceId:t})},e.createUserToken=async(e,t,n)=>{const a=await xn(),s=$n(),o=In(ln("http",t)),{data:i}=await o.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:a,deviceInfo:Object.assign(Object.assign({},s),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:i.accessToken}},e.deleteReport=async(e,t)=>{const n=Xe();return n.log("report/deleteReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await bo(n);Hn(e)}return Ft("user.unflagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await Ia(n);Hn(e)}return Ft("message.unflagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/posts/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await Ml(n);Hn(e)}return Ft("post.unflagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/comments/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await zc(n);Hn(e)}return Ft("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=Xe();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=dt,e.enableCache=(e={},t)=>{const n=Xe();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.exceedsUntilAtBoundary=Dt,e.filterByChannelMembership=mt,e.filterByCommunityMembership=pt,e.filterByFeedType=gt,e.filterByPostDataTypes=yt,e.filterByPropEquality=lt,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=ht,e.filterBySearchTerm=vt,e.filterByStringComparePartially=ut,e.filterByUntilAt=(e,t,n)=>{const a=new Date(t).valueOf();return"firstCreated"===n?e.filter((e=>new Date(e.createdAt).valueOf()<a)):e.filter((e=>new Date(e.createdAt).valueOf()>a))},e.filterCommentsByBlockUsers=It,e.filterPostsByBlockUsers=bt,e.getBlockUsersId=ft,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=jt();return`${Ht(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>Jt(t,n),e.getLiveReactionTopic=e=>`${e.path}/liveReaction`,e.getLiveStreamTopic=tn,e.getMarkedMessageTopic=Gt,e.getMarkerUserFeedTopic=()=>{const e=jt();return`${Ht(e)}/marker/user/${e._id}`},e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=Wt,e.getMyFollowingsTopic=zt,e.getNetworkId=Ht,e.getNetworkTopic=Yt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=jl,e.getRoomStreamerTopic=e=>{const t=Qt();return`${Ht(t)}/room/${e.roomId}/streamer`},e.getRoomWatcherTopic=e=>{const t=Qt();return`${Ht(t)}/room/${e._id}`},e.getSmartFeedChannelTopic=Xt,e.getSmartFeedMessageTopic=en,e.getSmartFeedSubChannelTopic=Zt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const a=jt();return`${Ht(a)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=({path:t},n=e.SubscriptionLevels.USER)=>Jt(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),e.isAfterBefore=je,e.isAfterBeforeRaw=Ee,e.isCachable=_e,e.isFetcher=Ke,e.isFresh=Be,e.isLocal=e=>_e(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=Ne,e.isOffline=Fe,e.isPaged=Me,e.isReportedByMe=async(e,t)=>{const n=Xe();return n.log("report/isReportedByMe",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/users/${t}/isflagbyme`),{result:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`),{result:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/posts/${t}/isflagbyme`),{result:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/comments/${t}/isflagbyme`),{result:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=Ue,e.mergeInCache=rt,e.notificationTray=Ny,e.onChannelMarkerFetched=Cr,e.onFeedMarkerFetched=e=>{const t=Xe();return Nt(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=Xe();return Nt(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Hn(t),e(t.feedMarkers[0])}))},e.onMessageMarked=Tr,e.onMessageMarkerFetched=Ar,e.onSubChannelMarkerFetched=wr,e.onSubChannelMarkerUpdated=Sr,e.onUserMarkerFetched=Or,e.onUserMarkerFetchedLegacy=e=>{const t=Xe();return Nt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=ot,e.pushToCache=it,e.queryCache=st,e.queryOptions=Le,e.queryRoles=Ul,e.restoreCache=async(e="amitySdk")=>{var t;const n=Xe();if(!n.cache)return!1;n.log("cache/api/restoreCache",{storageKey:e});const a=localStorage&&null!==(t=await localStorage.getItem(`${e}#${n.userId}`))&&void 0!==t?t:"{}";let s={};try{s=JSON.parse(a)}catch(e){}return n.cache.data=Object.assign(Object.assign({},s),n.cache.data),!0},e.runQuery=Qe,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=Ct,e.sortByFirstCreated=St,e.sortByFirstUpdated=Tt,e.sortByLastActivity=Pt,e.sortByLastCreated=At,e.sortByLastUpdated=Rt,e.sortByLocalSortingDate=Ot,e.sortByName=wt,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=nn,e.toPage=xe,e.toPageRaw=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return Ee(n)?n:void 0},e.toToken=qe,e.upsertInCache=ct,e.validateUntilAt=kt,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:a}=Xe();return!!n&&(t("cache/api/wipeCache",{storageKey:e}),n.data={},localStorage&&await localStorage.setItem(`${e}#${a}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({},jsBase64,mitt,debug,axios,HttpAgent,uuid$1,mqtt,uaParserJs,AsyncStorage,jwtDecode,reactNative,hash,Hls);