@amityco/ts-sdk 7.4.0 → 7.4.1-18d364a3.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 (303) hide show
  1. package/.env +26 -26
  2. package/dist/@types/core/events.d.ts +7 -0
  3. package/dist/@types/core/events.d.ts.map +1 -1
  4. package/dist/@types/core/model.d.ts +5 -1
  5. package/dist/@types/core/model.d.ts.map +1 -1
  6. package/dist/@types/core/payload.d.ts +38 -5
  7. package/dist/@types/core/payload.d.ts.map +1 -1
  8. package/dist/@types/domains/client.d.ts +10 -0
  9. package/dist/@types/domains/client.d.ts.map +1 -1
  10. package/dist/@types/domains/community.d.ts +37 -1
  11. package/dist/@types/domains/community.d.ts.map +1 -1
  12. package/dist/@types/domains/invitation.d.ts +88 -0
  13. package/dist/@types/domains/invitation.d.ts.map +1 -0
  14. package/dist/@types/domains/joinRequest.d.ts +53 -0
  15. package/dist/@types/domains/joinRequest.d.ts.map +1 -0
  16. package/dist/@types/domains/notification.d.ts +4 -2
  17. package/dist/@types/domains/notification.d.ts.map +1 -1
  18. package/dist/@types/index.d.ts +3 -0
  19. package/dist/@types/index.d.ts.map +1 -1
  20. package/dist/communityRepository/api/createCommunity.d.ts +2 -2
  21. package/dist/communityRepository/api/createCommunity.d.ts.map +1 -1
  22. package/dist/communityRepository/api/getCommunities.d.ts +1 -1
  23. package/dist/communityRepository/api/getCommunities.d.ts.map +1 -1
  24. package/dist/communityRepository/api/getCommunity.d.ts +1 -1
  25. package/dist/communityRepository/api/getCommunity.d.ts.map +1 -1
  26. package/dist/communityRepository/api/getRecommendedCommunities.d.ts +3 -1
  27. package/dist/communityRepository/api/getRecommendedCommunities.d.ts.map +1 -1
  28. package/dist/communityRepository/api/getTrendingCommunities.d.ts +3 -1
  29. package/dist/communityRepository/api/getTrendingCommunities.d.ts.map +1 -1
  30. package/dist/communityRepository/api/joinCommunity.d.ts +3 -0
  31. package/dist/communityRepository/api/joinCommunity.d.ts.map +1 -1
  32. package/dist/communityRepository/api/queryCommunities.d.ts.map +1 -1
  33. package/dist/communityRepository/api/updateCommunity.d.ts +2 -2
  34. package/dist/communityRepository/api/updateCommunity.d.ts.map +1 -1
  35. package/dist/communityRepository/communityMembership/events/onCommunityJoined.d.ts +1 -1
  36. package/dist/communityRepository/communityMembership/events/onCommunityJoined.d.ts.map +1 -1
  37. package/dist/communityRepository/communityMembership/events/onCommunityLeft.d.ts +1 -1
  38. package/dist/communityRepository/communityMembership/events/onCommunityLeft.d.ts.map +1 -1
  39. package/dist/communityRepository/communityMembership/events/onCommunityUserAdded.d.ts +1 -1
  40. package/dist/communityRepository/communityMembership/events/onCommunityUserAdded.d.ts.map +1 -1
  41. package/dist/communityRepository/communityMembership/events/onCommunityUserBanned.d.ts +1 -1
  42. package/dist/communityRepository/communityMembership/events/onCommunityUserBanned.d.ts.map +1 -1
  43. package/dist/communityRepository/communityMembership/events/onCommunityUserChanged.d.ts +1 -1
  44. package/dist/communityRepository/communityMembership/events/onCommunityUserChanged.d.ts.map +1 -1
  45. package/dist/communityRepository/communityMembership/events/onCommunityUserRemoved.d.ts +1 -1
  46. package/dist/communityRepository/communityMembership/events/onCommunityUserRemoved.d.ts.map +1 -1
  47. package/dist/communityRepository/communityMembership/events/onCommunityUserRoleAdded.d.ts +1 -1
  48. package/dist/communityRepository/communityMembership/events/onCommunityUserRoleAdded.d.ts.map +1 -1
  49. package/dist/communityRepository/communityMembership/events/onCommunityUserRoleRemoved.d.ts +1 -1
  50. package/dist/communityRepository/communityMembership/events/onCommunityUserRoleRemoved.d.ts.map +1 -1
  51. package/dist/communityRepository/communityMembership/events/onCommunityUserUnbanned.d.ts +1 -1
  52. package/dist/communityRepository/communityMembership/events/onCommunityUserUnbanned.d.ts.map +1 -1
  53. package/dist/communityRepository/communityMembership/events/onLocalCommunityJoined.d.ts +1 -1
  54. package/dist/communityRepository/communityMembership/events/onLocalCommunityJoined.d.ts.map +1 -1
  55. package/dist/communityRepository/communityMembership/events/onLocalCommunityLeft.d.ts +1 -1
  56. package/dist/communityRepository/communityMembership/events/onLocalCommunityLeft.d.ts.map +1 -1
  57. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserAdded.d.ts +1 -1
  58. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserAdded.d.ts.map +1 -1
  59. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserRemoved.d.ts +1 -1
  60. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserRemoved.d.ts.map +1 -1
  61. package/dist/communityRepository/communityMembership/events/onUserDeleted.d.ts +1 -1
  62. package/dist/communityRepository/communityMembership/events/onUserDeleted.d.ts.map +1 -1
  63. package/dist/communityRepository/communityMembership/events/utils.d.ts +2 -2
  64. package/dist/communityRepository/communityMembership/events/utils.d.ts.map +1 -1
  65. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts +2 -2
  66. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts.map +1 -1
  67. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.d.ts +2 -2
  68. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.d.ts.map +1 -1
  69. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleAdded.d.ts +1 -1
  70. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleAdded.d.ts.map +1 -1
  71. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleRemoved.d.ts +1 -1
  72. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleRemoved.d.ts.map +1 -1
  73. package/dist/communityRepository/events/onCommunityCreated.d.ts +1 -1
  74. package/dist/communityRepository/events/onCommunityCreated.d.ts.map +1 -1
  75. package/dist/communityRepository/events/onCommunityDeleted.d.ts +1 -1
  76. package/dist/communityRepository/events/onCommunityDeleted.d.ts.map +1 -1
  77. package/dist/communityRepository/events/onCommunityUpdated.d.ts +1 -1
  78. package/dist/communityRepository/events/onCommunityUpdated.d.ts.map +1 -1
  79. package/dist/communityRepository/events/utils.d.ts +1 -1
  80. package/dist/communityRepository/events/utils.d.ts.map +1 -1
  81. package/dist/communityRepository/internalAPI/getMyJoinRequest.d.ts +16 -0
  82. package/dist/communityRepository/internalAPI/getMyJoinRequest.d.ts.map +1 -0
  83. package/dist/communityRepository/internalAPI/joinCommunity.d.ts +16 -0
  84. package/dist/communityRepository/internalAPI/joinCommunity.d.ts.map +1 -0
  85. package/dist/communityRepository/joinRequest/events/index.d.ts +4 -0
  86. package/dist/communityRepository/joinRequest/events/index.d.ts.map +1 -0
  87. package/dist/communityRepository/joinRequest/events/onJoinRequestCreated.d.ts +17 -0
  88. package/dist/communityRepository/joinRequest/events/onJoinRequestCreated.d.ts.map +1 -0
  89. package/dist/communityRepository/joinRequest/events/onJoinRequestDeleted.d.ts +17 -0
  90. package/dist/communityRepository/joinRequest/events/onJoinRequestDeleted.d.ts.map +1 -0
  91. package/dist/communityRepository/joinRequest/events/onJoinRequestUpdated.d.ts +17 -0
  92. package/dist/communityRepository/joinRequest/events/onJoinRequestUpdated.d.ts.map +1 -0
  93. package/dist/communityRepository/joinRequest/internalAPI/approveJoinRequest.d.ts +16 -0
  94. package/dist/communityRepository/joinRequest/internalAPI/approveJoinRequest.d.ts.map +1 -0
  95. package/dist/communityRepository/joinRequest/internalAPI/cancelJoinRequest.d.ts +16 -0
  96. package/dist/communityRepository/joinRequest/internalAPI/cancelJoinRequest.d.ts.map +1 -0
  97. package/dist/communityRepository/joinRequest/internalAPI/rejectJoinRequest.d.ts +16 -0
  98. package/dist/communityRepository/joinRequest/internalAPI/rejectJoinRequest.d.ts.map +1 -0
  99. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts +2 -2
  100. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts.map +1 -1
  101. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsLiveCollectionController.d.ts +14 -0
  102. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsLiveCollectionController.d.ts.map +1 -0
  103. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsPaginationController.d.ts +9 -0
  104. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsPaginationController.d.ts.map +1 -0
  105. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsQueryStreamController.d.ts +15 -0
  106. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsQueryStreamController.d.ts.map +1 -0
  107. package/dist/communityRepository/observers/getJoinRequests/enum.d.ts +6 -0
  108. package/dist/communityRepository/observers/getJoinRequests/enum.d.ts.map +1 -0
  109. package/dist/communityRepository/observers/getJoinRequests.d.ts +12 -0
  110. package/dist/communityRepository/observers/getJoinRequests.d.ts.map +1 -0
  111. package/dist/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesLiveCollectionController.d.ts.map +1 -1
  112. package/dist/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesQueryStreamController.d.ts +2 -2
  113. package/dist/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesQueryStreamController.d.ts.map +1 -1
  114. package/dist/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesLiveCollectionController.d.ts.map +1 -1
  115. package/dist/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesQueryStreamController.d.ts +2 -2
  116. package/dist/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesQueryStreamController.d.ts.map +1 -1
  117. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts.map +1 -1
  118. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts +2 -2
  119. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts.map +1 -1
  120. package/dist/communityRepository/observers/semanticSearch/SemanticSearchCommunityQueryStreamController.d.ts +2 -2
  121. package/dist/communityRepository/observers/semanticSearch/SemanticSearchCommunityQueryStreamController.d.ts.map +1 -1
  122. package/dist/communityRepository/utils/communityWithMembership.d.ts +1 -1
  123. package/dist/communityRepository/utils/communityWithMembership.d.ts.map +1 -1
  124. package/dist/communityRepository/utils/payload.d.ts +2 -1
  125. package/dist/communityRepository/utils/payload.d.ts.map +1 -1
  126. package/dist/core/events.d.ts +3 -3
  127. package/dist/core/events.d.ts.map +1 -1
  128. package/dist/core/model/idResolvers.d.ts.map +1 -1
  129. package/dist/core/model/index.d.ts.map +1 -1
  130. package/dist/index.cjs.js +2679 -1419
  131. package/dist/index.d.ts +1 -0
  132. package/dist/index.d.ts.map +1 -1
  133. package/dist/index.esm.js +2937 -1678
  134. package/dist/index.umd.js +4 -4
  135. package/dist/invitationRepository/events/index.d.ts +4 -0
  136. package/dist/invitationRepository/events/index.d.ts.map +1 -0
  137. package/dist/invitationRepository/events/onLocalInvitationCreated.d.ts +17 -0
  138. package/dist/invitationRepository/events/onLocalInvitationCreated.d.ts.map +1 -0
  139. package/dist/invitationRepository/events/onLocalInvitationDeleted.d.ts +17 -0
  140. package/dist/invitationRepository/events/onLocalInvitationDeleted.d.ts.map +1 -0
  141. package/dist/invitationRepository/events/onLocalInvitationUpdated.d.ts +17 -0
  142. package/dist/invitationRepository/events/onLocalInvitationUpdated.d.ts.map +1 -0
  143. package/dist/invitationRepository/index.d.ts +3 -0
  144. package/dist/invitationRepository/index.d.ts.map +1 -0
  145. package/dist/invitationRepository/internalApi/acceptInvitation.d.ts +16 -0
  146. package/dist/invitationRepository/internalApi/acceptInvitation.d.ts.map +1 -0
  147. package/dist/invitationRepository/internalApi/cancelInvitation.d.ts +16 -0
  148. package/dist/invitationRepository/internalApi/cancelInvitation.d.ts.map +1 -0
  149. package/dist/invitationRepository/internalApi/createInvitations.d.ts +21 -0
  150. package/dist/invitationRepository/internalApi/createInvitations.d.ts.map +1 -0
  151. package/dist/invitationRepository/internalApi/getInvitation.d.ts +17 -0
  152. package/dist/invitationRepository/internalApi/getInvitation.d.ts.map +1 -0
  153. package/dist/invitationRepository/internalApi/index.d.ts +5 -0
  154. package/dist/invitationRepository/internalApi/index.d.ts.map +1 -0
  155. package/dist/invitationRepository/internalApi/rejectInvitation.d.ts +16 -0
  156. package/dist/invitationRepository/internalApi/rejectInvitation.d.ts.map +1 -0
  157. package/dist/invitationRepository/observers/getInvitations/InvitationsLiveCollectionController.d.ts +14 -0
  158. package/dist/invitationRepository/observers/getInvitations/InvitationsLiveCollectionController.d.ts.map +1 -0
  159. package/dist/invitationRepository/observers/getInvitations/InvitationsPaginationController.d.ts +5 -0
  160. package/dist/invitationRepository/observers/getInvitations/InvitationsPaginationController.d.ts.map +1 -0
  161. package/dist/invitationRepository/observers/getInvitations/InvitationsQueryStreamController.d.ts +15 -0
  162. package/dist/invitationRepository/observers/getInvitations/InvitationsQueryStreamController.d.ts.map +1 -0
  163. package/dist/invitationRepository/observers/getInvitations/enums.d.ts +6 -0
  164. package/dist/invitationRepository/observers/getInvitations/enums.d.ts.map +1 -0
  165. package/dist/invitationRepository/observers/getInvitations.d.ts +12 -0
  166. package/dist/invitationRepository/observers/getInvitations.d.ts.map +1 -0
  167. package/dist/invitationRepository/observers/getMyCommunityInvitations.d.ts +12 -0
  168. package/dist/invitationRepository/observers/getMyCommunityInvitations.d.ts.map +1 -0
  169. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsLiveCollectionController.d.ts +14 -0
  170. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsLiveCollectionController.d.ts.map +1 -0
  171. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsPaginationController.d.ts +5 -0
  172. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsPaginationController.d.ts.map +1 -0
  173. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsQueryStreamController.d.ts +15 -0
  174. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsQueryStreamController.d.ts.map +1 -0
  175. package/dist/invitationRepository/observers/index.d.ts +2 -0
  176. package/dist/invitationRepository/observers/index.d.ts.map +1 -0
  177. package/dist/invitationRepository/utils/convertRawInvitationToInternalInvitation.d.ts +2 -0
  178. package/dist/invitationRepository/utils/convertRawInvitationToInternalInvitation.d.ts.map +1 -0
  179. package/dist/invitationRepository/utils/index.d.ts +2 -0
  180. package/dist/invitationRepository/utils/index.d.ts.map +1 -0
  181. package/dist/invitationRepository/utils/prepareInvitationPayload.d.ts +2 -0
  182. package/dist/invitationRepository/utils/prepareInvitationPayload.d.ts.map +1 -0
  183. package/dist/invitationRepository/utils/prepareMyInvitationsPayload.d.ts +2 -0
  184. package/dist/invitationRepository/utils/prepareMyInvitationsPayload.d.ts.map +1 -0
  185. package/dist/messageRepository/api/flagMessage.d.ts +3 -2
  186. package/dist/messageRepository/api/flagMessage.d.ts.map +1 -1
  187. package/dist/postRepository/observers/getGlobalPinnedPosts/GlobalPinnedPostQueryStreamController.d.ts.map +1 -1
  188. package/dist/postRepository/observers/getPinnedPosts/PinnedPostQueryStreamController.d.ts.map +1 -1
  189. package/dist/subChannelRepository/utils/prepareSubChannelPayload.d.ts.map +1 -1
  190. package/dist/utils/linkedObject/communityLinkedObject.d.ts +2 -0
  191. package/dist/utils/linkedObject/communityLinkedObject.d.ts.map +1 -0
  192. package/dist/utils/linkedObject/index.d.ts +3 -0
  193. package/dist/utils/linkedObject/index.d.ts.map +1 -1
  194. package/dist/utils/linkedObject/invitationLinkedObject.d.ts +2 -0
  195. package/dist/utils/linkedObject/invitationLinkedObject.d.ts.map +1 -0
  196. package/dist/utils/linkedObject/joinRequestLinkedObject.d.ts +2 -0
  197. package/dist/utils/linkedObject/joinRequestLinkedObject.d.ts.map +1 -0
  198. package/dist/utils/tests/dummy/comment.d.ts +1 -1
  199. package/dist/utils/tests/dummy/post.d.ts +3 -3
  200. package/package.json +1 -1
  201. package/src/@types/core/events.ts +11 -1
  202. package/src/@types/core/model.ts +8 -1
  203. package/src/@types/core/payload.ts +48 -5
  204. package/src/@types/domains/client.ts +12 -0
  205. package/src/@types/domains/community.ts +56 -1
  206. package/src/@types/domains/invitation.ts +116 -0
  207. package/src/@types/domains/joinRequest.ts +66 -0
  208. package/src/@types/domains/notification.ts +2 -0
  209. package/src/@types/index.ts +3 -0
  210. package/src/communityRepository/api/createCommunity.ts +5 -2
  211. package/src/communityRepository/api/getCommunities.ts +7 -2
  212. package/src/communityRepository/api/getCommunity.ts +13 -2
  213. package/src/communityRepository/api/getRecommendedCommunities.ts +11 -4
  214. package/src/communityRepository/api/getTrendingCommunities.ts +11 -4
  215. package/src/communityRepository/api/joinCommunity.ts +4 -1
  216. package/src/communityRepository/api/queryCommunities.ts +6 -1
  217. package/src/communityRepository/api/updateCommunity.ts +13 -3
  218. package/src/communityRepository/communityMembership/events/onCommunityJoined.ts +1 -1
  219. package/src/communityRepository/communityMembership/events/onCommunityLeft.ts +1 -1
  220. package/src/communityRepository/communityMembership/events/onCommunityUserAdded.ts +1 -1
  221. package/src/communityRepository/communityMembership/events/onCommunityUserBanned.ts +1 -1
  222. package/src/communityRepository/communityMembership/events/onCommunityUserChanged.ts +1 -1
  223. package/src/communityRepository/communityMembership/events/onCommunityUserRemoved.ts +1 -1
  224. package/src/communityRepository/communityMembership/events/onCommunityUserRoleAdded.ts +1 -1
  225. package/src/communityRepository/communityMembership/events/onCommunityUserRoleRemoved.ts +1 -1
  226. package/src/communityRepository/communityMembership/events/onCommunityUserUnbanned.ts +1 -1
  227. package/src/communityRepository/communityMembership/events/onLocalCommunityJoined.ts +1 -1
  228. package/src/communityRepository/communityMembership/events/onLocalCommunityLeft.ts +1 -1
  229. package/src/communityRepository/communityMembership/events/onLocalCommunityUserAdded.ts +1 -1
  230. package/src/communityRepository/communityMembership/events/onLocalCommunityUserRemoved.ts +1 -1
  231. package/src/communityRepository/communityMembership/events/onUserDeleted.ts +3 -1
  232. package/src/communityRepository/communityMembership/events/utils.ts +2 -2
  233. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.ts +8 -2
  234. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.ts +8 -2
  235. package/src/communityRepository/communityModeration/events/onLocalCommunityRoleAdded.ts +1 -1
  236. package/src/communityRepository/communityModeration/events/onLocalCommunityRoleRemoved.ts +1 -1
  237. package/src/communityRepository/events/onCommunityCreated.ts +1 -1
  238. package/src/communityRepository/events/onCommunityDeleted.ts +1 -1
  239. package/src/communityRepository/events/onCommunityUpdated.ts +1 -1
  240. package/src/communityRepository/events/utils.ts +1 -1
  241. package/src/communityRepository/internalAPI/getMyJoinRequest.ts +43 -0
  242. package/src/communityRepository/internalAPI/joinCommunity.ts +51 -0
  243. package/src/communityRepository/joinRequest/events/index.ts +3 -0
  244. package/src/communityRepository/joinRequest/events/onJoinRequestCreated.ts +33 -0
  245. package/src/communityRepository/joinRequest/events/onJoinRequestDeleted.ts +33 -0
  246. package/src/communityRepository/joinRequest/events/onJoinRequestUpdated.ts +33 -0
  247. package/src/communityRepository/joinRequest/internalAPI/approveJoinRequest.ts +52 -0
  248. package/src/communityRepository/joinRequest/internalAPI/cancelJoinRequest.ts +46 -0
  249. package/src/communityRepository/joinRequest/internalAPI/rejectJoinRequest.ts +52 -0
  250. package/src/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.ts +2 -2
  251. package/src/communityRepository/observers/getJoinRequests/JoinRequestsLiveCollectionController.ts +126 -0
  252. package/src/communityRepository/observers/getJoinRequests/JoinRequestsPaginationController.ts +26 -0
  253. package/src/communityRepository/observers/getJoinRequests/JoinRequestsQueryStreamController.ts +108 -0
  254. package/src/communityRepository/observers/getJoinRequests/enum.ts +5 -0
  255. package/src/communityRepository/observers/getJoinRequests.ts +44 -0
  256. package/src/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesLiveCollectionController.ts +2 -1
  257. package/src/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesQueryStreamController.ts +2 -2
  258. package/src/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesLiveCollectionController.ts +2 -1
  259. package/src/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesQueryStreamController.ts +2 -2
  260. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.ts +1 -0
  261. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.ts +2 -2
  262. package/src/communityRepository/observers/semanticSearch/SemanticSearchCommunityQueryStreamController.ts +2 -2
  263. package/src/communityRepository/utils/communityWithMembership.ts +9 -5
  264. package/src/communityRepository/utils/payload.ts +28 -2
  265. package/src/core/liveCollection/PaginationController.ts +1 -1
  266. package/src/core/liveCollection/PaginationNoPageController.ts +1 -1
  267. package/src/core/model/idResolvers.ts +3 -0
  268. package/src/core/model/index.ts +3 -0
  269. package/src/index.ts +2 -0
  270. package/src/invitationRepository/events/index.ts +3 -0
  271. package/src/invitationRepository/events/onLocalInvitationCreated.ts +33 -0
  272. package/src/invitationRepository/events/onLocalInvitationDeleted.ts +33 -0
  273. package/src/invitationRepository/events/onLocalInvitationUpdated.ts +33 -0
  274. package/src/invitationRepository/index.ts +2 -0
  275. package/src/invitationRepository/internalApi/acceptInvitation.ts +45 -0
  276. package/src/invitationRepository/internalApi/cancelInvitation.ts +44 -0
  277. package/src/invitationRepository/internalApi/createInvitations.ts +52 -0
  278. package/src/invitationRepository/internalApi/getInvitation.ts +47 -0
  279. package/src/invitationRepository/internalApi/index.ts +4 -0
  280. package/src/invitationRepository/internalApi/rejectInvitation.ts +45 -0
  281. package/src/invitationRepository/observers/getInvitations/InvitationsLiveCollectionController.ts +148 -0
  282. package/src/invitationRepository/observers/getInvitations/InvitationsPaginationController.ts +19 -0
  283. package/src/invitationRepository/observers/getInvitations/InvitationsQueryStreamController.ts +97 -0
  284. package/src/invitationRepository/observers/getInvitations/enums.ts +5 -0
  285. package/src/invitationRepository/observers/getInvitations.ts +44 -0
  286. package/src/invitationRepository/observers/getMyCommunityInvitations.ts +48 -0
  287. package/src/invitationRepository/observers/getMyInvitations/MyInvitationsLiveCollectionController.ts +148 -0
  288. package/src/invitationRepository/observers/getMyInvitations/MyInvitationsPaginationController.ts +22 -0
  289. package/src/invitationRepository/observers/getMyInvitations/MyInvitationsQueryStreamController.ts +105 -0
  290. package/src/invitationRepository/observers/index.ts +1 -0
  291. package/src/invitationRepository/utils/convertRawInvitationToInternalInvitation.ts +8 -0
  292. package/src/invitationRepository/utils/index.ts +1 -0
  293. package/src/invitationRepository/utils/prepareInvitationPayload.ts +12 -0
  294. package/src/invitationRepository/utils/prepareMyInvitationsPayload.ts +12 -0
  295. package/src/messagePreview/utils/getChannelMessagePreviewWithUser.ts +3 -3
  296. package/src/messageRepository/api/flagMessage.ts +19 -2
  297. package/src/postRepository/observers/getGlobalPinnedPosts/GlobalPinnedPostQueryStreamController.ts +7 -1
  298. package/src/postRepository/observers/getPinnedPosts/PinnedPostQueryStreamController.ts +7 -1
  299. package/src/subChannelRepository/utils/prepareSubChannelPayload.ts +4 -0
  300. package/src/utils/linkedObject/communityLinkedObject.ts +58 -0
  301. package/src/utils/linkedObject/index.ts +6 -0
  302. package/src/utils/linkedObject/invitationLinkedObject.ts +44 -0
  303. package/src/utils/linkedObject/joinRequestLinkedObject.ts +31 -0
package/dist/index.cjs.js CHANGED
@@ -23,6 +23,12 @@ var uuid__default = /*#__PURE__*/_interopDefaultLegacy(uuid$1);
23
23
  var hash__default = /*#__PURE__*/_interopDefaultLegacy(hash);
24
24
  var Hls__default = /*#__PURE__*/_interopDefaultLegacy(Hls);
25
25
 
26
+ exports.MembershipAcceptanceTypeEnum = void 0;
27
+ (function (MembershipAcceptanceTypeEnum) {
28
+ MembershipAcceptanceTypeEnum["AUTOMATIC"] = "automatic";
29
+ MembershipAcceptanceTypeEnum["INVITATION"] = "invitation";
30
+ })(exports.MembershipAcceptanceTypeEnum || (exports.MembershipAcceptanceTypeEnum = {}));
31
+
26
32
  const FileType = Object.freeze({
27
33
  FILE: 'file',
28
34
  IMAGE: 'image',
@@ -112,6 +118,37 @@ const PostContentType = Object.freeze({
112
118
  POLL: 'poll',
113
119
  });
114
120
 
121
+ exports.InvitationTypeEnum = void 0;
122
+ (function (InvitationTypeEnum) {
123
+ InvitationTypeEnum["CommunityMemberInvite"] = "communityMemberInvite";
124
+ InvitationTypeEnum["LivestreamInvite"] = "livestreamInvite";
125
+ })(exports.InvitationTypeEnum || (exports.InvitationTypeEnum = {}));
126
+ exports.InvitationStatusEnum = void 0;
127
+ (function (InvitationStatusEnum) {
128
+ InvitationStatusEnum["Pending"] = "pending";
129
+ InvitationStatusEnum["Approved"] = "approved";
130
+ InvitationStatusEnum["Rejected"] = "rejected";
131
+ InvitationStatusEnum["Cancelled"] = "cancelled";
132
+ })(exports.InvitationStatusEnum || (exports.InvitationStatusEnum = {}));
133
+ exports.InvitationSortByEnum = void 0;
134
+ (function (InvitationSortByEnum) {
135
+ InvitationSortByEnum["FirstCreated"] = "firstCreated";
136
+ InvitationSortByEnum["LastCreated"] = "lastCreated";
137
+ })(exports.InvitationSortByEnum || (exports.InvitationSortByEnum = {}));
138
+
139
+ exports.JoinRequestStatusEnum = void 0;
140
+ (function (JoinRequestStatusEnum) {
141
+ JoinRequestStatusEnum["Pending"] = "pending";
142
+ JoinRequestStatusEnum["Approved"] = "approved";
143
+ JoinRequestStatusEnum["Rejected"] = "rejected";
144
+ JoinRequestStatusEnum["Cancelled"] = "cancelled";
145
+ })(exports.JoinRequestStatusEnum || (exports.JoinRequestStatusEnum = {}));
146
+ exports.JoinResultStatusEnum = void 0;
147
+ (function (JoinResultStatusEnum) {
148
+ JoinResultStatusEnum["Success"] = "success";
149
+ JoinResultStatusEnum["Pending"] = "pending";
150
+ })(exports.JoinResultStatusEnum || (exports.JoinResultStatusEnum = {}));
151
+
115
152
  function getVersion() {
116
153
  try {
117
154
  // the string ''v7.4.0-cjs'' should be replaced by actual value by @rollup/plugin-replace
@@ -558,6 +595,8 @@ const idResolvers = {
558
595
  pinTarget: ({ targetId }) => targetId,
559
596
  notificationTrayItem: ({ _id }) => _id,
560
597
  notificationTraySeen: ({ userId }) => userId,
598
+ invitation: ({ _id }) => _id,
599
+ joinRequest: ({ joinRequestId }) => joinRequestId,
561
600
  };
562
601
  /**
563
602
  * Retrieve the id resolver matching a domain name
@@ -610,6 +649,8 @@ const PAYLOAD2MODEL = {
610
649
  pinTargets: 'pinTarget',
611
650
  pins: 'pin',
612
651
  notificationTrayItems: 'notificationTrayItem',
652
+ invitations: 'invitation',
653
+ joinRequests: 'joinRequest',
613
654
  };
614
655
  /** hidden */
615
656
  const isOutdated = (prevData, nextData) => {
@@ -4877,122 +4918,1219 @@ const getChannelMessagePreview = (channelId) => {
4877
4918
  return ((_b = (_a = pullFromCache(['messagePreviewChannel', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : null);
4878
4919
  };
4879
4920
 
4880
- const ANALYTIC_CACHE_KEY = ['analytic', 'normal-priority'];
4881
- const HIGH_PRIORITY_ANALYTIC_CACHE_KEY = ['analytic', 'high-priority'];
4921
+ const userLinkedObject = (user) => {
4922
+ return Object.assign(Object.assign({}, user), { get avatar() {
4923
+ var _a;
4924
+ if (!user.avatarFileId)
4925
+ return undefined;
4926
+ const avatar = (_a = pullFromCache([
4927
+ 'file',
4928
+ 'get',
4929
+ `${user.avatarFileId}`,
4930
+ ])) === null || _a === void 0 ? void 0 : _a.data;
4931
+ return avatar;
4932
+ } });
4933
+ };
4882
4934
 
4883
- const syncEvent = async (events) => {
4884
- const client = getActiveClient();
4885
- const params = {
4886
- activities: events,
4935
+ const getChannelMessagePreviewWithUser = (channel) => {
4936
+ var _a;
4937
+ const messagePreview = channel.messagePreviewId
4938
+ ? getChannelMessagePreview(channel.channelId)
4939
+ : null;
4940
+ const internalUser = (_a = pullFromCache([
4941
+ 'user',
4942
+ 'get',
4943
+ messagePreview === null || messagePreview === void 0 ? void 0 : messagePreview.creatorId,
4944
+ ])) === null || _a === void 0 ? void 0 : _a.data;
4945
+ const messagePreviewWithUser = messagePreview
4946
+ ? Object.assign(Object.assign({}, messagePreview), { user: internalUser ? userLinkedObject(internalUser) : undefined }) : null;
4947
+ return Object.assign(Object.assign({}, channel), { messagePreview: messagePreviewWithUser });
4948
+ };
4949
+
4950
+ const updateChannelMessagePreviewCache = (rawPayload) => {
4951
+ var _a, _b;
4952
+ const withMessageFeedInfo = (messagePreview) => {
4953
+ var _a;
4954
+ const messageFeedInfo = (_a = rawPayload.messageFeedsInfo) === null || _a === void 0 ? void 0 : _a.find(messageFeed => {
4955
+ return messageFeed.messageFeedId === messagePreview.messageFeedId;
4956
+ });
4957
+ const { channelPublicId: channelId, messageFeedId: subChannelId, data, dataType, isDeleted, segment, creatorPublicId: creatorId, createdAt, updatedAt, } = messagePreview;
4958
+ return {
4959
+ channelId,
4960
+ subChannelId,
4961
+ data,
4962
+ dataType,
4963
+ isDeleted,
4964
+ segment,
4965
+ creatorId,
4966
+ createdAt,
4967
+ updatedAt,
4968
+ subChannelName: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.name,
4969
+ messagePreviewId: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.messagePreviewId,
4970
+ subChannelUpdatedAt: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.updatedAt,
4971
+ };
4887
4972
  };
4888
- await client.http.post('/api/v1/analytics/activities', params);
4973
+ const newData = {
4974
+ messagePreviewChannel: (_b = (_a = rawPayload.messagePreviews) === null || _a === void 0 ? void 0 : _a.map(messagePreview => withMessageFeedInfo(messagePreview))) !== null && _b !== void 0 ? _b : [],
4975
+ };
4976
+ ingestInCache(newData);
4889
4977
  };
4890
4978
 
4891
- class AnalyticsEventSyncer {
4892
- constructor() {
4893
- this._timer = undefined;
4894
- this._high_priority_timer = undefined;
4895
- }
4896
- start() {
4897
- this.syncCapturedEvent();
4898
- this._timer = setInterval(() => {
4899
- this.syncCapturedEvent();
4900
- }, 1 * MINUTE);
4901
- this._high_priority_timer = setInterval(() => {
4902
- this.syncHighPriorityCapturedEvent();
4903
- }, 10 * SECOND$1);
4904
- }
4905
- stop() {
4906
- if (this._timer) {
4907
- clearInterval(this._timer);
4908
- this._timer = undefined;
4909
- }
4910
- if (this._high_priority_timer) {
4911
- clearInterval(this._high_priority_timer);
4912
- this._high_priority_timer = undefined;
4913
- }
4914
- }
4915
- async syncCapturedEvent() {
4916
- try {
4917
- // Must query only objects that have same userId with current logged-in user.
4918
- // Query captured event with maximum of 1000
4919
- // Order by latest first
4920
- // e.g., If there are 2000 events we will query 1000-2000 first
4921
- const cache = pullFromCache(ANALYTIC_CACHE_KEY);
4922
- if (!(cache === null || cache === void 0 ? void 0 : cache.data))
4923
- return;
4924
- if (cache.data.event.length === 0)
4925
- return;
4926
- const capturedEvents = cache.data.event;
4927
- await syncEvent(capturedEvents);
4928
- dropFromCache(ANALYTIC_CACHE_KEY);
4929
- }
4930
- catch (error) {
4931
- // stop and destroy all events
4932
- this.stop();
4933
- dropFromCache(ANALYTIC_CACHE_KEY);
4934
- }
4935
- }
4936
- async syncHighPriorityCapturedEvent() {
4937
- try {
4938
- // Must query only objects that have same userId with current logged-in user.
4939
- // Query captured event with maximum of 1000
4940
- // Order by latest first
4941
- // e.g., If there are 2000 events we will query 1000-2000 first
4942
- const cache = pullFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
4943
- if (!(cache === null || cache === void 0 ? void 0 : cache.data))
4944
- return;
4945
- if (cache.data.event.length === 0)
4946
- return;
4947
- const capturedEvents = cache.data.event;
4948
- await syncEvent(capturedEvents);
4949
- dropFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
4950
- }
4951
- catch (error) {
4952
- // stop and destroy all events
4953
- this.stop();
4954
- dropFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
4955
- }
4956
- }
4979
+ const getSubChannelMessagePreview = (subChannelId) => {
4980
+ var _a, _b;
4981
+ return ((_b = (_a = pullFromCache(['messagePreviewSubChannel', 'get', subChannelId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : null);
4982
+ };
4983
+
4984
+ const getSubChannelMessagePreviewWithUser = (subChannel) => {
4985
+ var _a;
4986
+ const messagePreview = subChannel.messagePreviewId
4987
+ ? getSubChannelMessagePreview(subChannel.subChannelId)
4988
+ : null;
4989
+ const messagePreviewWithUser = messagePreview
4990
+ ? Object.assign(Object.assign({}, messagePreview), { user: (_a = pullFromCache(['user', 'get', messagePreview === null || messagePreview === void 0 ? void 0 : messagePreview.creatorId])) === null || _a === void 0 ? void 0 : _a.data }) : null;
4991
+ return Object.assign(Object.assign({}, subChannel), { messagePreview: messagePreviewWithUser });
4992
+ };
4993
+
4994
+ const updateSubChannelMessagePreviewCache = (rawPayload) => {
4995
+ var _a, _b;
4996
+ const withMessageFeedInfo = (messagePreview) => {
4997
+ var _a;
4998
+ const messageFeedInfo = (_a = rawPayload.messageFeeds) === null || _a === void 0 ? void 0 : _a.find(messageFeed => {
4999
+ return messageFeed.messageFeedId === messagePreview.messageFeedId;
5000
+ });
5001
+ const { channelPublicId: channelId, messageFeedId: subChannelId, messageId: messagePreviewId, creatorPublicId: creatorId, data, dataType, isDeleted, segment, createdAt, updatedAt, } = messagePreview;
5002
+ return {
5003
+ messagePreviewId,
5004
+ channelId,
5005
+ subChannelId,
5006
+ data,
5007
+ dataType,
5008
+ isDeleted,
5009
+ segment,
5010
+ creatorId,
5011
+ createdAt,
5012
+ updatedAt,
5013
+ subChannelName: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.name,
5014
+ subChannelUpdatedAt: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.updatedAt,
5015
+ };
5016
+ };
5017
+ const newData = {
5018
+ messagePreviewSubChannel: (_b = (_a = rawPayload.messages) === null || _a === void 0 ? void 0 : _a.map(messagePreview => withMessageFeedInfo(messagePreview))) !== null && _b !== void 0 ? _b : [],
5019
+ };
5020
+ ingestInCache(newData);
5021
+ };
5022
+
5023
+ /**
5024
+ * ```js
5025
+ * import { shallowClone } from '~/utils/shallowClone'
5026
+ * const newObj = shallowClone(obj)
5027
+ * ```
5028
+ *
5029
+ * Clone an object with same prototype and properties
5030
+ *
5031
+ * @param obj the object to clone
5032
+ * @returns new object with same prototype and properties
5033
+ *
5034
+ * @category utility
5035
+ * @private
5036
+ */
5037
+ function shallowClone(source, target) {
5038
+ return Object.create(Object.getPrototypeOf(source), Object.assign(Object.assign({}, Object.getOwnPropertyDescriptors(source)), Object.getOwnPropertyDescriptors(target)));
4957
5039
  }
4958
5040
 
4959
- class AnalyticsEventCapturer {
4960
- constructor() {
4961
- this._expireTime = 5 * MINUTE;
4962
- this._poolLimit = 1000;
4963
- this._recentViewed = {};
4964
- this._recentHighPriorityViewed = {};
4965
- // Story
4966
- this._throttleStoryTimer = undefined;
4967
- this._bufferNewSeenStoryReferenceIds = [];
4968
- }
4969
- isAbleToEnqueue({ uniqueId, expireTime, isHighPriority = false, }) {
4970
- const now = new Date();
4971
- // Get the recent view date (if any)
4972
- const recentViewedDate = isHighPriority
4973
- ? this._recentHighPriorityViewed[uniqueId]
4974
- : this._recentViewed[uniqueId];
4975
- // If this is the first view, always allow it
4976
- if (!recentViewedDate) {
4977
- return true;
4978
- }
4979
- const timeDiff = now.getTime() - recentViewedDate.getTime();
4980
- if (timeDiff < expireTime) {
4981
- // just recently view this post, ignore the event.
4982
- return false;
4983
- }
4984
- return true;
5041
+ function updateSubChannelCache(subChannelId, subChannel, params) {
5042
+ pushToCache(['subChannel', 'get', subChannelId],
5043
+ // eslint-disable-next-line prefer-object-spread
5044
+ shallowClone(subChannel, params));
5045
+ }
5046
+
5047
+ /**
5048
+ * ```js
5049
+ * import { isInTombstone } from '@amityco/ts-sdk'
5050
+ * const user = isInTombstone(["message", "messageId"])
5051
+ * ```
5052
+ *
5053
+ * Checks if the {@link Amity.TombstoneCacheOptions} exists
5054
+ * in cache and it's not expired means it's in tombstone
5055
+ * and we throw an Error
5056
+ *
5057
+ * @param model the model to check
5058
+ * @param modelId the object id to check
5059
+ * @returns the matching cache entry, or undefined.
5060
+ *
5061
+ * @category Cache API
5062
+ */
5063
+ const isInTombstone = (model, modelId) => {
5064
+ const { log, cache } = getActiveClient();
5065
+ const key = [model, CACHE_KEY_TOMBSTONE, modelId];
5066
+ if (!cache)
5067
+ return;
5068
+ log('cache/api/isInTombstone', key);
5069
+ const isInTombstone = pullFromCache(key);
5070
+ const { lifeSpan } = queryOptions('cache_then_server', CACHE_LIFESPAN_TOMBSTONE);
5071
+ if (isInTombstone && isFresh(isInTombstone.data, lifeSpan)) {
5072
+ throw new ASCApiError('Item not found!', 400400 /* Amity.ServerError.ITEM_NOT_FOUND */, "error" /* Amity.ErrorLevel.ERROR */);
4985
5073
  }
4986
- markAs({ uniqueId, contentId, contentType, activityType, metadata, }) {
4987
- if (!this.isAbleToEnqueue({ uniqueId, expireTime: this._expireTime }))
4988
- return;
4989
- const now = new Date();
4990
- const currentData = { event: [] };
4991
- const cache = pullFromCache(ANALYTIC_CACHE_KEY);
4992
- if (cache === null || cache === void 0 ? void 0 : cache.data) {
4993
- currentData.event = cache.data.event;
4994
- }
4995
- // If the pool is full (Max 1000 items), remove the oldest data
5074
+ };
5075
+
5076
+ /**
5077
+ * ```js
5078
+ * import { getMessageMarkers } from '@amityco/ts-sdk'
5079
+ * const messageMarkers = await getMessageMarkers(['sch1', 'sch2'])
5080
+ * ```
5081
+ *
5082
+ * Fetches a list of {@link Amity.MessageMarker} by messageIds
5083
+ *
5084
+ * @param messageIds the feed IDs of the {@link Amity.RawMessage} marker to fetch
5085
+ * @returns A list of {@link Amity.MessageMarker} by messageIds
5086
+ *
5087
+ * @category Channel API
5088
+ * @async
5089
+ * @private
5090
+ */
5091
+ const getMessageMarkers = async (messageIds) => {
5092
+ const client = getActiveClient();
5093
+ client.log('channel/getMessageMarkers', messageIds);
5094
+ const { data: queryPayload } = await client.http.get(`/api/v1/markers/messages`, {
5095
+ params: {
5096
+ messageIds,
5097
+ },
5098
+ });
5099
+ const { contentMarkers, feedMarkers, userMarkers } = queryPayload;
5100
+ const cachedAt = client.cache && Date.now();
5101
+ if (client.cache)
5102
+ ingestInCache({ contentMarkers, feedMarkers, userMarkers }, { cachedAt });
5103
+ fireEvent('local.feedMarker.fetched', { feedMarkers });
5104
+ fireEvent('local.messageMarker.fetched', { contentMarkers });
5105
+ fireEvent('local.userMarker.fetched', { userMarkers });
5106
+ return { data: contentMarkers, cachedAt };
5107
+ };
5108
+
5109
+ const reCalculateChannelUnreadInfo = (channelId) => {
5110
+ var _a;
5111
+ const cacheKeyChannelUnread = ['channelUnreadInfo', 'get', channelId];
5112
+ const cacheChannelUnreadInfo = (_a = pullFromCache(cacheKeyChannelUnread)) === null || _a === void 0 ? void 0 : _a.data;
5113
+ const cacheKeySubChannelUnread = ['subChannelUnreadInfo', 'get'];
5114
+ const cachedSubChannelUnreadInfo = queryCache(cacheKeySubChannelUnread);
5115
+ let channelUnreads = 0;
5116
+ let isMentioned = false;
5117
+ if (cachedSubChannelUnreadInfo && (cachedSubChannelUnreadInfo === null || cachedSubChannelUnreadInfo === void 0 ? void 0 : cachedSubChannelUnreadInfo.length) > 0) {
5118
+ const subChannelUnreadsInfo = cachedSubChannelUnreadInfo === null || cachedSubChannelUnreadInfo === void 0 ? void 0 : cachedSubChannelUnreadInfo.filter(({ data }) => {
5119
+ return data.channelId === channelId && !data.isDeleted;
5120
+ });
5121
+ channelUnreads = subChannelUnreadsInfo
5122
+ .map(({ data }) => data.unreadCount)
5123
+ .reduce((acc, cur) => acc + cur, 0);
5124
+ isMentioned = subChannelUnreadsInfo.some(({ data }) => data.isMentioned);
5125
+ }
5126
+ const channelUnreadInfo = Object.assign(Object.assign({}, (cacheChannelUnreadInfo !== null && cacheChannelUnreadInfo !== void 0 ? cacheChannelUnreadInfo : {
5127
+ channelId,
5128
+ createdAt: new Date().toISOString(),
5129
+ })), { updatedAt: new Date().toISOString(), unreadCount: channelUnreads, isMentioned });
5130
+ pushToCache(cacheKeyChannelUnread, channelUnreadInfo);
5131
+ return channelUnreadInfo;
5132
+ };
5133
+
5134
+ const persistUnreadCountInfo = (payload) => {
5135
+ const { feedMarkers, userFeedMarkers } = payload;
5136
+ // calculate sub channel unread info and channel unread info
5137
+ if (feedMarkers.length > 0 && userFeedMarkers.length > 0) {
5138
+ const channelIds = [];
5139
+ const feedMarkerMap = new Map(feedMarkers.map(fm => [fm.feedId, fm]));
5140
+ userFeedMarkers.forEach(userFeedMarker => {
5141
+ const feedMarker = feedMarkerMap.get(userFeedMarker.feedId);
5142
+ if (!feedMarker)
5143
+ return;
5144
+ if (feedMarker.feedId === userFeedMarker.feedId) {
5145
+ const unreadCount = feedMarker.lastSegment - userFeedMarker.readToSegment;
5146
+ const subChannelUnreadInfo = {
5147
+ subChannelId: feedMarker.feedId,
5148
+ channelId: feedMarker.entityId,
5149
+ readToSegment: userFeedMarker.readToSegment,
5150
+ lastSegment: feedMarker.lastSegment,
5151
+ lastMentionSegment: userFeedMarker.lastMentionSegment,
5152
+ unreadCount: Math.max(0, unreadCount),
5153
+ isMentioned: userFeedMarker.isMentioned,
5154
+ isDeleted: feedMarker.isDeleted,
5155
+ createdAt: userFeedMarker.createdAt,
5156
+ updatedAt: userFeedMarker.updatedAt,
5157
+ };
5158
+ // update sub channel unread info in cache
5159
+ ingestInCache({ subChannelUnreadInfo: [subChannelUnreadInfo] });
5160
+ if (!channelIds.includes(feedMarker.entityId)) {
5161
+ channelIds.push(feedMarker.entityId);
5162
+ }
5163
+ }
5164
+ });
5165
+ // re-calculate channel unread info in cache
5166
+ channelIds.forEach(channelId => {
5167
+ reCalculateChannelUnreadInfo(channelId);
5168
+ });
5169
+ }
5170
+ };
5171
+
5172
+ /**
5173
+ * ```js
5174
+ * import { getSubChannelMarkers } from '@amityco/ts-sdk'
5175
+ * const subChannelMarkers = await getSubChannelMarkers(['sch1', 'sch2'])
5176
+ * ```
5177
+ *
5178
+ * Fetches a paginable list of {@link Amity.SubChannelMarker} objects
5179
+ *
5180
+ * @param messageFeedIds the feed IDs of the {@link Amity.RawSubChannel} marker to fetch
5181
+ * @param page
5182
+ * @returns A page of {@link Amity.SubChannelMarker} objects
5183
+ *
5184
+ * @category Channel API
5185
+ * @async
5186
+ * @private
5187
+ */
5188
+ const getSubChannelMarkers = async (messageFeedIds, page = { limit: 100 }) => {
5189
+ const client = getActiveClient();
5190
+ client.log('channel/getSubChannelMarkers', messageFeedIds, page);
5191
+ const { data: queryPayload } = await client.http.get(`/api/v1/markers/message-feeds`, {
5192
+ params: {
5193
+ messageFeedIds,
5194
+ options: {
5195
+ token: toToken(page, 'skiplimit'),
5196
+ },
5197
+ },
5198
+ });
5199
+ const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
5200
+ const { userEntityMarkers: userEntityMarkersPayload, userFeedMarkers: userFeedMarkersPayload, userMarkers, feedMarkers: feedMarkersPayload, } = payload;
5201
+ // if consistent mode is enabled, persist the unread count info to the cache
5202
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
5203
+ persistUnreadCountInfo({
5204
+ feedMarkers: feedMarkersPayload,
5205
+ userFeedMarkers: userFeedMarkersPayload,
5206
+ });
5207
+ }
5208
+ const userEntityMarkers = convertChannelMarkerResponse(userEntityMarkersPayload);
5209
+ const userFeedMarkers = convertSubChannelMarkerResponse(userFeedMarkersPayload);
5210
+ const cachedAt = client.cache && Date.now();
5211
+ if (client.cache)
5212
+ ingestInCache({ userEntityMarkers, userFeedMarkers, userMarkers }, { cachedAt });
5213
+ fireEvent('local.channelMarker.fetched', { userEntityMarkers });
5214
+ fireEvent('local.subChannelMarker.fetched', { userFeedMarkers });
5215
+ fireEvent('local.userMarker.fetched', { userMarkers });
5216
+ const nextPage = toPage(paging.next);
5217
+ const prevPage = toPage(paging.previous);
5218
+ return { data: userFeedMarkers, cachedAt, prevPage, nextPage };
5219
+ };
5220
+
5221
+ const getUserMarker = async () => {
5222
+ const client = getActiveClient();
5223
+ client.log('channel/getUserMarker');
5224
+ const { data: payload } = await client.http.get(`/api/v1/markers/userMarker`);
5225
+ const { userMarkers } = payload;
5226
+ const cachedAt = client.cache && Date.now();
5227
+ if (client.cache)
5228
+ ingestInCache({ userMarkers }, { cachedAt });
5229
+ fireEvent('local.userMarker.fetched', { userMarkers });
5230
+ const latestUserMarker = userMarkers.reduce((maxUserMarker, userMarker) => {
5231
+ if (maxUserMarker == null ||
5232
+ new Date(maxUserMarker.lastSyncAt).getTime() < new Date(userMarker.lastSyncAt).getTime()) {
5233
+ return userMarker;
5234
+ }
5235
+ return maxUserMarker;
5236
+ }, undefined);
5237
+ return { data: latestUserMarker, cachedAt };
5238
+ };
5239
+
5240
+ /** @hidden */
5241
+ /*
5242
+ * @param message payload from http request without myReactions
5243
+ * add myReactions to http response if the event was a reaction event
5244
+ */
5245
+ const prepareMessagePayloadForCache = (payload, reactors, event) => {
5246
+ const client = getActiveClient();
5247
+ const cached = pullFromCache(['message', 'get', payload.messageId]);
5248
+ // '[]' in cases where the new reaction is the first one
5249
+ const myReactions = (cached === null || cached === void 0 ? void 0 : cached.data.myReactions) || [];
5250
+ // add myReactions to the payload
5251
+ Object.assign(payload, { myReactions });
5252
+ // check if there are any updates to the reactions
5253
+ const latestReaction = reactors[0];
5254
+ const isLatestReactionMine = latestReaction && latestReaction.userId === client.userId;
5255
+ if (!isLatestReactionMine) {
5256
+ return;
5257
+ }
5258
+ // new reaction added
5259
+ if (event === 'message.reactionAdded' && !myReactions.includes(latestReaction.reactionName)) {
5260
+ Object.assign(payload, {
5261
+ myReactions: [...myReactions, latestReaction.reactionName],
5262
+ });
5263
+ }
5264
+ // existing reaction removed
5265
+ if (event === 'message.reactionRemoved' && myReactions.includes(latestReaction.reactionName)) {
5266
+ Object.assign(payload, {
5267
+ myReactions: myReactions.filter(x => x !== latestReaction.reactionName),
5268
+ });
5269
+ }
5270
+ };
5271
+
5272
+ /*
5273
+ * This is a simple utility that infers the value of isDeleted based on the
5274
+ * value of includeDeleted
5275
+ *
5276
+ * There are two important things to note here:
5277
+ * 1. `includeDeleted` is purely client side query param and not recognized by
5278
+ * the server
5279
+ * 2. The only values we wish to expose with regards to `isDeleted` (the server
5280
+ * param for queries) is false | undefined and want to disallow users to query
5281
+ * for deleted entities
5282
+ *
5283
+ * Although this is a very simple utility, it's only purpose is to keep things
5284
+ * DRY
5285
+ */
5286
+ const inferIsDeleted = (includeDeleted) => includeDeleted === true ? undefined : false;
5287
+
5288
+ function getSubChannelIsMentioned(channelId, subChannelId, marker) {
5289
+ var _a, _b;
5290
+ // Look for `unreadCount` in the marker param first
5291
+ if (marker) {
5292
+ return marker.hasMentioned;
5293
+ }
5294
+ const client = getActiveClient();
5295
+ // If consistent mode is enabled, look in the SubChannelUnreadCountInfo cache
5296
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
5297
+ const cachedUnreadCount = (_a = pullFromCache([
5298
+ 'subChannelUnreadInfo',
5299
+ 'get',
5300
+ subChannelId,
5301
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5302
+ if (cachedUnreadCount) {
5303
+ return cachedUnreadCount.isMentioned;
5304
+ }
5305
+ return false;
5306
+ }
5307
+ const key = {
5308
+ entityId: channelId,
5309
+ feedId: subChannelId,
5310
+ userId: getActiveUser()._id,
5311
+ };
5312
+ // If the marker param is not set, look in the cache
5313
+ const cachedMarker = (_b = pullFromCache([
5314
+ 'subChannelMarker',
5315
+ 'get',
5316
+ getResolver('subChannelMarker')(key),
5317
+ ])) === null || _b === void 0 ? void 0 : _b.data;
5318
+ if (cachedMarker) {
5319
+ return cachedMarker.hasMentioned;
5320
+ }
5321
+ // and if not found in cache use default value `false`
5322
+ return false;
5323
+ }
5324
+
5325
+ function getSubChannelUnreadCount(channelId, subChannelId, marker) {
5326
+ var _a, _b;
5327
+ // Look for `unreadCount` in the marker param first
5328
+ if (marker) {
5329
+ return marker.unreadCount;
5330
+ }
5331
+ const client = getActiveClient();
5332
+ // If consistent mode is enabled, look in the SubChannelUnreadCountInfo cache
5333
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
5334
+ const cachedUnreadCount = (_a = pullFromCache([
5335
+ 'subChannelUnreadInfo',
5336
+ 'get',
5337
+ subChannelId,
5338
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5339
+ if (cachedUnreadCount) {
5340
+ return cachedUnreadCount.isDeleted ? 0 : cachedUnreadCount.unreadCount;
5341
+ }
5342
+ return 0;
5343
+ }
5344
+ const key = {
5345
+ entityId: channelId,
5346
+ feedId: subChannelId,
5347
+ userId: getActiveUser()._id,
5348
+ };
5349
+ // If the marker param is not set, look in the cache
5350
+ const cachedMarker = (_b = pullFromCache([
5351
+ 'subChannelMarker',
5352
+ 'get',
5353
+ getResolver('subChannelMarker')(key),
5354
+ ])) === null || _b === void 0 ? void 0 : _b.data;
5355
+ if (cachedMarker) {
5356
+ return cachedMarker.unreadCount;
5357
+ }
5358
+ // and if not found in cache use default value `0`
5359
+ return 0;
5360
+ }
5361
+
5362
+ const MARKER_INCLUDED_SUB_CHANNEL_TYPE$1 = ['broadcast', 'conversation', 'community'];
5363
+ const isUnreadCountSupport$2 = ({ channelType }) => MARKER_INCLUDED_SUB_CHANNEL_TYPE$1.includes(channelType);
5364
+ function convertFromRaw$2(_a) {
5365
+ var { channelId, channelPublicId, channelType, childCount, creatorId, creatorPublicId, lastMessageId, lastMessageTimestamp, messageFeedId, name } = _a, rest = __rest(_a, ["channelId", "channelPublicId", "channelType", "childCount", "creatorId", "creatorPublicId", "lastMessageId", "lastMessageTimestamp", "messageFeedId", "name"]);
5366
+ return Object.assign(Object.assign({ get unreadCount() {
5367
+ return getSubChannelUnreadCount(channelId, messageFeedId);
5368
+ },
5369
+ get hasMentioned() {
5370
+ return getSubChannelIsMentioned(channelId, messageFeedId);
5371
+ },
5372
+ get isMentioned() {
5373
+ return getSubChannelIsMentioned(channelId, messageFeedId);
5374
+ } }, rest), { channelId: channelPublicId, creatorId: creatorPublicId, displayName: name, lastActivity: lastMessageTimestamp, latestMessageId: lastMessageId, messageCount: childCount, subChannelId: messageFeedId, isUnreadCountSupport: isUnreadCountSupport$2({ channelType }) });
5375
+ }
5376
+
5377
+ const mergePayloadWithLocal = (payload) => {
5378
+ var _a, _b, _c;
5379
+ const localMessage = (_b = (_a = queryCache(['message', 'get'])) === null || _a === void 0 ? void 0 : _a.find(({ data }) => data.messageId === payload.messageId)) === null || _b === void 0 ? void 0 : _b.data;
5380
+ if (localMessage) {
5381
+ return Object.assign(Object.assign(Object.assign({}, localMessage), payload), {
5382
+ // NOTE: referenceId is missing in the some payload event. If we have local message data with referenceId, use it instead.
5383
+ referenceId: (_c = localMessage.referenceId) !== null && _c !== void 0 ? _c : payload.referenceId });
5384
+ }
5385
+ return payload;
5386
+ };
5387
+ function convertFromRaw$1(message, reactors, event) {
5388
+ var _a;
5389
+ const mergeMessage = mergePayloadWithLocal(message);
5390
+ const { channelPublicId, childCount, creatorPublicId, mentionedUsers, messageFeedId, myReactions, reactionCount, reactions, referenceId, segment, messageId, creatorId } = mergeMessage, rest = __rest(mergeMessage, ["channelPublicId", "childCount", "creatorPublicId", "mentionedUsers", "messageFeedId", "myReactions", "reactionCount", "reactions", "referenceId", "segment", "messageId", "creatorId"]);
5391
+ let cache;
5392
+ if (referenceId) {
5393
+ cache = pullFromCache(['message', 'get', referenceId]);
5394
+ }
5395
+ if (!cache) {
5396
+ cache = pullFromCache(['message', 'get', messageId]);
5397
+ }
5398
+ const out = Object.assign(Object.assign({}, rest), { messageId, channelId: channelPublicId, channelSegment: segment, childrenNumber: childCount, creatorId: creatorPublicId, creatorPrivateId: message.creatorId, reactions: reactions !== null && reactions !== void 0 ? reactions : {},
5399
+ /*
5400
+ * Previously, myReactions were added only if it was part of the payload.
5401
+ * So empty myReactions were not present. So I've edited the payload to add
5402
+ * a default for those cases.
5403
+ *
5404
+ * Check git blame for previous iteration
5405
+ */
5406
+ myReactions: myReactions || ((_a = cache === null || cache === void 0 ? void 0 : cache.data.myReactions) !== null && _a !== void 0 ? _a : []), reactionsCount: reactionCount, subChannelId: messageFeedId, uniqueId: cache ? cache.data.uniqueId : messageId, referenceId, syncState: "synced" /* Amity.SyncState.Synced */ });
5407
+ if (mentionedUsers) {
5408
+ out.mentionees = mentionedUsers.map(mention => {
5409
+ if (mention.type === 'channel') {
5410
+ return mention;
5411
+ }
5412
+ return { type: 'user', userIds: mention.userPublicIds };
5413
+ });
5414
+ }
5415
+ if (reactors && reactors.length && event) {
5416
+ // mqtt event
5417
+ prepareMessagePayloadForCache(out, reactors, event);
5418
+ }
5419
+ return out;
5420
+ }
5421
+ const preUpdateMessageCache = (rawPayload) => {
5422
+ ingestInCache({
5423
+ messages: rawPayload.messages.map(message => convertFromRaw$1(message, rawPayload.reactions)),
5424
+ });
5425
+ };
5426
+ const DEBOUNCE_TIME = 2000;
5427
+ const currentDebounceMap = {};
5428
+ const prepareMessagePayload = async (payload, event) => {
5429
+ const markerIds = payload.messages.map(({ messageId }) => messageId);
5430
+ if (markerIds.length > 0) {
5431
+ // since the get markers method requires a channel cache to function with the reducer.
5432
+ preUpdateMessageCache(payload);
5433
+ const markerIdsKey = markerIds.join('');
5434
+ if (currentDebounceMap[markerIdsKey]) {
5435
+ clearTimeout(currentDebounceMap[markerIdsKey]);
5436
+ }
5437
+ currentDebounceMap[markerIdsKey] = setTimeout(() => {
5438
+ try {
5439
+ getMessageMarkers(markerIds);
5440
+ }
5441
+ catch (_error) {
5442
+ // do nothing
5443
+ }
5444
+ }, DEBOUNCE_TIME);
5445
+ }
5446
+ const { messageFeeds } = payload, restPayload = __rest(payload, ["messageFeeds"]);
5447
+ // upsert messageFeeds to subchannel cache because messageFeeds from event payload not include messagePreviewId
5448
+ if (messageFeeds && messageFeeds.length > 0) {
5449
+ messageFeeds === null || messageFeeds === void 0 ? void 0 : messageFeeds.forEach(messageFeed => {
5450
+ var _a, _b;
5451
+ const subChannelCache = (_b = (_a = pullFromCache(['subChannel', 'get', messageFeed.messageFeedId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {};
5452
+ // exclude getter properties from existing subChannel cache, update only other properties to existing subChannel cache
5453
+ const _c = convertFromRaw$2(messageFeed), restSubChannel = __rest(_c, ["unreadCount", "isMentioned"]);
5454
+ updateSubChannelCache(messageFeed.messageFeedId, subChannelCache, restSubChannel);
5455
+ });
5456
+ }
5457
+ return Object.assign(Object.assign({}, restPayload), { messages: payload.messages.map(m => convertFromRaw$1(m, payload.reactions, event)) });
5458
+ };
5459
+ function convertParams(_a) {
5460
+ var { subChannelId, mentionees, dataType, data } = _a, rest = __rest(_a, ["subChannelId", "mentionees", "dataType", "data"]);
5461
+ if (dataType === MessageContentType.IMAGE || dataType === MessageContentType.FILE) {
5462
+ return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees, dataType, data: Object.assign({ caption: '' }, data) }, rest);
5463
+ }
5464
+ return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees, dataType, data }, rest);
5465
+ }
5466
+ function convertQueryParams$1(_a) {
5467
+ var { sortBy, subChannelId, includingTags, excludingTags, includeDeleted, aroundMessageId, limit, type } = _a, rest = __rest(_a, ["sortBy", "subChannelId", "includingTags", "excludingTags", "includeDeleted", "aroundMessageId", "limit", "type"]);
5468
+ const out = Object.assign(Object.assign({}, rest), { messageFeedId: subChannelId, isDeleted: inferIsDeleted(includeDeleted), options: {
5469
+ sortBy,
5470
+ limit: limit || COLLECTION_DEFAULT_PAGINATION_LIMIT,
5471
+ around: aroundMessageId,
5472
+ } });
5473
+ if (includingTags) {
5474
+ out.includeTags = includingTags;
5475
+ }
5476
+ if (type) {
5477
+ out.dataType = type;
5478
+ }
5479
+ if (excludingTags) {
5480
+ out.excludeTags = excludingTags;
5481
+ }
5482
+ return out;
5483
+ }
5484
+
5485
+ function convertRawUserToInternalUser(rawUser) {
5486
+ return Object.assign(Object.assign({}, rawUser), { isGlobalBanned: (rawUser === null || rawUser === void 0 ? void 0 : rawUser.isGlobalBan) || false });
5487
+ }
5488
+
5489
+ const MARKER_INCLUDED_SUB_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
5490
+ /**
5491
+ * Filter sub channel by type. Only conversation, community and broadcast type are included.
5492
+ */
5493
+ const isUnreadCountSupport$1 = ({ channelType }) => MARKER_INCLUDED_SUB_CHANNEL_TYPE.includes(channelType);
5494
+ const preUpdateSubChannelCache = (rawPayload) => {
5495
+ ingestInCache({
5496
+ messageFeeds: rawPayload.messageFeeds.map(messageFeed => convertFromRaw$2(messageFeed)),
5497
+ });
5498
+ };
5499
+ const prepareSubChannelPayload = async (rawPayload) => {
5500
+ const markerIds = rawPayload.messageFeeds
5501
+ .filter(isUnreadCountSupport$1)
5502
+ .map(({ messageFeedId }) => messageFeedId);
5503
+ if (markerIds.length > 0) {
5504
+ // since the get markers method requires a channel cache to function with the reducer.
5505
+ preUpdateSubChannelCache(rawPayload);
5506
+ try {
5507
+ await getSubChannelMarkers(markerIds);
5508
+ }
5509
+ catch (e) {
5510
+ // empty block (from the spec, allow marker fetch to fail without having to do anything)
5511
+ }
5512
+ }
5513
+ updateSubChannelMessagePreviewCache(rawPayload);
5514
+ // attach marker to sub channel
5515
+ const messageFeeds = rawPayload.messageFeeds.map(convertFromRaw$2);
5516
+ const messages = rawPayload.messages.map(m => convertFromRaw$1(m));
5517
+ const user = rawPayload.users.map(convertRawUserToInternalUser);
5518
+ return Object.assign(Object.assign({}, rawPayload), { messageFeeds,
5519
+ messages, users: user });
5520
+ };
5521
+ function convertQueryParams(_a) {
5522
+ var { excludeDefaultSubChannel } = _a, rest = __rest(_a, ["excludeDefaultSubChannel"]);
5523
+ const out = Object.assign({}, rest);
5524
+ if (excludeDefaultSubChannel !== undefined) {
5525
+ out.excludeDefaultMessageFeed = excludeDefaultSubChannel;
5526
+ }
5527
+ return out;
5528
+ }
5529
+
5530
+ /**
5531
+ * ```js
5532
+ * import { getSubChannel } from '@amityco/ts-sdk'
5533
+ * const subChannel = await getSubChannel('foobar')
5534
+ * ```
5535
+ *
5536
+ * Fetches a {@link Amity.SubChannel} object
5537
+ *
5538
+ * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
5539
+ * @returns the associated {@link Amity.SubChannel} object
5540
+ *
5541
+ * @category Channel API
5542
+ * @async
5543
+ */
5544
+ const getSubChannel$1 = async (subChannelId) => {
5545
+ const client = getActiveClient();
5546
+ client.log('channel/getSubChannel', subChannelId);
5547
+ isInTombstone('subChannel', subChannelId);
5548
+ try {
5549
+ const response = await client.http.get(`/api/v5/message-feeds/${encodeURIComponent(subChannelId)}`);
5550
+ const data = await prepareSubChannelPayload(response.data);
5551
+ const cachedAt = client.cache && Date.now();
5552
+ if (client.cache)
5553
+ ingestInCache(data, { cachedAt });
5554
+ fireEvent('local.message-feed.fetched', data);
5555
+ return {
5556
+ data: data.messageFeeds[0],
5557
+ cachedAt,
5558
+ };
5559
+ }
5560
+ catch (error) {
5561
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
5562
+ pushToTombstone('subChannel', subChannelId);
5563
+ }
5564
+ throw error;
5565
+ }
5566
+ };
5567
+ /**
5568
+ * ```js
5569
+ * import { getSubChannel } from '@amityco/ts-sdk'
5570
+ * const subChannel = getSubChannel.locally('foobar')
5571
+ * ```
5572
+ *
5573
+ * Fetches a {@link Amity.SubChannel} object from cache
5574
+ *
5575
+ * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
5576
+ * @returns the associated {@link Amity.SubChannel} object
5577
+ *
5578
+ * @category Channel API
5579
+ */
5580
+ getSubChannel$1.locally = (subChannelId) => {
5581
+ const client = getActiveClient();
5582
+ client.log('channel/getSubChannel.locally', subChannelId);
5583
+ if (!client.cache)
5584
+ return;
5585
+ const cached = pullFromCache(['subChannel', 'get', subChannelId]);
5586
+ if (!cached)
5587
+ return;
5588
+ return {
5589
+ data: cached.data,
5590
+ cachedAt: cached.cachedAt,
5591
+ };
5592
+ };
5593
+
5594
+ const convertDateStringToTimestamp = (dateString) => {
5595
+ return new Date(dateString).getTime();
5596
+ };
5597
+
5598
+ const getMessagePreviewSetting$1 = async () => {
5599
+ const client = getActiveClient();
5600
+ return client.getMessagePreviewSetting(false);
5601
+ };
5602
+ const getSubChannelCache = async (subChannelId) => {
5603
+ var _a;
5604
+ let subChannelCache = (_a = pullFromCache(['subChannel', 'get', subChannelId])) === null || _a === void 0 ? void 0 : _a.data;
5605
+ if (!subChannelCache) {
5606
+ subChannelCache = (await getSubChannel$1(subChannelId)).data;
5607
+ }
5608
+ return subChannelCache;
5609
+ };
5610
+ const isLastestMessageOnSubchannel = (message) => {
5611
+ var _a;
5612
+ const cache = (_a = pullFromCache([
5613
+ 'messagePreviewSubChannel',
5614
+ 'get',
5615
+ message.subChannelId,
5616
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5617
+ // The message payload from optimistic created event has no segment, so we check createdAt instead.
5618
+ return (!cache ||
5619
+ cache.segment <= message.channelSegment ||
5620
+ convertDateStringToTimestamp(cache.createdAt) <= convertDateStringToTimestamp(message.createdAt));
5621
+ };
5622
+ const isLastestMessageOnChannel = (message) => {
5623
+ var _a;
5624
+ const cache = (_a = pullFromCache([
5625
+ 'messagePreviewChannel',
5626
+ 'get',
5627
+ message.channelId,
5628
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5629
+ return (!cache ||
5630
+ convertDateStringToTimestamp(cache.createdAt) <= convertDateStringToTimestamp(message.createdAt));
5631
+ };
5632
+ const handleMessageCreatedOnSubChannel = async (message) => {
5633
+ const messagePreviewSetting = await getMessagePreviewSetting$1();
5634
+ const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
5635
+ // 1. get subChannel from cache, if not exist fetch from server
5636
+ const subChannelCache = await getSubChannelCache(subChannelId);
5637
+ // 2. if messagePreviewSetting is NO_MESSAGE_PREVEIW, update only lastActiviy in subChannel cache
5638
+ if (messagePreviewSetting === "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */) {
5639
+ // 2.1 if the message is the latest message, update lastActivity to be createdAt in subChannel cache
5640
+ if (convertDateStringToTimestamp(subChannelCache.lastActivity) <
5641
+ convertDateStringToTimestamp(createdAt))
5642
+ updateSubChannelCache(message.subChannelId, subChannelCache, {
5643
+ lastActivity: createdAt,
5644
+ });
5645
+ return;
5646
+ }
5647
+ // 3. if messagePreviewSetting is `NOT` NO_MESSAGE_PREVEIW, update messagePreviewSubChannel and subChannel cache
5648
+ // 3.1 check if the message is the latest message, if not ignore the message.
5649
+ if (!isLastestMessageOnSubchannel(message))
5650
+ return;
5651
+ // 3.2 if the message is the latest message, update messagePreviewSubChannel and subChannel cache
5652
+ pushToCache(['messagePreviewSubChannel', 'get', message.subChannelId], {
5653
+ channelId,
5654
+ creatorId,
5655
+ messagePreviewId,
5656
+ createdAt,
5657
+ updatedAt,
5658
+ subChannelId,
5659
+ data,
5660
+ dataType,
5661
+ segment,
5662
+ isDeleted,
5663
+ subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt,
5664
+ subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName,
5665
+ });
5666
+ updateSubChannelCache(message.subChannelId, subChannelCache, {
5667
+ lastActivity: createdAt,
5668
+ messagePreviewId,
5669
+ });
5670
+ };
5671
+ const handleMessageUpdatedOnSubChannel = async (message) => {
5672
+ var _a;
5673
+ const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
5674
+ const messagePreviewSubChannelCache = (_a = pullFromCache([
5675
+ 'messagePreviewSubChannel',
5676
+ 'get',
5677
+ message.subChannelId,
5678
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5679
+ // if messagePreviewSubChannel is not exist, ignore the message.
5680
+ if (messagePreviewSubChannelCache &&
5681
+ messagePreviewSubChannelCache.messagePreviewId === message.messageId) {
5682
+ const subChannelCache = await getSubChannelCache(subChannelId);
5683
+ pushToCache(['messagePreviewSubChannel', 'get', message.subChannelId], {
5684
+ channelId,
5685
+ creatorId,
5686
+ messagePreviewId,
5687
+ createdAt,
5688
+ updatedAt,
5689
+ subChannelId,
5690
+ data,
5691
+ dataType,
5692
+ segment,
5693
+ isDeleted,
5694
+ subChannelUpdatedAt: subChannelCache.updatedAt,
5695
+ subChannelName: messagePreviewSubChannelCache.subChannelName,
5696
+ });
5697
+ }
5698
+ };
5699
+ const handleMessageCreated = async (message) => {
5700
+ const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
5701
+ if (isLastestMessageOnChannel(message)) {
5702
+ const subChannelCache = await getSubChannelCache(subChannelId);
5703
+ pushToCache(['messagePreviewChannel', 'get', message.channelId], {
5704
+ channelId,
5705
+ creatorId,
5706
+ messagePreviewId,
5707
+ createdAt,
5708
+ updatedAt,
5709
+ subChannelId,
5710
+ data,
5711
+ dataType,
5712
+ segment,
5713
+ isDeleted,
5714
+ subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt,
5715
+ subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName,
5716
+ });
5717
+ }
5718
+ };
5719
+ const handleMessageUpdated = async (message) => {
5720
+ /**
5721
+ * Channel Case
5722
+ */
5723
+ var _a;
5724
+ const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
5725
+ const messagePreviewChannelCache = (_a = pullFromCache([
5726
+ 'messagePreviewChannel',
5727
+ 'get',
5728
+ message.channelId,
5729
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5730
+ if (messagePreviewChannelCache &&
5731
+ messagePreviewChannelCache.messagePreviewId === message.messageId) {
5732
+ const subChannelCache = await getSubChannelCache(subChannelId);
5733
+ pushToCache(['messagePreviewChannel', 'get', message.channelId], {
5734
+ channelId,
5735
+ creatorId,
5736
+ messagePreviewId,
5737
+ createdAt,
5738
+ updatedAt,
5739
+ subChannelId,
5740
+ data,
5741
+ dataType,
5742
+ segment,
5743
+ isDeleted,
5744
+ subChannelUpdatedAt: subChannelCache.updatedAt,
5745
+ subChannelName: messagePreviewChannelCache.subChannelName,
5746
+ });
5747
+ }
5748
+ };
5749
+ const handleSubChannelUpdated = async (subChannel) => {
5750
+ var _a, _b, _c, _d;
5751
+ const { channelId, subChannelId } = subChannel;
5752
+ /** Channel Case */
5753
+ const messagePreviewChannelCache = (_a = pullFromCache([
5754
+ 'messagePreviewChannel',
5755
+ 'get',
5756
+ channelId,
5757
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5758
+ if ((messagePreviewChannelCache === null || messagePreviewChannelCache === void 0 ? void 0 : messagePreviewChannelCache.subChannelId) === subChannelId) {
5759
+ const subChannelCache = (_b = pullFromCache([
5760
+ 'subChannel',
5761
+ 'get',
5762
+ subChannelId,
5763
+ ])) === null || _b === void 0 ? void 0 : _b.data;
5764
+ pushToCache(['messagePreviewChannel', 'get', channelId], Object.assign(Object.assign({}, messagePreviewChannelCache), { subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName, subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt }));
5765
+ }
5766
+ /** SubChannel Case */
5767
+ const messagePreviewSubChannelCache = (_c = pullFromCache([
5768
+ 'messagePreviewSubChannel',
5769
+ 'get',
5770
+ subChannelId,
5771
+ ])) === null || _c === void 0 ? void 0 : _c.data;
5772
+ if (messagePreviewSubChannelCache &&
5773
+ new Date(messagePreviewSubChannelCache.updatedAt).valueOf() >
5774
+ new Date(subChannel.updatedAt).valueOf()) {
5775
+ const subChannelCache = (_d = pullFromCache([
5776
+ 'subChannel',
5777
+ 'get',
5778
+ subChannelId,
5779
+ ])) === null || _d === void 0 ? void 0 : _d.data;
5780
+ pushToCache(['messagePreviewSubChannel', 'get', subChannelId], Object.assign(Object.assign({}, messagePreviewSubChannelCache), { subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName, subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt }));
5781
+ }
5782
+ };
5783
+
5784
+ const MARKER_INCLUDED_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
5785
+ const isUnreadCountSupport = ({ type }) => MARKER_INCLUDED_CHANNEL_TYPE.includes(type);
5786
+ function convertFromRaw(channel, options = { isMessagePreviewUpdated: true }) {
5787
+ var _a;
5788
+ let { messagePreviewId } = channel;
5789
+ const messagePreviewChannelCache = (_a = pullFromCache([
5790
+ 'messagePreviewChannel',
5791
+ 'get',
5792
+ channel.channelId,
5793
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5794
+ if ((messagePreviewChannelCache === null || messagePreviewChannelCache === void 0 ? void 0 : messagePreviewChannelCache.messagePreviewId) && !options.isMessagePreviewUpdated) {
5795
+ messagePreviewId = messagePreviewChannelCache.messagePreviewId;
5796
+ }
5797
+ return Object.assign(Object.assign({}, channel), { defaultSubChannelId: channel.channelInternalId, isUnreadCountSupport: isUnreadCountSupport(channel), messagePreviewId });
5798
+ }
5799
+ const preUpdateChannelCache = (rawPayload, options = { isMessagePreviewUpdated: true }) => {
5800
+ ingestInCache({
5801
+ channels: rawPayload.channels.map(channel => convertFromRaw(channel, { isMessagePreviewUpdated: options.isMessagePreviewUpdated })),
5802
+ });
5803
+ };
5804
+ const updateChannelUnread = ({ currentUserId, channels, channelUsers, }) => {
5805
+ for (let i = 0; i < channels.length; i += 1) {
5806
+ const cacheKey = ['channelUnread', 'get', channels[i].channelId];
5807
+ const channelUser = channelUsers.find(channelUser => channelUser.channelId === channels[i].channelId && channelUser.userId === currentUserId);
5808
+ let unreadCount = 0;
5809
+ let readToSegment = null;
5810
+ let lastMentionedSegment = null;
5811
+ let isMentioned = false;
5812
+ if (channelUser) {
5813
+ readToSegment = channelUser.readToSegment;
5814
+ lastMentionedSegment = channelUser.lastMentionedSegment;
5815
+ unreadCount = Math.max(channels[i].messageCount - readToSegment, 0);
5816
+ isMentioned = lastMentionedSegment > readToSegment;
5817
+ }
5818
+ const cacheChannelUnread = {
5819
+ channelId: channels[i].channelId,
5820
+ lastSegment: channels[i].messageCount,
5821
+ readToSegment,
5822
+ lastMentionedSegment,
5823
+ unreadCount,
5824
+ isMentioned,
5825
+ isDeleted: channels[i].isDeleted || false,
5826
+ };
5827
+ pushToCache(cacheKey, cacheChannelUnread);
5828
+ }
5829
+ };
5830
+ const prepareChannelPayload = async (rawPayload, options = { isMessagePreviewUpdated: true }) => {
5831
+ const client = getActiveClient();
5832
+ const networkPreviewSetting = await client.getMessagePreviewSetting(false);
5833
+ if (options.isMessagePreviewUpdated &&
5834
+ networkPreviewSetting !== "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */ &&
5835
+ rawPayload.messagePreviews &&
5836
+ rawPayload.messagePreviews.length > 0) {
5837
+ updateChannelMessagePreviewCache(rawPayload);
5838
+ }
5839
+ if (client.useLegacyUnreadCount) {
5840
+ updateChannelUnread({
5841
+ channels: rawPayload.channels,
5842
+ channelUsers: rawPayload.channelUsers,
5843
+ currentUserId: client.userId,
5844
+ });
5845
+ }
5846
+ else {
5847
+ const markerIds = rawPayload.channels
5848
+ // filter channel by type. Only conversation, community and broadcast type are included.
5849
+ .filter(isUnreadCountSupport)
5850
+ .map(({ channelInternalId }) => channelInternalId);
5851
+ if (markerIds.length > 0) {
5852
+ // since the get markers method requires a channel cache to function with the reducer.
5853
+ preUpdateChannelCache(rawPayload, {
5854
+ isMessagePreviewUpdated: options.isMessagePreviewUpdated,
5855
+ });
5856
+ try {
5857
+ await getChannelMarkers(markerIds);
5858
+ }
5859
+ catch (e) {
5860
+ // empty block (from the spec, allow marker fetch to fail without having to do anything)
5861
+ }
5862
+ }
5863
+ }
5864
+ // convert raw channel to internal channel
5865
+ const channels = rawPayload.channels.map(payload => convertFromRaw(payload, { isMessagePreviewUpdated: options.isMessagePreviewUpdated }));
5866
+ // convert raw channel user to membership (add user object)
5867
+ const channelUsers = rawPayload.channelUsers.map(channelUser => {
5868
+ return convertRawMembershipToMembership(channelUser);
5869
+ });
5870
+ const users = rawPayload.users.map(convertRawUserToInternalUser);
5871
+ const restRawPayload = __rest(rawPayload, ["messageFeedsInfo", "messagePreviews"]);
5872
+ return Object.assign(Object.assign({}, restRawPayload), { users,
5873
+ channels,
5874
+ channelUsers });
5875
+ };
5876
+
5877
+ /**
5878
+ * ```js
5879
+ * import { getSubChannelMarkers } from '@amityco/ts-sdk'
5880
+ * const subChannelMarkers = await getSubChannelMarkers(['sch1', 'sch2'])
5881
+ * ```
5882
+ *
5883
+ * Fetches a paginable list of {@link Amity.SubChannelMarker} objects
5884
+ *
5885
+ * @param messageFeedIds the feed IDs of the {@link Amity.RawSubChannel} marker to fetch
5886
+ * @param page
5887
+ * @returns A page of {@link Amity.SubChannelMarker} objects
5888
+ *
5889
+ * @category Channel API
5890
+ * @async
5891
+ * @private
5892
+ */
5893
+ const getUserMessageFeedMakers = async (channelIds) => {
5894
+ const client = getActiveClient();
5895
+ client.log('channel/getUserMessageFeedMakers', channelIds);
5896
+ const { data } = await client.http.get(`/api/v1/markers/user-message-feed`, {
5897
+ params: {
5898
+ channelIds,
5899
+ },
5900
+ });
5901
+ fireEvent('local.userMessageFeedMarker.fetched', { userMessageFeedMarker: data });
5902
+ return data;
5903
+ };
5904
+
5905
+ const prepareUnreadCountInfo = async (rawPayload) => {
5906
+ const client = getActiveClient();
5907
+ // if consistent mode is enabled, persist the unread count info to the cache
5908
+ // Marker service API uses channelInternalId as channelId
5909
+ const queryPayload = await getUserMessageFeedMakers(rawPayload.channels.map(({ channelInternalId }) => channelInternalId));
5910
+ const { feedMarkers, userFeedMarkers } = queryPayload;
5911
+ persistUnreadCountInfo({
5912
+ feedMarkers,
5913
+ userFeedMarkers,
5914
+ });
5915
+ client.log('channel/prepareUnreadCountInfo', rawPayload.channels);
5916
+ };
5917
+
5918
+ const getCachedMarker$2 = (entityId) => {
5919
+ var _a;
5920
+ const key = {
5921
+ entityId,
5922
+ userId: getActiveUser()._id,
5923
+ };
5924
+ return (_a = pullFromCache([
5925
+ 'channelMarker',
5926
+ 'get',
5927
+ getResolver('channelMarker')(key),
5928
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5929
+ };
5930
+ const getUnreadInfoCached$1 = (channelId) => {
5931
+ var _a;
5932
+ return (_a = pullFromCache(['channelUnreadInfo', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
5933
+ };
5934
+ /**
5935
+ * The function use to get value of hasMentioned or isMentioned field.
5936
+ * function will get the value from marker params first, if there is no hasMentioned field, will look in to the cache.
5937
+ *
5938
+ * If consistent mode is enabled, the function will return the value from the channelUnreadCountInfo cache.
5939
+ * If not, the function will return the value from the channelMarker cache.
5940
+ * If not found in the both cache, use `false` as defaul value.
5941
+ */
5942
+ const getChannelIsMentioned = (channel, marker) => {
5943
+ var _a, _b, _c, _d;
5944
+ const client = getActiveClient();
5945
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
5946
+ return (_b = (_a = getUnreadInfoCached$1(channel.channelPublicId)) === null || _a === void 0 ? void 0 : _a.isMentioned) !== null && _b !== void 0 ? _b : false;
5947
+ }
5948
+ return (marker === null || marker === void 0 ? void 0 : marker.hasMentioned) !== undefined
5949
+ ? marker === null || marker === void 0 ? void 0 : marker.hasMentioned
5950
+ : (_d = (_c = getCachedMarker$2(channel.channelPublicId)) === null || _c === void 0 ? void 0 : _c.hasMentioned) !== null && _d !== void 0 ? _d : false;
5951
+ };
5952
+
5953
+ const getCachedMarker$1 = (entityId) => {
5954
+ var _a;
5955
+ const key = {
5956
+ entityId,
5957
+ userId: getActiveUser()._id,
5958
+ };
5959
+ return (_a = pullFromCache([
5960
+ 'channelMarker',
5961
+ 'get',
5962
+ getResolver('channelMarker')(key),
5963
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5964
+ };
5965
+ const getUnreadInfoCached = (channelId) => {
5966
+ var _a;
5967
+ return (_a = pullFromCache(['channelUnreadInfo', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
5968
+ };
5969
+ /**
5970
+ * The function use to get value of unreadCount field.
5971
+ * function will get the value from marker params first, if there is no hasMentioned field, will look in to the cache.
5972
+ *
5973
+ * If consistent mode is enabled, the function will return the value from the channelUnreadCountInfo cache.
5974
+ * If not, the function will return the value from the channelMarker cache.
5975
+ * If not found in the both cache, use `0` as defaul value.
5976
+ */
5977
+ const getSubChannelsUnreadCount = (channel, marker) => {
5978
+ var _a, _b, _c, _d, _e;
5979
+ const client = getActiveClient();
5980
+ if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
5981
+ // Marker service API uses channelInternalId as channelId
5982
+ return (_b = (_a = getUnreadInfoCached(channel.channelInternalId)) === null || _a === void 0 ? void 0 : _a.unreadCount) !== null && _b !== void 0 ? _b : 0;
5983
+ }
5984
+ if (marker === null || marker === void 0 ? void 0 : marker.isDeleted) {
5985
+ // NOTE: This is a temporary solution to handle the channel marker when the user is forced to
5986
+ // leave the channel because currently backend can't handle this, so every time a user is banned
5987
+ // from a channel or the channel is deleted the channel's unread count will reset to zero
5988
+ return 0;
5989
+ }
5990
+ return (_e = (_c = marker === null || marker === void 0 ? void 0 : marker.unreadCount) !== null && _c !== void 0 ? _c : (_d = getCachedMarker$1(channel.channelInternalId)) === null || _d === void 0 ? void 0 : _d.unreadCount) !== null && _e !== void 0 ? _e : 0;
5991
+ };
5992
+
5993
+ const getLegacyChannelUnread = (channelId) => {
5994
+ var _a;
5995
+ return (_a = pullFromCache(['channelUnread', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
5996
+ };
5997
+
5998
+ const constructChannelDynamicValue = (channel) => {
5999
+ const client = getActiveClient();
6000
+ const rest = __rest(channel, ["messageCount"]);
6001
+ return shallowClone(rest, {
6002
+ get unreadCount() {
6003
+ var _a, _b;
6004
+ return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.unreadCount) !== null && _b !== void 0 ? _b : 0;
6005
+ },
6006
+ get subChannelsUnreadCount() {
6007
+ return getSubChannelsUnreadCount(rest);
6008
+ },
6009
+ get isMentioned() {
6010
+ var _a, _b;
6011
+ if (client.useLegacyUnreadCount)
6012
+ return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.isMentioned) !== null && _b !== void 0 ? _b : false;
6013
+ return getChannelIsMentioned(rest);
6014
+ },
6015
+ });
6016
+ };
6017
+
6018
+ const ANALYTIC_CACHE_KEY = ['analytic', 'normal-priority'];
6019
+ const HIGH_PRIORITY_ANALYTIC_CACHE_KEY = ['analytic', 'high-priority'];
6020
+
6021
+ const syncEvent = async (events) => {
6022
+ const client = getActiveClient();
6023
+ const params = {
6024
+ activities: events,
6025
+ };
6026
+ await client.http.post('/api/v1/analytics/activities', params);
6027
+ };
6028
+
6029
+ class AnalyticsEventSyncer {
6030
+ constructor() {
6031
+ this._timer = undefined;
6032
+ this._high_priority_timer = undefined;
6033
+ }
6034
+ start() {
6035
+ this.syncCapturedEvent();
6036
+ this._timer = setInterval(() => {
6037
+ this.syncCapturedEvent();
6038
+ }, 1 * MINUTE);
6039
+ this._high_priority_timer = setInterval(() => {
6040
+ this.syncHighPriorityCapturedEvent();
6041
+ }, 10 * SECOND$1);
6042
+ }
6043
+ stop() {
6044
+ if (this._timer) {
6045
+ clearInterval(this._timer);
6046
+ this._timer = undefined;
6047
+ }
6048
+ if (this._high_priority_timer) {
6049
+ clearInterval(this._high_priority_timer);
6050
+ this._high_priority_timer = undefined;
6051
+ }
6052
+ }
6053
+ async syncCapturedEvent() {
6054
+ try {
6055
+ // Must query only objects that have same userId with current logged-in user.
6056
+ // Query captured event with maximum of 1000
6057
+ // Order by latest first
6058
+ // e.g., If there are 2000 events we will query 1000-2000 first
6059
+ const cache = pullFromCache(ANALYTIC_CACHE_KEY);
6060
+ if (!(cache === null || cache === void 0 ? void 0 : cache.data))
6061
+ return;
6062
+ if (cache.data.event.length === 0)
6063
+ return;
6064
+ const capturedEvents = cache.data.event;
6065
+ await syncEvent(capturedEvents);
6066
+ dropFromCache(ANALYTIC_CACHE_KEY);
6067
+ }
6068
+ catch (error) {
6069
+ // stop and destroy all events
6070
+ this.stop();
6071
+ dropFromCache(ANALYTIC_CACHE_KEY);
6072
+ }
6073
+ }
6074
+ async syncHighPriorityCapturedEvent() {
6075
+ try {
6076
+ // Must query only objects that have same userId with current logged-in user.
6077
+ // Query captured event with maximum of 1000
6078
+ // Order by latest first
6079
+ // e.g., If there are 2000 events we will query 1000-2000 first
6080
+ const cache = pullFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
6081
+ if (!(cache === null || cache === void 0 ? void 0 : cache.data))
6082
+ return;
6083
+ if (cache.data.event.length === 0)
6084
+ return;
6085
+ const capturedEvents = cache.data.event;
6086
+ await syncEvent(capturedEvents);
6087
+ dropFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
6088
+ }
6089
+ catch (error) {
6090
+ // stop and destroy all events
6091
+ this.stop();
6092
+ dropFromCache(HIGH_PRIORITY_ANALYTIC_CACHE_KEY);
6093
+ }
6094
+ }
6095
+ }
6096
+
6097
+ class AnalyticsEventCapturer {
6098
+ constructor() {
6099
+ this._expireTime = 5 * MINUTE;
6100
+ this._poolLimit = 1000;
6101
+ this._recentViewed = {};
6102
+ this._recentHighPriorityViewed = {};
6103
+ // Story
6104
+ this._throttleStoryTimer = undefined;
6105
+ this._bufferNewSeenStoryReferenceIds = [];
6106
+ }
6107
+ isAbleToEnqueue({ uniqueId, expireTime, isHighPriority = false, }) {
6108
+ const now = new Date();
6109
+ // Get the recent view date (if any)
6110
+ const recentViewedDate = isHighPriority
6111
+ ? this._recentHighPriorityViewed[uniqueId]
6112
+ : this._recentViewed[uniqueId];
6113
+ // If this is the first view, always allow it
6114
+ if (!recentViewedDate) {
6115
+ return true;
6116
+ }
6117
+ const timeDiff = now.getTime() - recentViewedDate.getTime();
6118
+ if (timeDiff < expireTime) {
6119
+ // just recently view this post, ignore the event.
6120
+ return false;
6121
+ }
6122
+ return true;
6123
+ }
6124
+ markAs({ uniqueId, contentId, contentType, activityType, metadata, }) {
6125
+ if (!this.isAbleToEnqueue({ uniqueId, expireTime: this._expireTime }))
6126
+ return;
6127
+ const now = new Date();
6128
+ const currentData = { event: [] };
6129
+ const cache = pullFromCache(ANALYTIC_CACHE_KEY);
6130
+ if (cache === null || cache === void 0 ? void 0 : cache.data) {
6131
+ currentData.event = cache.data.event;
6132
+ }
6133
+ // If the pool is full (Max 1000 items), remove the oldest data
4996
6134
  if (currentData.event.length >= this._poolLimit) {
4997
6135
  // Remove oldest data
4998
6136
  currentData.event.shift();
@@ -5176,20 +6314,6 @@ var AnalyticsEngine$1 = {
5176
6314
  },
5177
6315
  };
5178
6316
 
5179
- const userLinkedObject = (user) => {
5180
- return Object.assign(Object.assign({}, user), { get avatar() {
5181
- var _a;
5182
- if (!user.avatarFileId)
5183
- return undefined;
5184
- const avatar = (_a = pullFromCache([
5185
- 'file',
5186
- 'get',
5187
- `${user.avatarFileId}`,
5188
- ])) === null || _a === void 0 ? void 0 : _a.data;
5189
- return avatar;
5190
- } });
5191
- };
5192
-
5193
6317
  class StoryComputedValue {
5194
6318
  constructor(targetId, lastStoryExpiresAt, lastStorySeenExpiresAt) {
5195
6319
  this._syncingStoriesCount = 0;
@@ -5621,7 +6745,7 @@ const postLinkedObject = (post) => {
5621
6745
  } });
5622
6746
  };
5623
6747
 
5624
- const getCachedMarker$2 = (message) => {
6748
+ const getCachedMarker = (message) => {
5625
6749
  var _a, _b;
5626
6750
  const key = {
5627
6751
  creatorId: 'creatorPrivateId' in message ? message.creatorPrivateId : message.creatorId,
@@ -5639,7 +6763,7 @@ const getMessageReadCount = (message, marker) => {
5639
6763
  // Look in the marker param first
5640
6764
  return (_a = marker !== null && marker !== void 0 ? marker :
5641
6765
  // If the marker param is not set, look in the cache
5642
- getCachedMarker$2(message)) !== null && _a !== void 0 ? _a : { readCount: 0, deliveredCount: 0 };
6766
+ getCachedMarker(message)) !== null && _a !== void 0 ? _a : { readCount: 0, deliveredCount: 0 };
5643
6767
  }; // and if not found in cache use default value `0`
5644
6768
 
5645
6769
  /**
@@ -5882,31 +7006,6 @@ const markAsReadBySegment = async ({ subChannelId, readToSegment, }) => {
5882
7006
  }
5883
7007
  };
5884
7008
 
5885
- const reCalculateChannelUnreadInfo = (channelId) => {
5886
- var _a;
5887
- const cacheKeyChannelUnread = ['channelUnreadInfo', 'get', channelId];
5888
- const cacheChannelUnreadInfo = (_a = pullFromCache(cacheKeyChannelUnread)) === null || _a === void 0 ? void 0 : _a.data;
5889
- const cacheKeySubChannelUnread = ['subChannelUnreadInfo', 'get'];
5890
- const cachedSubChannelUnreadInfo = queryCache(cacheKeySubChannelUnread);
5891
- let channelUnreads = 0;
5892
- let isMentioned = false;
5893
- if (cachedSubChannelUnreadInfo && (cachedSubChannelUnreadInfo === null || cachedSubChannelUnreadInfo === void 0 ? void 0 : cachedSubChannelUnreadInfo.length) > 0) {
5894
- const subChannelUnreadsInfo = cachedSubChannelUnreadInfo === null || cachedSubChannelUnreadInfo === void 0 ? void 0 : cachedSubChannelUnreadInfo.filter(({ data }) => {
5895
- return data.channelId === channelId && !data.isDeleted;
5896
- });
5897
- channelUnreads = subChannelUnreadsInfo
5898
- .map(({ data }) => data.unreadCount)
5899
- .reduce((acc, cur) => acc + cur, 0);
5900
- isMentioned = subChannelUnreadsInfo.some(({ data }) => data.isMentioned);
5901
- }
5902
- const channelUnreadInfo = Object.assign(Object.assign({}, (cacheChannelUnreadInfo !== null && cacheChannelUnreadInfo !== void 0 ? cacheChannelUnreadInfo : {
5903
- channelId,
5904
- createdAt: new Date().toISOString(),
5905
- })), { updatedAt: new Date().toISOString(), unreadCount: channelUnreads, isMentioned });
5906
- pushToCache(cacheKeyChannelUnread, channelUnreadInfo);
5907
- return channelUnreadInfo;
5908
- };
5909
-
5910
7009
  class LegacyMessageReadReceiptSyncEngine {
5911
7010
  constructor() {
5912
7011
  this.isActive = true;
@@ -6192,24 +7291,6 @@ const markAsRead = async (channelId) => {
6192
7291
  return true;
6193
7292
  };
6194
7293
 
6195
- /**
6196
- * ```js
6197
- * import { shallowClone } from '~/utils/shallowClone'
6198
- * const newObj = shallowClone(obj)
6199
- * ```
6200
- *
6201
- * Clone an object with same prototype and properties
6202
- *
6203
- * @param obj the object to clone
6204
- * @returns new object with same prototype and properties
6205
- *
6206
- * @category utility
6207
- * @private
6208
- */
6209
- function shallowClone(source, target) {
6210
- return Object.create(Object.getPrototypeOf(source), Object.assign(Object.assign({}, Object.getOwnPropertyDescriptors(source)), Object.getOwnPropertyDescriptors(target)));
6211
- }
6212
-
6213
7294
  const channelLinkedObject = (channel) => {
6214
7295
  return shallowClone(channel, {
6215
7296
  markAsRead: () => markAsRead(channel.channelInternalId),
@@ -6277,1071 +7358,1293 @@ const pinnedPostLinkedObject = (pinnedPost) => {
6277
7358
  ]);
6278
7359
  if (!(pinTarget === null || pinTarget === void 0 ? void 0 : pinTarget.data))
6279
7360
  return;
6280
- return pinTarget === null || pinTarget === void 0 ? void 0 : pinTarget.data;
6281
- } });
6282
- };
6283
-
6284
- const notificationTrayLinkedObject = (noti) => {
6285
- return Object.assign(Object.assign({}, noti), { isSeen: noti.lastSeenAt > noti.lastOccurredAt, isRecent: new Date(noti.lastOccurredAt).getTime() >= Date.now() - WEEK, users: noti.actors
6286
- .map(({ publicId }) => pullFromCache(['user', 'get', publicId]))
6287
- .filter(isNonNullable)
6288
- .map(({ data }) => data)
6289
- .map(user => userLinkedObject(user)) });
6290
- };
6291
-
6292
- const LinkedObject = {
6293
- ad: adLinkedObject,
6294
- comment: commentLinkedObject,
6295
- post: postLinkedObject,
6296
- user: userLinkedObject,
6297
- category: categoryLinkedObject,
6298
- stream: streamLinkedObject,
6299
- story: storyLinkedObject,
6300
- storyTarget: storyTargetLinkedObject,
6301
- message: messageLinkedObject,
6302
- reactor: reactorLinkedObject,
6303
- channel: channelLinkedObject,
6304
- pinnedPost: pinnedPostLinkedObject,
6305
- notificationTray: notificationTrayLinkedObject,
6306
- };
6307
-
6308
- const getChannelMessagePreviewWithUser = (channel) => {
6309
- var _a;
6310
- const messagePreview = channel.messagePreviewId
6311
- ? getChannelMessagePreview(channel.channelId)
6312
- : null;
6313
- const internalUser = (_a = pullFromCache([
6314
- 'user',
6315
- 'get',
6316
- messagePreview === null || messagePreview === void 0 ? void 0 : messagePreview.creatorId,
6317
- ])) === null || _a === void 0 ? void 0 : _a.data;
6318
- const messagePreviewWithUser = messagePreview
6319
- ? Object.assign(Object.assign({}, messagePreview), { user: internalUser ? LinkedObject.user(internalUser) : undefined }) : null;
6320
- return Object.assign(Object.assign({}, channel), { messagePreview: messagePreviewWithUser });
6321
- };
6322
-
6323
- const updateChannelMessagePreviewCache = (rawPayload) => {
6324
- var _a, _b;
6325
- const withMessageFeedInfo = (messagePreview) => {
6326
- var _a;
6327
- const messageFeedInfo = (_a = rawPayload.messageFeedsInfo) === null || _a === void 0 ? void 0 : _a.find(messageFeed => {
6328
- return messageFeed.messageFeedId === messagePreview.messageFeedId;
6329
- });
6330
- const { channelPublicId: channelId, messageFeedId: subChannelId, data, dataType, isDeleted, segment, creatorPublicId: creatorId, createdAt, updatedAt, } = messagePreview;
6331
- return {
6332
- channelId,
6333
- subChannelId,
6334
- data,
6335
- dataType,
6336
- isDeleted,
6337
- segment,
6338
- creatorId,
6339
- createdAt,
6340
- updatedAt,
6341
- subChannelName: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.name,
6342
- messagePreviewId: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.messagePreviewId,
6343
- subChannelUpdatedAt: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.updatedAt,
6344
- };
6345
- };
6346
- const newData = {
6347
- messagePreviewChannel: (_b = (_a = rawPayload.messagePreviews) === null || _a === void 0 ? void 0 : _a.map(messagePreview => withMessageFeedInfo(messagePreview))) !== null && _b !== void 0 ? _b : [],
6348
- };
6349
- ingestInCache(newData);
6350
- };
6351
-
6352
- const getSubChannelMessagePreview = (subChannelId) => {
6353
- var _a, _b;
6354
- return ((_b = (_a = pullFromCache(['messagePreviewSubChannel', 'get', subChannelId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : null);
6355
- };
6356
-
6357
- const getSubChannelMessagePreviewWithUser = (subChannel) => {
6358
- var _a;
6359
- const messagePreview = subChannel.messagePreviewId
6360
- ? getSubChannelMessagePreview(subChannel.subChannelId)
6361
- : null;
6362
- const messagePreviewWithUser = messagePreview
6363
- ? Object.assign(Object.assign({}, messagePreview), { user: (_a = pullFromCache(['user', 'get', messagePreview === null || messagePreview === void 0 ? void 0 : messagePreview.creatorId])) === null || _a === void 0 ? void 0 : _a.data }) : null;
6364
- return Object.assign(Object.assign({}, subChannel), { messagePreview: messagePreviewWithUser });
6365
- };
6366
-
6367
- const updateSubChannelMessagePreviewCache = (rawPayload) => {
6368
- var _a, _b;
6369
- const withMessageFeedInfo = (messagePreview) => {
6370
- var _a;
6371
- const messageFeedInfo = (_a = rawPayload.messageFeeds) === null || _a === void 0 ? void 0 : _a.find(messageFeed => {
6372
- return messageFeed.messageFeedId === messagePreview.messageFeedId;
6373
- });
6374
- const { channelPublicId: channelId, messageFeedId: subChannelId, messageId: messagePreviewId, creatorPublicId: creatorId, data, dataType, isDeleted, segment, createdAt, updatedAt, } = messagePreview;
6375
- return {
6376
- messagePreviewId,
6377
- channelId,
6378
- subChannelId,
6379
- data,
6380
- dataType,
6381
- isDeleted,
6382
- segment,
6383
- creatorId,
6384
- createdAt,
6385
- updatedAt,
6386
- subChannelName: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.name,
6387
- subChannelUpdatedAt: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.updatedAt,
6388
- };
6389
- };
6390
- const newData = {
6391
- messagePreviewSubChannel: (_b = (_a = rawPayload.messages) === null || _a === void 0 ? void 0 : _a.map(messagePreview => withMessageFeedInfo(messagePreview))) !== null && _b !== void 0 ? _b : [],
6392
- };
6393
- ingestInCache(newData);
7361
+ return pinTarget === null || pinTarget === void 0 ? void 0 : pinTarget.data;
7362
+ } });
6394
7363
  };
6395
7364
 
6396
- function updateSubChannelCache(subChannelId, subChannel, params) {
6397
- pushToCache(['subChannel', 'get', subChannelId],
6398
- // eslint-disable-next-line prefer-object-spread
6399
- shallowClone(subChannel, params));
7365
+ const notificationTrayLinkedObject = (noti) => {
7366
+ return Object.assign(Object.assign({}, noti), { isSeen: noti.lastSeenAt > noti.lastOccurredAt, isRecent: new Date(noti.lastOccurredAt).getTime() >= Date.now() - WEEK, users: noti.actors
7367
+ .map(({ publicId }) => pullFromCache(['user', 'get', publicId]))
7368
+ .filter(isNonNullable)
7369
+ .map(({ data }) => data)
7370
+ .map(user => userLinkedObject(user)) });
7371
+ };
7372
+
7373
+ /*
7374
+ * verifies membership status
7375
+ */
7376
+ function isMember(membership) {
7377
+ return membership !== 'none';
7378
+ }
7379
+ /*
7380
+ * checks if currently logged in user is part of the community
7381
+ */
7382
+ function isCurrentUserPartOfCommunity(c, m) {
7383
+ const { userId } = getActiveUser();
7384
+ return c.communityId === m.communityId && m.userId === userId;
7385
+ }
7386
+ /*
7387
+ * For mqtt events server will not send user specific data as it's broadcasted
7388
+ * to multiple users and it also does not include communityUser
7389
+ *
7390
+ * Client SDK needs to check for the existing isJoined field in cache data before calculating.
7391
+ * Althought this can be calculated, it's not scalable.
7392
+ */
7393
+ function updateMembershipStatus(communities, communityUsers) {
7394
+ return communities.map(c => {
7395
+ const cachedCommunity = pullFromCache([
7396
+ 'community',
7397
+ 'get',
7398
+ c.communityId,
7399
+ ]);
7400
+ if ((cachedCommunity === null || cachedCommunity === void 0 ? void 0 : cachedCommunity.data) && (cachedCommunity === null || cachedCommunity === void 0 ? void 0 : cachedCommunity.data.hasOwnProperty('isJoined'))) {
7401
+ return Object.assign(Object.assign({}, cachedCommunity.data), c);
7402
+ }
7403
+ const isJoined = communityUsers.some(m => isCurrentUserPartOfCommunity(c, m) && isMember(m.communityMembership));
7404
+ return Object.assign(Object.assign({}, c), { isJoined });
7405
+ });
6400
7406
  }
6401
7407
 
7408
+ const getMatchPostSetting = (value) => {
7409
+ var _a;
7410
+ return (_a = Object.keys(CommunityPostSettingMaps).find(key => value.needApprovalOnPostCreation ===
7411
+ CommunityPostSettingMaps[key].needApprovalOnPostCreation &&
7412
+ value.onlyAdminCanPost === CommunityPostSettingMaps[key].onlyAdminCanPost)) !== null && _a !== void 0 ? _a : DefaultCommunityPostSetting;
7413
+ };
7414
+ function addPostSetting({ communities }) {
7415
+ return communities.map((_a) => {
7416
+ var { needApprovalOnPostCreation, onlyAdminCanPost } = _a, restCommunityPayload = __rest(_a, ["needApprovalOnPostCreation", "onlyAdminCanPost"]);
7417
+ return (Object.assign({ postSetting: getMatchPostSetting({
7418
+ needApprovalOnPostCreation,
7419
+ onlyAdminCanPost,
7420
+ }) }, restCommunityPayload));
7421
+ });
7422
+ }
7423
+ const prepareCommunityPayload = (rawPayload) => {
7424
+ const communitiesWithPostSetting = addPostSetting({ communities: rawPayload.communities });
7425
+ // Convert users to internal format
7426
+ const internalUsers = rawPayload.users.map(convertRawUserToInternalUser);
7427
+ // map users with community
7428
+ const mappedCommunityUsers = rawPayload.communityUsers.map(communityUser => {
7429
+ const user = internalUsers.find(user => user.userId === communityUser.userId);
7430
+ return Object.assign(Object.assign({}, communityUser), { user });
7431
+ });
7432
+ const communityWithMembershipStatus = updateMembershipStatus(communitiesWithPostSetting, mappedCommunityUsers);
7433
+ return Object.assign(Object.assign({}, rawPayload), { users: rawPayload.users.map(convertRawUserToInternalUser), communities: communityWithMembershipStatus, communityUsers: mappedCommunityUsers });
7434
+ };
7435
+ const prepareCommunityJoinRequestPayload = (rawPayload) => {
7436
+ const mappedJoinRequests = rawPayload.joinRequests.map(joinRequest => {
7437
+ return Object.assign(Object.assign({}, joinRequest), { joinRequestId: joinRequest._id });
7438
+ });
7439
+ const users = rawPayload.users.map(convertRawUserToInternalUser);
7440
+ return Object.assign(Object.assign({}, rawPayload), { joinRequests: mappedJoinRequests, users });
7441
+ };
7442
+ const prepareCommunityMembershipPayload = (rawPayload) => {
7443
+ const communitiesWithPostSetting = addPostSetting({ communities: rawPayload.communities });
7444
+ // map users with community
7445
+ const mappedCommunityUsers = rawPayload.communityUsers.map(communityUser => {
7446
+ const user = rawPayload.users.find(user => user.userId === communityUser.userId);
7447
+ return Object.assign(Object.assign({}, communityUser), { user });
7448
+ });
7449
+ const communityWithMembershipStatus = updateMembershipStatus(communitiesWithPostSetting, mappedCommunityUsers);
7450
+ return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers: mappedCommunityUsers });
7451
+ };
7452
+ const prepareCommunityRequest = (params) => {
7453
+ const { postSetting = undefined, storySetting } = params, restParam = __rest(params, ["postSetting", "storySetting"]);
7454
+ return Object.assign(Object.assign(Object.assign({}, restParam), (postSetting ? CommunityPostSettingMaps[postSetting] : undefined)), {
7455
+ // Convert story setting to the actual value. (Allow by default)
7456
+ allowCommentInStory: typeof (storySetting === null || storySetting === void 0 ? void 0 : storySetting.enableComment) === 'boolean' ? storySetting.enableComment : true });
7457
+ };
7458
+ const prepareSemanticSearchCommunityPayload = (_a) => {
7459
+ var communityPayload = __rest(_a, ["searchResult"]);
7460
+ const processedCommunityPayload = prepareCommunityPayload(communityPayload);
7461
+ return Object.assign({}, processedCommunityPayload);
7462
+ };
7463
+
7464
+ /* begin_public_function
7465
+ id: joinRequest.approve
7466
+ */
6402
7467
  /**
6403
7468
  * ```js
6404
- * import { isInTombstone } from '@amityco/ts-sdk'
6405
- * const user = isInTombstone(["message", "messageId"])
7469
+ * import { joinRequest } from '@amityco/ts-sdk'
7470
+ * const isAccepted = await joinRequest.approve()
6406
7471
  * ```
6407
7472
  *
6408
- * Checks if the {@link Amity.TombstoneCacheOptions} exists
6409
- * in cache and it's not expired means it's in tombstone
6410
- * and we throw an Error
7473
+ * Accepts a {@link Amity.JoinRequest} object
6411
7474
  *
6412
- * @param model the model to check
6413
- * @param modelId the object id to check
6414
- * @returns the matching cache entry, or undefined.
7475
+ * @param joinRequest the {@link Amity.JoinRequest} to accept
7476
+ * @returns A success boolean if the {@link Amity.JoinRequest} was accepted
6415
7477
  *
6416
- * @category Cache API
7478
+ * @category Join Request API
7479
+ * @async
6417
7480
  */
6418
- const isInTombstone = (model, modelId) => {
6419
- const { log, cache } = getActiveClient();
6420
- const key = [model, CACHE_KEY_TOMBSTONE, modelId];
6421
- if (!cache)
6422
- return;
6423
- log('cache/api/isInTombstone', key);
6424
- const isInTombstone = pullFromCache(key);
6425
- const { lifeSpan } = queryOptions('cache_then_server', CACHE_LIFESPAN_TOMBSTONE);
6426
- if (isInTombstone && isFresh(isInTombstone.data, lifeSpan)) {
6427
- throw new ASCApiError('Item not found!', 400400 /* Amity.ServerError.ITEM_NOT_FOUND */, "error" /* Amity.ErrorLevel.ERROR */);
7481
+ const approveJoinRequest = async (joinRequest) => {
7482
+ var _a;
7483
+ const client = getActiveClient();
7484
+ client.log('joinRequest/approveJoinRequest', joinRequest.joinRequestId);
7485
+ const { data } = await client.http.post(`/api/v4/communities/${joinRequest.targetId}/join/approve`, {
7486
+ userId: joinRequest.requestorInternalId,
7487
+ });
7488
+ const joinRequestCache = (_a = pullFromCache([
7489
+ 'joinRequest',
7490
+ 'get',
7491
+ joinRequest.joinRequestId,
7492
+ ])) === null || _a === void 0 ? void 0 : _a.data;
7493
+ if (joinRequestCache) {
7494
+ upsertInCache(['joinRequest', 'get', joinRequest.joinRequestId], {
7495
+ status: "approved" /* JoinRequestStatusEnum.Approved */,
7496
+ });
7497
+ fireEvent('local.joinRequest.updated', [joinRequestCache]);
6428
7498
  }
6429
- };
7499
+ return data.success;
7500
+ };
7501
+ /* end_public_function */
6430
7502
 
7503
+ /* begin_public_function
7504
+ id: joinRequest.cancel
7505
+ */
6431
7506
  /**
6432
7507
  * ```js
6433
- * import { getMessageMarkers } from '@amityco/ts-sdk'
6434
- * const messageMarkers = await getMessageMarkers(['sch1', 'sch2'])
7508
+ * import { joinRequest } from '@amityco/ts-sdk'
7509
+ * const isCanceled = await joinRequest.cancel()
6435
7510
  * ```
6436
7511
  *
6437
- * Fetches a list of {@link Amity.MessageMarker} by messageIds
7512
+ * Cancels a {@link Amity.JoinRequest} object
6438
7513
  *
6439
- * @param messageIds the feed IDs of the {@link Amity.RawMessage} marker to fetch
6440
- * @returns A list of {@link Amity.MessageMarker} by messageIds
7514
+ * @param joinRequest the {@link Amity.JoinRequest} to cancel
7515
+ * @returns A success boolean if the {@link Amity.JoinRequest} was canceled
6441
7516
  *
6442
- * @category Channel API
7517
+ * @category Join Request API
6443
7518
  * @async
6444
- * @private
6445
7519
  */
6446
- const getMessageMarkers = async (messageIds) => {
7520
+ const cancelJoinRequest = async (joinRequest) => {
7521
+ var _a;
6447
7522
  const client = getActiveClient();
6448
- client.log('channel/getMessageMarkers', messageIds);
6449
- const { data: queryPayload } = await client.http.get(`/api/v1/markers/messages`, {
6450
- params: {
6451
- messageIds,
6452
- },
6453
- });
6454
- const { contentMarkers, feedMarkers, userMarkers } = queryPayload;
6455
- const cachedAt = client.cache && Date.now();
6456
- if (client.cache)
6457
- ingestInCache({ contentMarkers, feedMarkers, userMarkers }, { cachedAt });
6458
- fireEvent('local.feedMarker.fetched', { feedMarkers });
6459
- fireEvent('local.messageMarker.fetched', { contentMarkers });
6460
- fireEvent('local.userMarker.fetched', { userMarkers });
6461
- return { data: contentMarkers, cachedAt };
6462
- };
6463
-
6464
- const persistUnreadCountInfo = (payload) => {
6465
- const { feedMarkers, userFeedMarkers } = payload;
6466
- // calculate sub channel unread info and channel unread info
6467
- if (feedMarkers.length > 0 && userFeedMarkers.length > 0) {
6468
- const channelIds = [];
6469
- const feedMarkerMap = new Map(feedMarkers.map(fm => [fm.feedId, fm]));
6470
- userFeedMarkers.forEach(userFeedMarker => {
6471
- const feedMarker = feedMarkerMap.get(userFeedMarker.feedId);
6472
- if (!feedMarker)
6473
- return;
6474
- if (feedMarker.feedId === userFeedMarker.feedId) {
6475
- const unreadCount = feedMarker.lastSegment - userFeedMarker.readToSegment;
6476
- const subChannelUnreadInfo = {
6477
- subChannelId: feedMarker.feedId,
6478
- channelId: feedMarker.entityId,
6479
- readToSegment: userFeedMarker.readToSegment,
6480
- lastSegment: feedMarker.lastSegment,
6481
- lastMentionSegment: userFeedMarker.lastMentionSegment,
6482
- unreadCount: Math.max(0, unreadCount),
6483
- isMentioned: userFeedMarker.isMentioned,
6484
- isDeleted: feedMarker.isDeleted,
6485
- createdAt: userFeedMarker.createdAt,
6486
- updatedAt: userFeedMarker.updatedAt,
6487
- };
6488
- // update sub channel unread info in cache
6489
- ingestInCache({ subChannelUnreadInfo: [subChannelUnreadInfo] });
6490
- if (!channelIds.includes(feedMarker.entityId)) {
6491
- channelIds.push(feedMarker.entityId);
6492
- }
6493
- }
6494
- });
6495
- // re-calculate channel unread info in cache
6496
- channelIds.forEach(channelId => {
6497
- reCalculateChannelUnreadInfo(channelId);
6498
- });
7523
+ client.log('joinRequest/cancelJoinRequest', joinRequest.joinRequestId);
7524
+ const { data } = await client.http.delete(`/api/v4/communities/${joinRequest.targetId}/join`);
7525
+ const joinRequestCache = (_a = pullFromCache([
7526
+ 'joinRequest',
7527
+ 'get',
7528
+ joinRequest.joinRequestId,
7529
+ ])) === null || _a === void 0 ? void 0 : _a.data;
7530
+ if (joinRequestCache) {
7531
+ dropFromCache(['joinRequest', 'get', joinRequest.joinRequestId]);
7532
+ fireEvent('local.joinRequest.deleted', [joinRequestCache]);
6499
7533
  }
6500
- };
7534
+ return data.success;
7535
+ };
7536
+ /* end_public_function */
6501
7537
 
7538
+ /* begin_public_function
7539
+ id: joinRequest.reject
7540
+ */
6502
7541
  /**
6503
7542
  * ```js
6504
- * import { getSubChannelMarkers } from '@amityco/ts-sdk'
6505
- * const subChannelMarkers = await getSubChannelMarkers(['sch1', 'sch2'])
7543
+ * import { joinRequest } from '@amityco/ts-sdk'
7544
+ * const isRejected = await joinRequest.reject()
6506
7545
  * ```
6507
7546
  *
6508
- * Fetches a paginable list of {@link Amity.SubChannelMarker} objects
7547
+ * Rejects a {@link Amity.JoinRequest} object
6509
7548
  *
6510
- * @param messageFeedIds the feed IDs of the {@link Amity.RawSubChannel} marker to fetch
6511
- * @param page
6512
- * @returns A page of {@link Amity.SubChannelMarker} objects
7549
+ * @param joinRequest the {@link Amity.JoinRequest} to reject
7550
+ * @returns A success boolean if the {@link Amity.JoinRequest} was rejected
6513
7551
  *
6514
- * @category Channel API
7552
+ * @category Join Request API
6515
7553
  * @async
6516
- * @private
6517
7554
  */
6518
- const getSubChannelMarkers = async (messageFeedIds, page = { limit: 100 }) => {
7555
+ const rejectJoinRequest = async (joinRequest) => {
7556
+ var _a;
6519
7557
  const client = getActiveClient();
6520
- client.log('channel/getSubChannelMarkers', messageFeedIds, page);
6521
- const { data: queryPayload } = await client.http.get(`/api/v1/markers/message-feeds`, {
6522
- params: {
6523
- messageFeedIds,
6524
- options: {
6525
- token: toToken(page, 'skiplimit'),
6526
- },
6527
- },
7558
+ client.log('joinRequest/rejectJoinRequest', joinRequest.joinRequestId);
7559
+ const { data } = await client.http.post(`/api/v4/communities/${joinRequest.targetId}/join/reject`, {
7560
+ userId: joinRequest.requestorInternalId,
6528
7561
  });
6529
- const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
6530
- const { userEntityMarkers: userEntityMarkersPayload, userFeedMarkers: userFeedMarkersPayload, userMarkers, feedMarkers: feedMarkersPayload, } = payload;
6531
- // if consistent mode is enabled, persist the unread count info to the cache
6532
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
6533
- persistUnreadCountInfo({
6534
- feedMarkers: feedMarkersPayload,
6535
- userFeedMarkers: userFeedMarkersPayload,
7562
+ const joinRequestCache = (_a = pullFromCache([
7563
+ 'joinRequest',
7564
+ 'get',
7565
+ joinRequest.joinRequestId,
7566
+ ])) === null || _a === void 0 ? void 0 : _a.data;
7567
+ if (joinRequestCache) {
7568
+ upsertInCache(['joinRequest', 'get', joinRequest.joinRequestId], {
7569
+ status: "rejected" /* JoinRequestStatusEnum.Rejected */,
6536
7570
  });
7571
+ fireEvent('local.joinRequest.updated', [joinRequestCache]);
6537
7572
  }
6538
- const userEntityMarkers = convertChannelMarkerResponse(userEntityMarkersPayload);
6539
- const userFeedMarkers = convertSubChannelMarkerResponse(userFeedMarkersPayload);
6540
- const cachedAt = client.cache && Date.now();
6541
- if (client.cache)
6542
- ingestInCache({ userEntityMarkers, userFeedMarkers, userMarkers }, { cachedAt });
6543
- fireEvent('local.channelMarker.fetched', { userEntityMarkers });
6544
- fireEvent('local.subChannelMarker.fetched', { userFeedMarkers });
6545
- fireEvent('local.userMarker.fetched', { userMarkers });
6546
- const nextPage = toPage(paging.next);
6547
- const prevPage = toPage(paging.previous);
6548
- return { data: userFeedMarkers, cachedAt, prevPage, nextPage };
6549
- };
7573
+ return data.success;
7574
+ };
7575
+ /* end_public_function */
6550
7576
 
6551
- const getUserMarker = async () => {
6552
- const client = getActiveClient();
6553
- client.log('channel/getUserMarker');
6554
- const { data: payload } = await client.http.get(`/api/v1/markers/userMarker`);
6555
- const { userMarkers } = payload;
6556
- const cachedAt = client.cache && Date.now();
6557
- if (client.cache)
6558
- ingestInCache({ userMarkers }, { cachedAt });
6559
- fireEvent('local.userMarker.fetched', { userMarkers });
6560
- const latestUserMarker = userMarkers.reduce((maxUserMarker, userMarker) => {
6561
- if (maxUserMarker == null ||
6562
- new Date(maxUserMarker.lastSyncAt).getTime() < new Date(userMarker.lastSyncAt).getTime()) {
6563
- return userMarker;
6564
- }
6565
- return maxUserMarker;
6566
- }, undefined);
6567
- return { data: latestUserMarker, cachedAt };
7577
+ const joinRequestLinkedObject = (joinRequest) => {
7578
+ return Object.assign(Object.assign({}, joinRequest), { get user() {
7579
+ var _a;
7580
+ const user = (_a = pullFromCache([
7581
+ 'user',
7582
+ 'get',
7583
+ joinRequest.requestorPublicId,
7584
+ ])) === null || _a === void 0 ? void 0 : _a.data;
7585
+ if (!user)
7586
+ return undefined;
7587
+ return userLinkedObject(user);
7588
+ }, cancel: async () => {
7589
+ await cancelJoinRequest(joinRequest);
7590
+ }, approve: async () => {
7591
+ await approveJoinRequest(joinRequest);
7592
+ }, reject: async () => {
7593
+ await rejectJoinRequest(joinRequest);
7594
+ } });
6568
7595
  };
6569
7596
 
6570
- /** @hidden */
6571
- /*
6572
- * @param message payload from http request without myReactions
6573
- * add myReactions to http response if the event was a reaction event
7597
+ /* begin_public_function
7598
+ id: community.getMyJoinRequest
7599
+ */
7600
+ /**
7601
+ * ```js
7602
+ * import { community } from '@amityco/ts-sdk'
7603
+ * const isJoined = await community.getMyJoinRequest('foobar')
7604
+ * ```
7605
+ *
7606
+ * Joins a {@link Amity.Community} object
7607
+ *
7608
+ * @param communityId the {@link Amity.Community} to join
7609
+ * @returns A success boolean if the {@link Amity.Community} was joined
7610
+ *
7611
+ * @category Community API
7612
+ * @async
6574
7613
  */
6575
- const prepareMessagePayloadForCache = (payload, reactors, event) => {
7614
+ const getMyJoinRequest = async (communityId) => {
6576
7615
  const client = getActiveClient();
6577
- const cached = pullFromCache(['message', 'get', payload.messageId]);
6578
- // '[]' in cases where the new reaction is the first one
6579
- const myReactions = (cached === null || cached === void 0 ? void 0 : cached.data.myReactions) || [];
6580
- // add myReactions to the payload
6581
- Object.assign(payload, { myReactions });
6582
- // check if there are any updates to the reactions
6583
- const latestReaction = reactors[0];
6584
- const isLatestReactionMine = latestReaction && latestReaction.userId === client.userId;
6585
- if (!isLatestReactionMine) {
6586
- return;
6587
- }
6588
- // new reaction added
6589
- if (event === 'message.reactionAdded' && !myReactions.includes(latestReaction.reactionName)) {
6590
- Object.assign(payload, {
6591
- myReactions: [...myReactions, latestReaction.reactionName],
6592
- });
6593
- }
6594
- // existing reaction removed
6595
- if (event === 'message.reactionRemoved' && myReactions.includes(latestReaction.reactionName)) {
6596
- Object.assign(payload, {
6597
- myReactions: myReactions.filter(x => x !== latestReaction.reactionName),
6598
- });
6599
- }
6600
- };
7616
+ client.log('community/myJoinRequest', communityId);
7617
+ const { data: payload } = await client.http.get(`/api/v4/communities/${communityId}/join/me`);
7618
+ const data = prepareCommunityJoinRequestPayload(payload);
7619
+ const cachedAt = client.cache && Date.now();
7620
+ if (client.cache)
7621
+ ingestInCache(data, { cachedAt });
7622
+ return {
7623
+ data: data.joinRequests[0] ? joinRequestLinkedObject(data.joinRequests[0]) : undefined,
7624
+ cachedAt,
7625
+ };
7626
+ };
7627
+ /* end_public_function */
6601
7628
 
6602
- /*
6603
- * This is a simple utility that infers the value of isDeleted based on the
6604
- * value of includeDeleted
7629
+ /* begin_public_function
7630
+ id: community.join
7631
+ */
7632
+ /**
7633
+ * ```js
7634
+ * import { community } from '@amityco/ts-sdk'
7635
+ * const isJoined = await community.join('foobar')
7636
+ * ```
6605
7637
  *
6606
- * There are two important things to note here:
6607
- * 1. `includeDeleted` is purely client side query param and not recognized by
6608
- * the server
6609
- * 2. The only values we wish to expose with regards to `isDeleted` (the server
6610
- * param for queries) is false | undefined and want to disallow users to query
6611
- * for deleted entities
7638
+ * Joins a {@link Amity.Community} object
6612
7639
  *
6613
- * Although this is a very simple utility, it's only purpose is to keep things
6614
- * DRY
7640
+ * @param communityId the {@link Amity.Community} to join
7641
+ * @returns A status join result
7642
+ *
7643
+ * @category Community API
7644
+ * @async
6615
7645
  */
6616
- const inferIsDeleted = (includeDeleted) => includeDeleted === true ? undefined : false;
7646
+ const joinRequest = async (communityId) => {
7647
+ const client = getActiveClient();
7648
+ client.log('community/joinRequest', communityId);
7649
+ const { data: payload } = await client.http.post(`/api/v4/communities/${communityId}/join`);
7650
+ const data = prepareCommunityJoinRequestPayload(payload);
7651
+ const cachedAt = client.cache && Date.now();
7652
+ if (client.cache)
7653
+ ingestInCache(data, { cachedAt });
7654
+ fireEvent('local.community.join', data.joinRequests);
7655
+ const status = data.joinRequests[0].status === "approved" /* JoinRequestStatusEnum.Approved */
7656
+ ? "success" /* JoinResultStatusEnum.Success */
7657
+ : "pending" /* JoinResultStatusEnum.Pending */;
7658
+ return status === "success" /* JoinResultStatusEnum.Success */
7659
+ ? { status }
7660
+ : { status, request: joinRequestLinkedObject(data.joinRequests[0]) };
7661
+ };
7662
+ /* end_public_function */
6617
7663
 
6618
- function getSubChannelIsMentioned(channelId, subChannelId, marker) {
6619
- var _a, _b;
6620
- // Look for `unreadCount` in the marker param first
6621
- if (marker) {
6622
- return marker.hasMentioned;
7664
+ class PaginationController {
7665
+ constructor(queryParams) {
7666
+ const { http } = getActiveClient();
7667
+ this.queryParams = queryParams;
7668
+ this.http = http;
6623
7669
  }
6624
- const client = getActiveClient();
6625
- // If consistent mode is enabled, look in the SubChannelUnreadCountInfo cache
6626
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
6627
- const cachedUnreadCount = (_a = pullFromCache([
6628
- 'subChannelUnreadInfo',
6629
- 'get',
6630
- subChannelId,
6631
- ])) === null || _a === void 0 ? void 0 : _a.data;
6632
- if (cachedUnreadCount) {
6633
- return cachedUnreadCount.isMentioned;
6634
- }
6635
- return false;
7670
+ loadFirstPage() {
7671
+ return this.onFetch("first" /* Amity.LiveCollectionPageDirection.FIRST */);
6636
7672
  }
6637
- const key = {
6638
- entityId: channelId,
6639
- feedId: subChannelId,
6640
- userId: getActiveUser()._id,
6641
- };
6642
- // If the marker param is not set, look in the cache
6643
- const cachedMarker = (_b = pullFromCache([
6644
- 'subChannelMarker',
6645
- 'get',
6646
- getResolver('subChannelMarker')(key),
6647
- ])) === null || _b === void 0 ? void 0 : _b.data;
6648
- if (cachedMarker) {
6649
- return cachedMarker.hasMentioned;
7673
+ loadNextPage() {
7674
+ return this.onFetch("next" /* Amity.LiveCollectionPageDirection.NEXT */);
6650
7675
  }
6651
- // and if not found in cache use default value `false`
6652
- return false;
6653
- }
6654
-
6655
- function getSubChannelUnreadCount(channelId, subChannelId, marker) {
6656
- var _a, _b;
6657
- // Look for `unreadCount` in the marker param first
6658
- if (marker) {
6659
- return marker.unreadCount;
7676
+ loadPreviousPage() {
7677
+ return this.onFetch("prev" /* Amity.LiveCollectionPageDirection.PREV */);
6660
7678
  }
6661
- const client = getActiveClient();
6662
- // If consistent mode is enabled, look in the SubChannelUnreadCountInfo cache
6663
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
6664
- const cachedUnreadCount = (_a = pullFromCache([
6665
- 'subChannelUnreadInfo',
6666
- 'get',
6667
- subChannelId,
6668
- ])) === null || _a === void 0 ? void 0 : _a.data;
6669
- if (cachedUnreadCount) {
6670
- return cachedUnreadCount.isDeleted ? 0 : cachedUnreadCount.unreadCount;
7679
+ async onFetch(direction = "first" /* Amity.LiveCollectionPageDirection.FIRST */) {
7680
+ var _a, _b, _c, _d;
7681
+ if (direction === 'prev' && !this.previousToken)
7682
+ return;
7683
+ if (direction === 'next' && !this.nextToken)
7684
+ return;
7685
+ let token;
7686
+ if (direction === 'prev')
7687
+ token = this.previousToken;
7688
+ if (direction === 'next')
7689
+ token = this.nextToken;
7690
+ const queryResponse = await this.getRequest(this.queryParams, token);
7691
+ if (direction === 'first') {
7692
+ this.nextToken = (_a = queryResponse.paging) === null || _a === void 0 ? void 0 : _a.next;
7693
+ this.previousToken = (_b = queryResponse.paging) === null || _b === void 0 ? void 0 : _b.previous;
6671
7694
  }
6672
- return 0;
7695
+ if (direction === 'prev')
7696
+ this.previousToken = (_c = queryResponse.paging) === null || _c === void 0 ? void 0 : _c.previous;
7697
+ if (direction === 'next')
7698
+ this.nextToken = (_d = queryResponse.paging) === null || _d === void 0 ? void 0 : _d.next;
7699
+ return queryResponse;
6673
7700
  }
6674
- const key = {
6675
- entityId: channelId,
6676
- feedId: subChannelId,
6677
- userId: getActiveUser()._id,
6678
- };
6679
- // If the marker param is not set, look in the cache
6680
- const cachedMarker = (_b = pullFromCache([
6681
- 'subChannelMarker',
6682
- 'get',
6683
- getResolver('subChannelMarker')(key),
6684
- ])) === null || _b === void 0 ? void 0 : _b.data;
6685
- if (cachedMarker) {
6686
- return cachedMarker.unreadCount;
7701
+ getNextToken() {
7702
+ return this.nextToken;
7703
+ }
7704
+ getPrevToken() {
7705
+ return this.previousToken;
6687
7706
  }
6688
- // and if not found in cache use default value `0`
6689
- return 0;
6690
7707
  }
6691
7708
 
6692
- const MARKER_INCLUDED_SUB_CHANNEL_TYPE$1 = ['broadcast', 'conversation', 'community'];
6693
- const isUnreadCountSupport$2 = ({ channelType }) => MARKER_INCLUDED_SUB_CHANNEL_TYPE$1.includes(channelType);
6694
- function convertFromRaw$2(_a) {
6695
- var { channelId, channelPublicId, channelType, childCount, creatorId, creatorPublicId, lastMessageId, lastMessageTimestamp, messageFeedId, name } = _a, rest = __rest(_a, ["channelId", "channelPublicId", "channelType", "childCount", "creatorId", "creatorPublicId", "lastMessageId", "lastMessageTimestamp", "messageFeedId", "name"]);
6696
- return Object.assign(Object.assign({ get unreadCount() {
6697
- return getSubChannelUnreadCount(channelId, messageFeedId);
6698
- },
6699
- get hasMentioned() {
6700
- return getSubChannelIsMentioned(channelId, messageFeedId);
6701
- },
6702
- get isMentioned() {
6703
- return getSubChannelIsMentioned(channelId, messageFeedId);
6704
- } }, rest), { channelId: channelPublicId, creatorId: creatorPublicId, displayName: name, lastActivity: lastMessageTimestamp, latestMessageId: lastMessageId, messageCount: childCount, subChannelId: messageFeedId, isUnreadCountSupport: isUnreadCountSupport$2({ channelType }) });
7709
+ /**
7710
+ * TODO: handle cache receive cache option, and cache policy
7711
+ * TODO: check if querybyIds is supported
7712
+ */
7713
+ class JoinRequestsPaginationController extends PaginationController {
7714
+ async getRequest(queryParams, token) {
7715
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, communityId } = queryParams, params = __rest(queryParams, ["limit", "communityId"]);
7716
+ const options = token ? { token } : { limit };
7717
+ const { data: queryResponse } = await this.http.get(`/api/v4/communities/${communityId}/join`, {
7718
+ params: Object.assign(Object.assign({}, params), { options }),
7719
+ });
7720
+ return queryResponse;
7721
+ }
6705
7722
  }
6706
7723
 
6707
- const mergePayloadWithLocal = (payload) => {
6708
- var _a, _b, _c;
6709
- const localMessage = (_b = (_a = queryCache(['message', 'get'])) === null || _a === void 0 ? void 0 : _a.find(({ data }) => data.messageId === payload.messageId)) === null || _b === void 0 ? void 0 : _b.data;
6710
- if (localMessage) {
6711
- return Object.assign(Object.assign(Object.assign({}, localMessage), payload), {
6712
- // NOTE: referenceId is missing in the some payload event. If we have local message data with referenceId, use it instead.
6713
- referenceId: (_c = localMessage.referenceId) !== null && _c !== void 0 ? _c : payload.referenceId });
7724
+ class QueryStreamController {
7725
+ constructor(query, cacheKey) {
7726
+ this.query = query;
7727
+ this.cacheKey = cacheKey;
6714
7728
  }
6715
- return payload;
6716
- };
6717
- function convertFromRaw$1(message, reactors, event) {
6718
- var _a;
6719
- const mergeMessage = mergePayloadWithLocal(message);
6720
- const { channelPublicId, childCount, creatorPublicId, mentionedUsers, messageFeedId, myReactions, reactionCount, reactions, referenceId, segment, messageId, creatorId } = mergeMessage, rest = __rest(mergeMessage, ["channelPublicId", "childCount", "creatorPublicId", "mentionedUsers", "messageFeedId", "myReactions", "reactionCount", "reactions", "referenceId", "segment", "messageId", "creatorId"]);
6721
- let cache;
6722
- if (referenceId) {
6723
- cache = pullFromCache(['message', 'get', referenceId]);
7729
+ }
7730
+
7731
+ var EnumJoinRequestAction;
7732
+ (function (EnumJoinRequestAction) {
7733
+ EnumJoinRequestAction["OnLocalJoinRequestCreated"] = "OnLocalJoinRequestCreated";
7734
+ EnumJoinRequestAction["OnLocalJoinRequestUpdated"] = "OnLocalJoinRequestUpdated";
7735
+ EnumJoinRequestAction["OnLocalJoinRequestDeleted"] = "OnLocalJoinRequestDeleted";
7736
+ })(EnumJoinRequestAction || (EnumJoinRequestAction = {}));
7737
+
7738
+ class JoinRequestsQueryStreamController extends QueryStreamController {
7739
+ constructor(query, cacheKey, notifyChange, preparePayload) {
7740
+ super(query, cacheKey);
7741
+ this.notifyChange = notifyChange;
7742
+ this.preparePayload = preparePayload;
6724
7743
  }
6725
- if (!cache) {
6726
- cache = pullFromCache(['message', 'get', messageId]);
7744
+ async saveToMainDB(response) {
7745
+ const processedPayload = await this.preparePayload(response);
7746
+ const client = getActiveClient();
7747
+ const cachedAt = client.cache && Date.now();
7748
+ if (client.cache) {
7749
+ ingestInCache(processedPayload, { cachedAt });
7750
+ }
6727
7751
  }
6728
- const out = Object.assign(Object.assign({}, rest), { messageId, channelId: channelPublicId, channelSegment: segment, childrenNumber: childCount, creatorId: creatorPublicId, creatorPrivateId: message.creatorId, reactions: reactions !== null && reactions !== void 0 ? reactions : {},
6729
- /*
6730
- * Previously, myReactions were added only if it was part of the payload.
6731
- * So empty myReactions were not present. So I've edited the payload to add
6732
- * a default for those cases.
6733
- *
6734
- * Check git blame for previous iteration
6735
- */
6736
- myReactions: myReactions || ((_a = cache === null || cache === void 0 ? void 0 : cache.data.myReactions) !== null && _a !== void 0 ? _a : []), reactionsCount: reactionCount, subChannelId: messageFeedId, uniqueId: cache ? cache.data.uniqueId : messageId, referenceId, syncState: "synced" /* Amity.SyncState.Synced */ });
6737
- if (mentionedUsers) {
6738
- out.mentionees = mentionedUsers.map(mention => {
6739
- if (mention.type === 'channel') {
6740
- return mention;
7752
+ appendToQueryStream(response, direction, refresh = false) {
7753
+ var _a, _b;
7754
+ if (refresh) {
7755
+ pushToCache(this.cacheKey, {
7756
+ data: response.joinRequests.map(joinRequest => getResolver('joinRequest')({ joinRequestId: joinRequest._id })),
7757
+ });
7758
+ }
7759
+ else {
7760
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
7761
+ const joinRequests = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
7762
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
7763
+ ...new Set([
7764
+ ...joinRequests,
7765
+ ...response.joinRequests.map(joinRequest => getResolver('joinRequest')({ joinRequestId: joinRequest._id })),
7766
+ ]),
7767
+ ] }));
7768
+ }
7769
+ }
7770
+ reactor(action) {
7771
+ return (joinRequest) => {
7772
+ var _a;
7773
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
7774
+ if (!collection)
7775
+ return;
7776
+ if (action === EnumJoinRequestAction.OnLocalJoinRequestUpdated) {
7777
+ const isExist = collection.data.find(id => id === joinRequest[0].joinRequestId);
7778
+ if (!isExist)
7779
+ return;
6741
7780
  }
6742
- return { type: 'user', userIds: mention.userPublicIds };
6743
- });
7781
+ if (action === EnumJoinRequestAction.OnLocalJoinRequestCreated) {
7782
+ collection.data = [
7783
+ ...new Set([
7784
+ ...joinRequest.map(joinRequest => joinRequest.joinRequestId),
7785
+ ...collection.data,
7786
+ ]),
7787
+ ];
7788
+ }
7789
+ if (action === EnumJoinRequestAction.OnLocalJoinRequestDeleted) {
7790
+ collection.data = collection.data.filter(id => id !== joinRequest[0].joinRequestId);
7791
+ }
7792
+ pushToCache(this.cacheKey, collection);
7793
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
7794
+ };
6744
7795
  }
6745
- if (reactors && reactors.length && event) {
6746
- // mqtt event
6747
- prepareMessagePayloadForCache(out, reactors, event);
7796
+ subscribeRTE(createSubscriber) {
7797
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
6748
7798
  }
6749
- return out;
7799
+ }
7800
+
7801
+ function isObject(value) {
7802
+ return typeof value === 'object' && value !== null;
6750
7803
  }
6751
- const preUpdateMessageCache = (rawPayload) => {
6752
- ingestInCache({
6753
- messages: rawPayload.messages.map(message => convertFromRaw$1(message, rawPayload.reactions)),
7804
+ /**
7805
+ * convert all object getter property to static value
7806
+ */
7807
+ const convertGetterPropsToStatic = (obj) => {
7808
+ if (!isObject(obj)) {
7809
+ return obj;
7810
+ }
7811
+ const entries = Object.entries(obj).map(([key, value]) => {
7812
+ const descriptor = Object.getOwnPropertyDescriptor(obj, key);
7813
+ if (typeof (descriptor === null || descriptor === void 0 ? void 0 : descriptor.get) === 'function') {
7814
+ return [key, descriptor.get.call(obj)];
7815
+ }
7816
+ return [key, value];
6754
7817
  });
7818
+ return Object.fromEntries(entries);
6755
7819
  };
6756
- const DEBOUNCE_TIME = 2000;
6757
- const currentDebounceMap = {};
6758
- const prepareMessagePayload = async (payload, event) => {
6759
- const markerIds = payload.messages.map(({ messageId }) => messageId);
6760
- if (markerIds.length > 0) {
6761
- // since the get markers method requires a channel cache to function with the reducer.
6762
- preUpdateMessageCache(payload);
6763
- const markerIdsKey = markerIds.join('');
6764
- if (currentDebounceMap[markerIdsKey]) {
6765
- clearTimeout(currentDebounceMap[markerIdsKey]);
7820
+ const removeFunctionProperties = (obj) => {
7821
+ if (!isObject(obj)) {
7822
+ return obj;
7823
+ }
7824
+ const entries = Object.entries(obj).map(([key, value]) => {
7825
+ if (typeof value === 'function') {
7826
+ return [key, undefined];
6766
7827
  }
6767
- currentDebounceMap[markerIdsKey] = setTimeout(() => {
6768
- try {
6769
- getMessageMarkers(markerIds);
6770
- }
6771
- catch (_error) {
6772
- // do nothing
6773
- }
6774
- }, DEBOUNCE_TIME);
7828
+ return [key, value];
7829
+ });
7830
+ return Object.fromEntries(entries);
7831
+ };
7832
+
7833
+ class PaginationNoPageController {
7834
+ constructor(queryParams) {
7835
+ const { http } = getActiveClient();
7836
+ this.queryParams = queryParams;
7837
+ this.http = http;
6775
7838
  }
6776
- const { messageFeeds } = payload, restPayload = __rest(payload, ["messageFeeds"]);
6777
- // upsert messageFeeds to subchannel cache because messageFeeds from event payload not include messagePreviewId
6778
- if (messageFeeds && messageFeeds.length > 0) {
6779
- messageFeeds === null || messageFeeds === void 0 ? void 0 : messageFeeds.forEach(messageFeed => {
6780
- var _a, _b;
6781
- const subChannelCache = (_b = (_a = pullFromCache(['subChannel', 'get', messageFeed.messageFeedId])) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {};
6782
- // exclude getter properties from existing subChannel cache, update only other properties to existing subChannel cache
6783
- const _c = convertFromRaw$2(messageFeed), restSubChannel = __rest(_c, ["unreadCount", "isMentioned"]);
6784
- updateSubChannelCache(messageFeed.messageFeedId, subChannelCache, restSubChannel);
6785
- });
7839
+ async onFetch() {
7840
+ const queryResponse = await this.getRequest(this.queryParams);
7841
+ return queryResponse;
6786
7842
  }
6787
- return Object.assign(Object.assign({}, restPayload), { messages: payload.messages.map(m => convertFromRaw$1(m, payload.reactions, event)) });
6788
- };
6789
- function convertParams(_a) {
6790
- var { subChannelId, mentionees, dataType, data } = _a, rest = __rest(_a, ["subChannelId", "mentionees", "dataType", "data"]);
6791
- if (dataType === MessageContentType.IMAGE || dataType === MessageContentType.FILE) {
6792
- return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees, dataType, data: Object.assign({ caption: '' }, data) }, rest);
7843
+ }
7844
+
7845
+ class LiveCollectionController {
7846
+ constructor(paginationController, queryStreamId, cacheKey, callback) {
7847
+ this.paginationController = paginationController;
7848
+ this.queryStreamId = queryStreamId;
7849
+ this.cacheKey = cacheKey;
7850
+ this.callback = callback;
6793
7851
  }
6794
- return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees, dataType, data }, rest);
6795
- }
6796
- function convertQueryParams$1(_a) {
6797
- var { sortBy, subChannelId, includingTags, excludingTags, includeDeleted, aroundMessageId, limit, type } = _a, rest = __rest(_a, ["sortBy", "subChannelId", "includingTags", "excludingTags", "includeDeleted", "aroundMessageId", "limit", "type"]);
6798
- const out = Object.assign(Object.assign({}, rest), { messageFeedId: subChannelId, isDeleted: inferIsDeleted(includeDeleted), options: {
6799
- sortBy,
6800
- limit: limit || COLLECTION_DEFAULT_PAGINATION_LIMIT,
6801
- around: aroundMessageId,
6802
- } });
6803
- if (includingTags) {
6804
- out.includeTags = includingTags;
7852
+ async refresh() {
7853
+ try {
7854
+ let result;
7855
+ if (this.paginationController instanceof PaginationNoPageController) {
7856
+ result = await this.paginationController.onFetch();
7857
+ }
7858
+ else {
7859
+ result = await this.paginationController.loadFirstPage();
7860
+ }
7861
+ if (!result)
7862
+ return;
7863
+ await this.persistModel(result);
7864
+ this.persistQueryStream({
7865
+ response: result,
7866
+ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
7867
+ refresh: true,
7868
+ });
7869
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
7870
+ }
7871
+ catch (e) {
7872
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
7873
+ }
6805
7874
  }
6806
- if (type) {
6807
- out.dataType = type;
7875
+ loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
7876
+ this.setup();
7877
+ this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
7878
+ if (initial) {
7879
+ this.refresh();
7880
+ }
7881
+ else if (direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */) {
7882
+ this.loadPrevPage();
7883
+ }
7884
+ else if (direction === "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
7885
+ this.loadNextPage();
7886
+ }
6808
7887
  }
6809
- if (excludingTags) {
6810
- out.excludeTags = excludingTags;
7888
+ async loadNextPage() {
7889
+ try {
7890
+ if (this.paginationController instanceof PaginationNoPageController)
7891
+ return;
7892
+ const result = await this.paginationController.loadNextPage();
7893
+ if (!result)
7894
+ return;
7895
+ await this.persistModel(result);
7896
+ this.persistQueryStream({
7897
+ response: result,
7898
+ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
7899
+ });
7900
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
7901
+ }
7902
+ catch (e) {
7903
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
7904
+ }
6811
7905
  }
6812
- return out;
6813
- }
6814
-
6815
- const MARKER_INCLUDED_SUB_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
6816
- /**
6817
- * Filter sub channel by type. Only conversation, community and broadcast type are included.
6818
- */
6819
- const isUnreadCountSupport$1 = ({ channelType }) => MARKER_INCLUDED_SUB_CHANNEL_TYPE.includes(channelType);
6820
- const preUpdateSubChannelCache = (rawPayload) => {
6821
- ingestInCache({
6822
- messageFeeds: rawPayload.messageFeeds.map(messageFeed => convertFromRaw$2(messageFeed)),
6823
- });
6824
- };
6825
- const prepareSubChannelPayload = async (rawPayload) => {
6826
- const markerIds = rawPayload.messageFeeds
6827
- .filter(isUnreadCountSupport$1)
6828
- .map(({ messageFeedId }) => messageFeedId);
6829
- if (markerIds.length > 0) {
6830
- // since the get markers method requires a channel cache to function with the reducer.
6831
- preUpdateSubChannelCache(rawPayload);
7906
+ async loadPrevPage() {
6832
7907
  try {
6833
- await getSubChannelMarkers(markerIds);
7908
+ if (this.paginationController instanceof PaginationNoPageController)
7909
+ return;
7910
+ const result = await this.paginationController.loadPreviousPage();
7911
+ if (!result)
7912
+ return;
7913
+ await this.persistModel(result);
7914
+ this.persistQueryStream({
7915
+ response: result,
7916
+ direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */,
7917
+ });
7918
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
6834
7919
  }
6835
7920
  catch (e) {
6836
- // empty block (from the spec, allow marker fetch to fail without having to do anything)
7921
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
6837
7922
  }
6838
7923
  }
6839
- updateSubChannelMessagePreviewCache(rawPayload);
6840
- // attach marker to sub channel
6841
- const messageFeeds = rawPayload.messageFeeds.map(convertFromRaw$2);
6842
- const messages = rawPayload.messages.map(m => convertFromRaw$1(m));
6843
- return Object.assign(Object.assign({}, rawPayload), { messageFeeds,
6844
- messages });
6845
- };
6846
- function convertQueryParams(_a) {
6847
- var { excludeDefaultSubChannel } = _a, rest = __rest(_a, ["excludeDefaultSubChannel"]);
6848
- const out = Object.assign({}, rest);
6849
- if (excludeDefaultSubChannel !== undefined) {
6850
- out.excludeDefaultMessageFeed = excludeDefaultSubChannel;
7924
+ shouldNotify(data) {
7925
+ const newData = data.map(convertGetterPropsToStatic).map(removeFunctionProperties);
7926
+ if (isEqual(this.snapshot, newData))
7927
+ return false;
7928
+ this.snapshot = newData;
7929
+ return true;
7930
+ }
7931
+ getCacheKey() {
7932
+ return this.cacheKey;
6851
7933
  }
6852
- return out;
6853
7934
  }
6854
7935
 
6855
7936
  /**
6856
7937
  * ```js
6857
- * import { getSubChannel } from '@amityco/ts-sdk'
6858
- * const subChannel = await getSubChannel('foobar')
7938
+ * import { onJoinRequestCreated } from '@amityco/ts-sdk'
7939
+ * const dispose = onJoinRequestCreated(data => {
7940
+ * // ...
7941
+ * })
7942
+ * ```
7943
+ *
7944
+ * Fired when an {@link Amity.CommunityJoinRequestPayload} has been created
7945
+ *
7946
+ * @param callback The function to call when the event was fired
7947
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
7948
+ *
7949
+ * @category JoinRequest Events
7950
+ */
7951
+ const onJoinRequestCreated = (callback) => {
7952
+ const client = getActiveClient();
7953
+ const disposers = [
7954
+ createEventSubscriber(client, 'onJoinRequestCreated', 'local.joinRequest.created', payload => callback(payload)),
7955
+ ];
7956
+ return () => {
7957
+ disposers.forEach(fn => fn());
7958
+ };
7959
+ };
7960
+
7961
+ /**
7962
+ * ```js
7963
+ * import { onJoinRequestUpdated } from '@amityco/ts-sdk'
7964
+ * const dispose = onJoinRequestUpdated(data => {
7965
+ * // ...
7966
+ * })
6859
7967
  * ```
6860
7968
  *
6861
- * Fetches a {@link Amity.SubChannel} object
7969
+ * Fired when an {@link Amity.CommunityJoinRequestPayload} has been created
6862
7970
  *
6863
- * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
6864
- * @returns the associated {@link Amity.SubChannel} object
7971
+ * @param callback The function to call when the event was fired
7972
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
6865
7973
  *
6866
- * @category Channel API
6867
- * @async
7974
+ * @category JoinRequest Events
6868
7975
  */
6869
- const getSubChannel$1 = async (subChannelId) => {
7976
+ const onJoinRequestUpdated = (callback) => {
6870
7977
  const client = getActiveClient();
6871
- client.log('channel/getSubChannel', subChannelId);
6872
- isInTombstone('subChannel', subChannelId);
6873
- try {
6874
- const response = await client.http.get(`/api/v5/message-feeds/${encodeURIComponent(subChannelId)}`);
6875
- const data = await prepareSubChannelPayload(response.data);
6876
- const cachedAt = client.cache && Date.now();
6877
- if (client.cache)
6878
- ingestInCache(data, { cachedAt });
6879
- fireEvent('local.message-feed.fetched', data);
6880
- return {
6881
- data: data.messageFeeds[0],
6882
- cachedAt,
6883
- };
6884
- }
6885
- catch (error) {
6886
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
6887
- pushToTombstone('subChannel', subChannelId);
6888
- }
6889
- throw error;
6890
- }
6891
- };
7978
+ const disposers = [
7979
+ createEventSubscriber(client, 'onJoinRequestUpdated', 'local.joinRequest.updated', payload => callback(payload)),
7980
+ ];
7981
+ return () => {
7982
+ disposers.forEach(fn => fn());
7983
+ };
7984
+ };
7985
+
6892
7986
  /**
6893
7987
  * ```js
6894
- * import { getSubChannel } from '@amityco/ts-sdk'
6895
- * const subChannel = getSubChannel.locally('foobar')
7988
+ * import { onJoinRequestDeleted } from '@amityco/ts-sdk'
7989
+ * const dispose = onJoinRequestDeleted(data => {
7990
+ * // ...
7991
+ * })
6896
7992
  * ```
6897
7993
  *
6898
- * Fetches a {@link Amity.SubChannel} object from cache
7994
+ * Fired when an {@link Amity.CommunityJoinRequestPayload} has been created
6899
7995
  *
6900
- * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
6901
- * @returns the associated {@link Amity.SubChannel} object
7996
+ * @param callback The function to call when the event was fired
7997
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
6902
7998
  *
6903
- * @category Channel API
7999
+ * @category JoinRequest Events
6904
8000
  */
6905
- getSubChannel$1.locally = (subChannelId) => {
8001
+ const onJoinRequestDeleted = (callback) => {
6906
8002
  const client = getActiveClient();
6907
- client.log('channel/getSubChannel.locally', subChannelId);
6908
- if (!client.cache)
6909
- return;
6910
- const cached = pullFromCache(['subChannel', 'get', subChannelId]);
6911
- if (!cached)
6912
- return;
6913
- return {
6914
- data: cached.data,
6915
- cachedAt: cached.cachedAt,
8003
+ const disposers = [
8004
+ createEventSubscriber(client, 'onJoinRequestDeleted', 'local.joinRequest.deleted', payload => callback(payload)),
8005
+ ];
8006
+ return () => {
8007
+ disposers.forEach(fn => fn());
6916
8008
  };
6917
8009
  };
6918
8010
 
6919
- const convertDateStringToTimestamp = (dateString) => {
6920
- return new Date(dateString).getTime();
6921
- };
6922
-
6923
- const getMessagePreviewSetting$1 = async () => {
6924
- const client = getActiveClient();
6925
- return client.getMessagePreviewSetting(false);
6926
- };
6927
- const getSubChannelCache = async (subChannelId) => {
6928
- var _a;
6929
- let subChannelCache = (_a = pullFromCache(['subChannel', 'get', subChannelId])) === null || _a === void 0 ? void 0 : _a.data;
6930
- if (!subChannelCache) {
6931
- subChannelCache = (await getSubChannel$1(subChannelId)).data;
8011
+ class JoinRequestsLiveCollectionController extends LiveCollectionController {
8012
+ constructor(query, callback) {
8013
+ const queryStreamId = hash__default["default"](query);
8014
+ const cacheKey = ['joinRequest', 'collection', queryStreamId];
8015
+ const paginationController = new JoinRequestsPaginationController(query);
8016
+ super(paginationController, queryStreamId, cacheKey, callback);
8017
+ this.query = query;
8018
+ this.queryStreamController = new JoinRequestsQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityJoinRequestPayload);
8019
+ this.callback = callback.bind(this);
8020
+ this.loadPage({ initial: true });
6932
8021
  }
6933
- return subChannelCache;
6934
- };
6935
- const isLastestMessageOnSubchannel = (message) => {
6936
- var _a;
6937
- const cache = (_a = pullFromCache([
6938
- 'messagePreviewSubChannel',
6939
- 'get',
6940
- message.subChannelId,
6941
- ])) === null || _a === void 0 ? void 0 : _a.data;
6942
- // The message payload from optimistic created event has no segment, so we check createdAt instead.
6943
- return (!cache ||
6944
- cache.segment <= message.channelSegment ||
6945
- convertDateStringToTimestamp(cache.createdAt) <= convertDateStringToTimestamp(message.createdAt));
6946
- };
6947
- const isLastestMessageOnChannel = (message) => {
6948
- var _a;
6949
- const cache = (_a = pullFromCache([
6950
- 'messagePreviewChannel',
6951
- 'get',
6952
- message.channelId,
6953
- ])) === null || _a === void 0 ? void 0 : _a.data;
6954
- return (!cache ||
6955
- convertDateStringToTimestamp(cache.createdAt) <= convertDateStringToTimestamp(message.createdAt));
6956
- };
6957
- const handleMessageCreatedOnSubChannel = async (message) => {
6958
- const messagePreviewSetting = await getMessagePreviewSetting$1();
6959
- const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
6960
- // 1. get subChannel from cache, if not exist fetch from server
6961
- const subChannelCache = await getSubChannelCache(subChannelId);
6962
- // 2. if messagePreviewSetting is NO_MESSAGE_PREVEIW, update only lastActiviy in subChannel cache
6963
- if (messagePreviewSetting === "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */) {
6964
- // 2.1 if the message is the latest message, update lastActivity to be createdAt in subChannel cache
6965
- if (convertDateStringToTimestamp(subChannelCache.lastActivity) <
6966
- convertDateStringToTimestamp(createdAt))
6967
- updateSubChannelCache(message.subChannelId, subChannelCache, {
6968
- lastActivity: createdAt,
8022
+ setup() {
8023
+ var _a;
8024
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
8025
+ if (!collection) {
8026
+ pushToCache(this.cacheKey, {
8027
+ data: [],
8028
+ params: this.query,
6969
8029
  });
6970
- return;
8030
+ }
6971
8031
  }
6972
- // 3. if messagePreviewSetting is `NOT` NO_MESSAGE_PREVEIW, update messagePreviewSubChannel and subChannel cache
6973
- // 3.1 check if the message is the latest message, if not ignore the message.
6974
- if (!isLastestMessageOnSubchannel(message))
6975
- return;
6976
- // 3.2 if the message is the latest message, update messagePreviewSubChannel and subChannel cache
6977
- pushToCache(['messagePreviewSubChannel', 'get', message.subChannelId], {
6978
- channelId,
6979
- creatorId,
6980
- messagePreviewId,
6981
- createdAt,
6982
- updatedAt,
6983
- subChannelId,
6984
- data,
6985
- dataType,
6986
- segment,
6987
- isDeleted,
6988
- subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt,
6989
- subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName,
6990
- });
6991
- updateSubChannelCache(message.subChannelId, subChannelCache, {
6992
- lastActivity: createdAt,
6993
- messagePreviewId,
6994
- });
6995
- };
6996
- const handleMessageUpdatedOnSubChannel = async (message) => {
6997
- var _a;
6998
- const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
6999
- const messagePreviewSubChannelCache = (_a = pullFromCache([
7000
- 'messagePreviewSubChannel',
7001
- 'get',
7002
- message.subChannelId,
7003
- ])) === null || _a === void 0 ? void 0 : _a.data;
7004
- // if messagePreviewSubChannel is not exist, ignore the message.
7005
- if (messagePreviewSubChannelCache &&
7006
- messagePreviewSubChannelCache.messagePreviewId === message.messageId) {
7007
- const subChannelCache = await getSubChannelCache(subChannelId);
7008
- pushToCache(['messagePreviewSubChannel', 'get', message.subChannelId], {
7009
- channelId,
7010
- creatorId,
7011
- messagePreviewId,
7012
- createdAt,
7013
- updatedAt,
7014
- subChannelId,
7015
- data,
7016
- dataType,
7017
- segment,
7018
- isDeleted,
7019
- subChannelUpdatedAt: subChannelCache.updatedAt,
7020
- subChannelName: messagePreviewSubChannelCache.subChannelName,
7021
- });
8032
+ async persistModel(queryPayload) {
8033
+ await this.queryStreamController.saveToMainDB(queryPayload);
7022
8034
  }
7023
- };
7024
- const handleMessageCreated = async (message) => {
7025
- const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
7026
- if (isLastestMessageOnChannel(message)) {
7027
- const subChannelCache = await getSubChannelCache(subChannelId);
7028
- pushToCache(['messagePreviewChannel', 'get', message.channelId], {
7029
- channelId,
7030
- creatorId,
7031
- messagePreviewId,
7032
- createdAt,
7033
- updatedAt,
7034
- subChannelId,
8035
+ persistQueryStream({ response, direction, refresh, }) {
8036
+ const joinRequestResponse = response;
8037
+ this.queryStreamController.appendToQueryStream(joinRequestResponse, direction, refresh);
8038
+ }
8039
+ startSubscription() {
8040
+ return this.queryStreamController.subscribeRTE([
8041
+ { fn: onJoinRequestCreated, action: EnumJoinRequestAction.OnLocalJoinRequestCreated },
8042
+ { fn: onJoinRequestUpdated, action: EnumJoinRequestAction.OnLocalJoinRequestUpdated },
8043
+ { fn: onJoinRequestDeleted, action: EnumJoinRequestAction.OnLocalJoinRequestDeleted },
8044
+ ]);
8045
+ }
8046
+ notifyChange({ origin, loading, error }) {
8047
+ var _a;
8048
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
8049
+ if (!collection)
8050
+ return;
8051
+ const data = this.applyFilter(collection.data
8052
+ .map(id => pullFromCache(['joinRequest', 'get', id]))
8053
+ .filter(isNonNullable)
8054
+ .map(({ data }) => data)
8055
+ .map(joinRequestLinkedObject));
8056
+ if (!this.shouldNotify(data) && origin === 'event')
8057
+ return;
8058
+ this.callback({
8059
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
7035
8060
  data,
7036
- dataType,
7037
- segment,
7038
- isDeleted,
7039
- subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt,
7040
- subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName,
8061
+ hasNextPage: !!this.paginationController.getNextToken(),
8062
+ loading,
8063
+ error,
7041
8064
  });
7042
8065
  }
8066
+ applyFilter(data) {
8067
+ let joinRequest = data;
8068
+ if (this.query.status) {
8069
+ joinRequest = joinRequest.filter(joinRequest => joinRequest.status === this.query.status);
8070
+ }
8071
+ const sortFn = (() => {
8072
+ switch (this.query.sortBy) {
8073
+ case 'firstCreated':
8074
+ return sortByFirstCreated;
8075
+ case 'lastCreated':
8076
+ return sortByLastCreated;
8077
+ default:
8078
+ return sortByLastCreated;
8079
+ }
8080
+ })();
8081
+ joinRequest = joinRequest.sort(sortFn);
8082
+ return joinRequest;
8083
+ }
8084
+ }
8085
+
8086
+ /**
8087
+ * Get Join Requests
8088
+ *
8089
+ * @param params the query parameters
8090
+ * @param callback the callback to be called when the join request are updated
8091
+ * @returns joinRequests
8092
+ *
8093
+ * @category joinRequest Live Collection
8094
+ *
8095
+ */
8096
+ const getJoinRequests = (params, callback, config) => {
8097
+ const { log, cache } = getActiveClient();
8098
+ if (!cache) {
8099
+ console.log(ENABLE_CACHE_MESSAGE);
8100
+ }
8101
+ const timestamp = Date.now();
8102
+ log(`getJoinRequests: (tmpid: ${timestamp}) > listen`);
8103
+ const joinRequestLiveCollection = new JoinRequestsLiveCollectionController(params, callback);
8104
+ const disposers = joinRequestLiveCollection.startSubscription();
8105
+ const cacheKey = joinRequestLiveCollection.getCacheKey();
8106
+ disposers.push(() => {
8107
+ dropFromCache(cacheKey);
8108
+ });
8109
+ return () => {
8110
+ log(`getJoinRequests (tmpid: ${timestamp}) > dispose`);
8111
+ disposers.forEach(fn => fn());
8112
+ };
8113
+ };
8114
+
8115
+ const convertRawInvitationToInternalInvitation = (rawInvitation) => {
8116
+ return Object.assign(Object.assign({}, rawInvitation), { createdById: rawInvitation.createdBy });
8117
+ };
8118
+
8119
+ const prepareInvitationPayload = (rawPayload) => {
8120
+ return Object.assign(Object.assign({}, rawPayload), { invitations: rawPayload.invitations.map(convertRawInvitationToInternalInvitation), users: rawPayload.users.map(convertRawUserToInternalUser) });
8121
+ };
8122
+
8123
+ /* begin_public_function
8124
+ id: invitation.createInvitations
8125
+ */
8126
+ /**
8127
+ * ```js
8128
+ * import { createInvitations } from '@amityco/ts-sdk'
8129
+ * const created = await createInvitations({
8130
+ * type: string,
8131
+ * targetType: string,
8132
+ * targetId: string,
8133
+ * userIds: string[]
8134
+ * }))
8135
+ * ```
8136
+ *
8137
+ * Creates an {@link Amity.Invitation}
8138
+ *
8139
+ * @param bundle The data necessary to create a new {@link Amity.Invitation}
8140
+ * @returns The newly created {@link Amity.Invitation}
8141
+ *
8142
+ * @category Invitation API
8143
+ * @async
8144
+ */
8145
+ const createInvitations = async (bundle) => {
8146
+ const client = getActiveClient();
8147
+ client.log('invitation/createInvitations', bundle);
8148
+ const { data: payload } = await client.http.post('/api/v1/invitations', bundle);
8149
+ const data = prepareInvitationPayload(payload);
8150
+ const cachedAt = client.cache && Date.now();
8151
+ if (client.cache)
8152
+ ingestInCache(data, { cachedAt });
8153
+ fireEvent('local.invitation.created', data.invitations);
8154
+ return {
8155
+ data: data.invitations,
8156
+ cachedAt,
8157
+ };
7043
8158
  };
7044
- const handleMessageUpdated = async (message) => {
7045
- /**
7046
- * Channel Case
7047
- */
8159
+ /* end_public_function */
8160
+
8161
+ /* begin_public_function
8162
+ id: invitation.accept
8163
+ */
8164
+ /**
8165
+ * ```js
8166
+ * import { acceptInvitation } from '@amityco/ts-sdk'
8167
+ * const isAccepted = await acceptInvitation(invitationId)
8168
+ * ```
8169
+ *
8170
+ * Accepts a {@link Amity.Invitation} object
8171
+ *
8172
+ * @param invitationId the {@link Amity.Invitation} to accept
8173
+ * @returns A success boolean if the {@link Amity.Invitation} was accepted
8174
+ *
8175
+ * @category Invitation API
8176
+ * @async
8177
+ */
8178
+ const acceptInvitation = async (invitationId) => {
7048
8179
  var _a;
7049
- const { channelId, messageId: messagePreviewId, creatorId, createdAt, updatedAt, data, dataType, subChannelId, channelSegment: segment, isDeleted, } = message;
7050
- const messagePreviewChannelCache = (_a = pullFromCache([
7051
- 'messagePreviewChannel',
8180
+ const client = getActiveClient();
8181
+ client.log('invitation/acceptInvitation', invitationId);
8182
+ const { data } = await client.http.post(`/api/v1/invitations/${invitationId}/accept`);
8183
+ const invitation = (_a = pullFromCache([
8184
+ 'invitation',
7052
8185
  'get',
7053
- message.channelId,
8186
+ invitationId,
7054
8187
  ])) === null || _a === void 0 ? void 0 : _a.data;
7055
- if (messagePreviewChannelCache &&
7056
- messagePreviewChannelCache.messagePreviewId === message.messageId) {
7057
- const subChannelCache = await getSubChannelCache(subChannelId);
7058
- pushToCache(['messagePreviewChannel', 'get', message.channelId], {
7059
- channelId,
7060
- creatorId,
7061
- messagePreviewId,
7062
- createdAt,
7063
- updatedAt,
7064
- subChannelId,
7065
- data,
7066
- dataType,
7067
- segment,
7068
- isDeleted,
7069
- subChannelUpdatedAt: subChannelCache.updatedAt,
7070
- subChannelName: messagePreviewChannelCache.subChannelName,
7071
- });
8188
+ if (invitation) {
8189
+ upsertInCache(['invitation', 'get', invitationId], { status: "approved" /* InvitationStatusEnum.Approved */ });
8190
+ fireEvent('local.invitation.updated', [invitation]);
7072
8191
  }
8192
+ return data.success;
7073
8193
  };
7074
- const handleSubChannelUpdated = async (subChannel) => {
7075
- var _a, _b, _c, _d;
7076
- const { channelId, subChannelId } = subChannel;
7077
- /** Channel Case */
7078
- const messagePreviewChannelCache = (_a = pullFromCache([
7079
- 'messagePreviewChannel',
8194
+ /* end_public_function */
8195
+
8196
+ /* begin_public_function
8197
+ id: invitation.reject
8198
+ */
8199
+ /**
8200
+ * ```js
8201
+ * import { rejectInvitation } from '@amityco/ts-sdk'
8202
+ * const isRejected = await rejectInvitation(invitationId)
8203
+ * ```
8204
+ *
8205
+ * Rejects a {@link Amity.Invitation} object
8206
+ *
8207
+ * @param invitationId the {@link Amity.Invitation} to reject
8208
+ * @returns A success boolean if the {@link Amity.Invitation} was rejected
8209
+ *
8210
+ * @category Invitation API
8211
+ * @async
8212
+ */
8213
+ const rejectInvitation = async (invitationId) => {
8214
+ var _a;
8215
+ const client = getActiveClient();
8216
+ client.log('invitation/rejectInvitation', invitationId);
8217
+ const { data } = await client.http.post(`/api/v1/invitations/${invitationId}/reject`);
8218
+ const invitation = (_a = pullFromCache([
8219
+ 'invitation',
7080
8220
  'get',
7081
- channelId,
8221
+ invitationId,
7082
8222
  ])) === null || _a === void 0 ? void 0 : _a.data;
7083
- if ((messagePreviewChannelCache === null || messagePreviewChannelCache === void 0 ? void 0 : messagePreviewChannelCache.subChannelId) === subChannelId) {
7084
- const subChannelCache = (_b = pullFromCache([
7085
- 'subChannel',
7086
- 'get',
7087
- subChannelId,
7088
- ])) === null || _b === void 0 ? void 0 : _b.data;
7089
- pushToCache(['messagePreviewChannel', 'get', channelId], Object.assign(Object.assign({}, messagePreviewChannelCache), { subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName, subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt }));
7090
- }
7091
- /** SubChannel Case */
7092
- const messagePreviewSubChannelCache = (_c = pullFromCache([
7093
- 'messagePreviewSubChannel',
7094
- 'get',
7095
- subChannelId,
7096
- ])) === null || _c === void 0 ? void 0 : _c.data;
7097
- if (messagePreviewSubChannelCache &&
7098
- new Date(messagePreviewSubChannelCache.updatedAt).valueOf() >
7099
- new Date(subChannel.updatedAt).valueOf()) {
7100
- const subChannelCache = (_d = pullFromCache([
7101
- 'subChannel',
7102
- 'get',
7103
- subChannelId,
7104
- ])) === null || _d === void 0 ? void 0 : _d.data;
7105
- pushToCache(['messagePreviewSubChannel', 'get', subChannelId], Object.assign(Object.assign({}, messagePreviewSubChannelCache), { subChannelName: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.displayName, subChannelUpdatedAt: subChannelCache === null || subChannelCache === void 0 ? void 0 : subChannelCache.updatedAt }));
8223
+ if (invitation) {
8224
+ upsertInCache(['invitation', 'get', invitationId], { status: "rejected" /* InvitationStatusEnum.Rejected */ });
8225
+ fireEvent('local.invitation.updated', [invitation]);
7106
8226
  }
7107
- };
7108
-
7109
- function convertRawUserToInternalUser(rawUser) {
7110
- return Object.assign(Object.assign({}, rawUser), { isGlobalBanned: (rawUser === null || rawUser === void 0 ? void 0 : rawUser.isGlobalBan) || false });
7111
- }
8227
+ return data.success;
8228
+ };
8229
+ /* end_public_function */
7112
8230
 
7113
- const MARKER_INCLUDED_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
7114
- const isUnreadCountSupport = ({ type }) => MARKER_INCLUDED_CHANNEL_TYPE.includes(type);
7115
- function convertFromRaw(channel, options = { isMessagePreviewUpdated: true }) {
8231
+ /* begin_public_function
8232
+ id: invitation.cancel
8233
+ */
8234
+ /**
8235
+ * ```js
8236
+ * import { cancelInvitation } from '@amityco/ts-sdk'
8237
+ * const isCanceled = await cancelInvitation(invitationId)
8238
+ * ```
8239
+ *
8240
+ * Cancels a {@link Amity.Invitation} object
8241
+ *
8242
+ * @param invitationId the {@link Amity.Invitation} to cancel
8243
+ * @returns A success boolean if the {@link Amity.Invitation} was canceled
8244
+ *
8245
+ * @category Invitation API
8246
+ * @async
8247
+ */
8248
+ const cancelInvitation = async (invitationId) => {
7116
8249
  var _a;
7117
- let { messagePreviewId } = channel;
7118
- const messagePreviewChannelCache = (_a = pullFromCache([
7119
- 'messagePreviewChannel',
8250
+ const client = getActiveClient();
8251
+ client.log('invitation/cancelInvitation', invitationId);
8252
+ const { data } = await client.http.delete(`/api/v1/invitations/${invitationId}`);
8253
+ const invitation = (_a = pullFromCache([
8254
+ 'invitation',
7120
8255
  'get',
7121
- channel.channelId,
8256
+ invitationId,
7122
8257
  ])) === null || _a === void 0 ? void 0 : _a.data;
7123
- if ((messagePreviewChannelCache === null || messagePreviewChannelCache === void 0 ? void 0 : messagePreviewChannelCache.messagePreviewId) && !options.isMessagePreviewUpdated) {
7124
- messagePreviewId = messagePreviewChannelCache.messagePreviewId;
7125
- }
7126
- return Object.assign(Object.assign({}, channel), { defaultSubChannelId: channel.channelInternalId, isUnreadCountSupport: isUnreadCountSupport(channel), messagePreviewId });
7127
- }
7128
- const preUpdateChannelCache = (rawPayload, options = { isMessagePreviewUpdated: true }) => {
7129
- ingestInCache({
7130
- channels: rawPayload.channels.map(channel => convertFromRaw(channel, { isMessagePreviewUpdated: options.isMessagePreviewUpdated })),
7131
- });
7132
- };
7133
- const updateChannelUnread = ({ currentUserId, channels, channelUsers, }) => {
7134
- for (let i = 0; i < channels.length; i += 1) {
7135
- const cacheKey = ['channelUnread', 'get', channels[i].channelId];
7136
- const channelUser = channelUsers.find(channelUser => channelUser.channelId === channels[i].channelId && channelUser.userId === currentUserId);
7137
- let unreadCount = 0;
7138
- let readToSegment = null;
7139
- let lastMentionedSegment = null;
7140
- let isMentioned = false;
7141
- if (channelUser) {
7142
- readToSegment = channelUser.readToSegment;
7143
- lastMentionedSegment = channelUser.lastMentionedSegment;
7144
- unreadCount = Math.max(channels[i].messageCount - readToSegment, 0);
7145
- isMentioned = lastMentionedSegment > readToSegment;
7146
- }
7147
- const cacheChannelUnread = {
7148
- channelId: channels[i].channelId,
7149
- lastSegment: channels[i].messageCount,
7150
- readToSegment,
7151
- lastMentionedSegment,
7152
- unreadCount,
7153
- isMentioned,
7154
- isDeleted: channels[i].isDeleted || false,
7155
- };
7156
- pushToCache(cacheKey, cacheChannelUnread);
8258
+ if (invitation) {
8259
+ dropFromCache(['invitation', 'get', invitationId]);
8260
+ fireEvent('local.invitation.deleted', [invitation]);
7157
8261
  }
8262
+ return data.success;
7158
8263
  };
7159
- const prepareChannelPayload = async (rawPayload, options = { isMessagePreviewUpdated: true }) => {
8264
+ /* end_public_function */
8265
+
8266
+ const prepareMyInvitationsPayload = (rawPayload) => {
8267
+ return Object.assign(Object.assign({}, rawPayload), { users: rawPayload.users.map(convertRawUserToInternalUser), invitations: rawPayload.invitations.map(convertRawInvitationToInternalInvitation) });
8268
+ };
8269
+
8270
+ const invitationLinkedObject = (invitation) => {
8271
+ return Object.assign(Object.assign({}, invitation), { get user() {
8272
+ const cacheData = pullFromCache(['user', 'get', invitation.invitedUserPublicId]);
8273
+ if (cacheData === null || cacheData === void 0 ? void 0 : cacheData.data)
8274
+ return userLinkedObject(cacheData.data);
8275
+ return undefined;
8276
+ },
8277
+ get createdBy() {
8278
+ const cacheData = pullFromCache(['user', 'get', invitation.inviterUserPublicId]);
8279
+ if (cacheData === null || cacheData === void 0 ? void 0 : cacheData.data)
8280
+ return userLinkedObject(cacheData.data);
8281
+ return undefined;
8282
+ },
8283
+ get target() {
8284
+ if (invitation.targetType === 'community') {
8285
+ const cacheData = pullFromCache([
8286
+ 'community',
8287
+ 'get',
8288
+ invitation.targetId,
8289
+ ]);
8290
+ if (cacheData === null || cacheData === void 0 ? void 0 : cacheData.data)
8291
+ return cacheData.data;
8292
+ return undefined;
8293
+ }
8294
+ return undefined;
8295
+ }, accept: async () => {
8296
+ await acceptInvitation(invitation._id);
8297
+ }, reject: async () => {
8298
+ await rejectInvitation(invitation._id);
8299
+ }, cancel: async () => {
8300
+ await cancelInvitation(invitation._id);
8301
+ } });
8302
+ };
8303
+
8304
+ /* begin_public_function
8305
+ id: invitation.get
8306
+ */
8307
+ /**
8308
+ * ```js
8309
+ * import { getInvitation } from '@amityco/ts-sdk'
8310
+ * const { invitation } = await getInvitation(targetType, targetId)
8311
+ * ```
8312
+ *
8313
+ * Get a {@link Amity.Invitation} object
8314
+ *
8315
+ * @param targetType The type of the target of the {@link Amity.Invitation}
8316
+ * @param targetId The ID of the target of the {@link Amity.Invitation}
8317
+ * @returns A {@link Amity.Invitation} object
8318
+ *
8319
+ * @category Invitation API
8320
+ * @async
8321
+ */
8322
+ const getInvitation = async (targetType, targetId) => {
7160
8323
  const client = getActiveClient();
7161
- const networkPreviewSetting = await client.getMessagePreviewSetting(false);
7162
- if (options.isMessagePreviewUpdated &&
7163
- networkPreviewSetting !== "no-message-preview" /* Amity.MessagePreviewSetting.NO_MESSAGE_PREVIEW */ &&
7164
- rawPayload.messagePreviews &&
7165
- rawPayload.messagePreviews.length > 0) {
7166
- updateChannelMessagePreviewCache(rawPayload);
8324
+ client.log('invitation/getInvitation', targetType, targetId);
8325
+ const { data: payload } = await client.http.get(`/api/v1/invitations/me`, { params: { targetType, targetId } });
8326
+ const data = prepareMyInvitationsPayload(payload);
8327
+ const cachedAt = client.cache && Date.now();
8328
+ if (client.cache)
8329
+ ingestInCache(data, { cachedAt });
8330
+ return {
8331
+ data: data.invitations[0] ? invitationLinkedObject(data.invitations[0]) : undefined,
8332
+ cachedAt,
8333
+ };
8334
+ };
8335
+ /* end_public_function */
8336
+
8337
+ var InvitationActionsEnum;
8338
+ (function (InvitationActionsEnum) {
8339
+ InvitationActionsEnum["OnLocalInvitationCreated"] = "onLocalInvitationCreated";
8340
+ InvitationActionsEnum["OnLocalInvitationUpdated"] = "onLocalInvitationUpdated";
8341
+ InvitationActionsEnum["OnLocalInvitationDeleted"] = "onLocalInvitationDeleted";
8342
+ })(InvitationActionsEnum || (InvitationActionsEnum = {}));
8343
+
8344
+ class InvitationsPaginationController extends PaginationController {
8345
+ async getRequest(queryParams, token) {
8346
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
8347
+ const options = token ? { token } : { limit };
8348
+ const { data } = await this.http.get('/api/v1/invitations', { params: Object.assign(Object.assign({}, params), { options }) });
8349
+ return data;
7167
8350
  }
7168
- if (client.useLegacyUnreadCount) {
7169
- updateChannelUnread({
7170
- channels: rawPayload.channels,
7171
- channelUsers: rawPayload.channelUsers,
7172
- currentUserId: client.userId,
7173
- });
8351
+ }
8352
+
8353
+ class InvitationsQueryStreamController extends QueryStreamController {
8354
+ constructor(query, cacheKey, notifyChange, preparePayload) {
8355
+ super(query, cacheKey);
8356
+ this.notifyChange = notifyChange;
8357
+ this.preparePayload = preparePayload;
7174
8358
  }
7175
- else {
7176
- const markerIds = rawPayload.channels
7177
- // filter channel by type. Only conversation, community and broadcast type are included.
7178
- .filter(isUnreadCountSupport)
7179
- .map(({ channelInternalId }) => channelInternalId);
7180
- if (markerIds.length > 0) {
7181
- // since the get markers method requires a channel cache to function with the reducer.
7182
- preUpdateChannelCache(rawPayload, {
7183
- isMessagePreviewUpdated: options.isMessagePreviewUpdated,
8359
+ async saveToMainDB(response) {
8360
+ const processedPayload = await this.preparePayload(response);
8361
+ const client = getActiveClient();
8362
+ const cachedAt = client.cache && Date.now();
8363
+ if (client.cache) {
8364
+ ingestInCache(processedPayload, { cachedAt });
8365
+ }
8366
+ }
8367
+ appendToQueryStream(response, direction, refresh = false) {
8368
+ var _a, _b;
8369
+ if (refresh) {
8370
+ pushToCache(this.cacheKey, {
8371
+ data: response.invitations.map(getResolver('invitation')),
7184
8372
  });
7185
- try {
7186
- await getChannelMarkers(markerIds);
8373
+ }
8374
+ else {
8375
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
8376
+ const invitations = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
8377
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
8378
+ ...new Set([...invitations, ...response.invitations.map(getResolver('invitation'))]),
8379
+ ] }));
8380
+ }
8381
+ }
8382
+ reactor(action) {
8383
+ return (invitations) => {
8384
+ var _a;
8385
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
8386
+ if (!collection)
8387
+ return;
8388
+ if (action === InvitationActionsEnum.OnLocalInvitationUpdated) {
8389
+ const isExist = collection.data.find(id => id === invitations[0].invitationId);
8390
+ if (!isExist)
8391
+ return;
7187
8392
  }
7188
- catch (e) {
7189
- // empty block (from the spec, allow marker fetch to fail without having to do anything)
8393
+ if (action === InvitationActionsEnum.OnLocalInvitationCreated) {
8394
+ collection.data = [
8395
+ ...new Set([
8396
+ ...invitations.map(invitation => invitation.invitationId),
8397
+ ...collection.data,
8398
+ ]),
8399
+ ];
7190
8400
  }
7191
- }
8401
+ if (action === InvitationActionsEnum.OnLocalInvitationDeleted) {
8402
+ collection.data = collection.data.filter(id => id !== invitations[0].invitationId);
8403
+ }
8404
+ pushToCache(this.cacheKey, collection);
8405
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
8406
+ };
7192
8407
  }
7193
- // convert raw channel to internal channel
7194
- const channels = rawPayload.channels.map(payload => convertFromRaw(payload, { isMessagePreviewUpdated: options.isMessagePreviewUpdated }));
7195
- // convert raw channel user to membership (add user object)
7196
- const channelUsers = rawPayload.channelUsers.map(channelUser => {
7197
- return convertRawMembershipToMembership(channelUser);
7198
- });
7199
- const users = rawPayload.users.map(convertRawUserToInternalUser);
7200
- const restRawPayload = __rest(rawPayload, ["messageFeedsInfo", "messagePreviews"]);
7201
- return Object.assign(Object.assign({}, restRawPayload), { users,
7202
- channels,
7203
- channelUsers });
7204
- };
8408
+ subscribeRTE(createSubscriber) {
8409
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
8410
+ }
8411
+ }
7205
8412
 
7206
8413
  /**
7207
8414
  * ```js
7208
- * import { getSubChannelMarkers } from '@amityco/ts-sdk'
7209
- * const subChannelMarkers = await getSubChannelMarkers(['sch1', 'sch2'])
8415
+ * import { onLocalInvitationCreated } from '@amityco/ts-sdk'
8416
+ * const dispose = onLocalInvitationCreated(data => {
8417
+ * // ...
8418
+ * })
7210
8419
  * ```
7211
8420
  *
7212
- * Fetches a paginable list of {@link Amity.SubChannelMarker} objects
8421
+ * Fired when an {@link Amity.InvitationPayload} has been created
7213
8422
  *
7214
- * @param messageFeedIds the feed IDs of the {@link Amity.RawSubChannel} marker to fetch
7215
- * @param page
7216
- * @returns A page of {@link Amity.SubChannelMarker} objects
8423
+ * @param callback The function to call when the event was fired
8424
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
7217
8425
  *
7218
- * @category Channel API
7219
- * @async
7220
- * @private
8426
+ * @category Invitation Events
7221
8427
  */
7222
- const getUserMessageFeedMakers = async (channelIds) => {
7223
- const client = getActiveClient();
7224
- client.log('channel/getUserMessageFeedMakers', channelIds);
7225
- const { data } = await client.http.get(`/api/v1/markers/user-message-feed`, {
7226
- params: {
7227
- channelIds,
7228
- },
7229
- });
7230
- fireEvent('local.userMessageFeedMarker.fetched', { userMessageFeedMarker: data });
7231
- return data;
7232
- };
7233
-
7234
- const prepareUnreadCountInfo = async (rawPayload) => {
8428
+ const onLocalInvitationCreated = (callback) => {
7235
8429
  const client = getActiveClient();
7236
- // if consistent mode is enabled, persist the unread count info to the cache
7237
- // Marker service API uses channelInternalId as channelId
7238
- const queryPayload = await getUserMessageFeedMakers(rawPayload.channels.map(({ channelInternalId }) => channelInternalId));
7239
- const { feedMarkers, userFeedMarkers } = queryPayload;
7240
- persistUnreadCountInfo({
7241
- feedMarkers,
7242
- userFeedMarkers,
7243
- });
7244
- client.log('channel/prepareUnreadCountInfo', rawPayload.channels);
8430
+ const disposers = [
8431
+ createEventSubscriber(client, 'onLocalInvitationCreated', 'local.invitation.created', payload => callback(payload)),
8432
+ ];
8433
+ return () => {
8434
+ disposers.forEach(fn => fn());
8435
+ };
7245
8436
  };
7246
8437
 
7247
- const getCachedMarker$1 = (entityId) => {
7248
- var _a;
7249
- const key = {
7250
- entityId,
7251
- userId: getActiveUser()._id,
7252
- };
7253
- return (_a = pullFromCache([
7254
- 'channelMarker',
7255
- 'get',
7256
- getResolver('channelMarker')(key),
7257
- ])) === null || _a === void 0 ? void 0 : _a.data;
7258
- };
7259
- const getUnreadInfoCached$1 = (channelId) => {
7260
- var _a;
7261
- return (_a = pullFromCache(['channelUnreadInfo', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
7262
- };
7263
8438
  /**
7264
- * The function use to get value of hasMentioned or isMentioned field.
7265
- * function will get the value from marker params first, if there is no hasMentioned field, will look in to the cache.
8439
+ * ```js
8440
+ * import { onLocalInvitationUpdated } from '@amityco/ts-sdk'
8441
+ * const dispose = onLocalInvitationUpdated(data => {
8442
+ * // ...
8443
+ * })
8444
+ * ```
7266
8445
  *
7267
- * If consistent mode is enabled, the function will return the value from the channelUnreadCountInfo cache.
7268
- * If not, the function will return the value from the channelMarker cache.
7269
- * If not found in the both cache, use `false` as defaul value.
8446
+ * Fired when an {@link Amity.InvitationPayload} has been updated
8447
+ *
8448
+ * @param callback The function to call when the event was fired
8449
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
8450
+ *
8451
+ * @category Invitation Events
7270
8452
  */
7271
- const getChannelIsMentioned = (channel, marker) => {
7272
- var _a, _b, _c, _d;
8453
+ const onLocalInvitationUpdated = (callback) => {
7273
8454
  const client = getActiveClient();
7274
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
7275
- return (_b = (_a = getUnreadInfoCached$1(channel.channelPublicId)) === null || _a === void 0 ? void 0 : _a.isMentioned) !== null && _b !== void 0 ? _b : false;
7276
- }
7277
- return (marker === null || marker === void 0 ? void 0 : marker.hasMentioned) !== undefined
7278
- ? marker === null || marker === void 0 ? void 0 : marker.hasMentioned
7279
- : (_d = (_c = getCachedMarker$1(channel.channelPublicId)) === null || _c === void 0 ? void 0 : _c.hasMentioned) !== null && _d !== void 0 ? _d : false;
8455
+ const disposers = [
8456
+ createEventSubscriber(client, 'onLocalInvitationUpdated', 'local.invitation.updated', payload => callback(payload)),
8457
+ ];
8458
+ return () => {
8459
+ disposers.forEach(fn => fn());
8460
+ };
7280
8461
  };
7281
8462
 
7282
- const getCachedMarker = (entityId) => {
7283
- var _a;
7284
- const key = {
7285
- entityId,
7286
- userId: getActiveUser()._id,
7287
- };
7288
- return (_a = pullFromCache([
7289
- 'channelMarker',
7290
- 'get',
7291
- getResolver('channelMarker')(key),
7292
- ])) === null || _a === void 0 ? void 0 : _a.data;
7293
- };
7294
- const getUnreadInfoCached = (channelId) => {
7295
- var _a;
7296
- return (_a = pullFromCache(['channelUnreadInfo', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
7297
- };
7298
8463
  /**
7299
- * The function use to get value of unreadCount field.
7300
- * function will get the value from marker params first, if there is no hasMentioned field, will look in to the cache.
8464
+ * ```js
8465
+ * import { onLocalInvitationDeleted } from '@amityco/ts-sdk'
8466
+ * const dispose = onLocalInvitationDeleted(data => {
8467
+ * // ...
8468
+ * })
8469
+ * ```
7301
8470
  *
7302
- * If consistent mode is enabled, the function will return the value from the channelUnreadCountInfo cache.
7303
- * If not, the function will return the value from the channelMarker cache.
7304
- * If not found in the both cache, use `0` as defaul value.
8471
+ * Fired when an {@link Amity.InvitationPayload} has been deleted
8472
+ *
8473
+ * @param callback The function to call when the event was fired
8474
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
8475
+ *
8476
+ * @category Invitation Events
7305
8477
  */
7306
- const getSubChannelsUnreadCount = (channel, marker) => {
7307
- var _a, _b, _c, _d, _e;
8478
+ const onLocalInvitationDeleted = (callback) => {
7308
8479
  const client = getActiveClient();
7309
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
7310
- // Marker service API uses channelInternalId as channelId
7311
- return (_b = (_a = getUnreadInfoCached(channel.channelInternalId)) === null || _a === void 0 ? void 0 : _a.unreadCount) !== null && _b !== void 0 ? _b : 0;
7312
- }
7313
- if (marker === null || marker === void 0 ? void 0 : marker.isDeleted) {
7314
- // NOTE: This is a temporary solution to handle the channel marker when the user is forced to
7315
- // leave the channel because currently backend can't handle this, so every time a user is banned
7316
- // from a channel or the channel is deleted the channel's unread count will reset to zero
7317
- return 0;
7318
- }
7319
- return (_e = (_c = marker === null || marker === void 0 ? void 0 : marker.unreadCount) !== null && _c !== void 0 ? _c : (_d = getCachedMarker(channel.channelInternalId)) === null || _d === void 0 ? void 0 : _d.unreadCount) !== null && _e !== void 0 ? _e : 0;
8480
+ const disposers = [
8481
+ createEventSubscriber(client, 'onLocalInvitationDeleted', 'local.invitation.deleted', payload => callback(payload)),
8482
+ ];
8483
+ return () => {
8484
+ disposers.forEach(fn => fn());
8485
+ };
7320
8486
  };
7321
8487
 
7322
- const getLegacyChannelUnread = (channelId) => {
7323
- var _a;
7324
- return (_a = pullFromCache(['channelUnread', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
7325
- };
8488
+ class InvitationsLiveCollectionController extends LiveCollectionController {
8489
+ constructor(query, callback) {
8490
+ const queryStreamId = hash__default["default"](query);
8491
+ const cacheKey = ['invitation', 'collection', queryStreamId];
8492
+ const paginationController = new InvitationsPaginationController(query);
8493
+ super(paginationController, queryStreamId, cacheKey, callback);
8494
+ this.query = query;
8495
+ this.queryStreamController = new InvitationsQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareInvitationPayload);
8496
+ this.callback = callback.bind(this);
8497
+ this.loadPage({ initial: true });
8498
+ }
8499
+ setup() {
8500
+ var _a;
8501
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
8502
+ if (!collection) {
8503
+ pushToCache(this.cacheKey, {
8504
+ data: [],
8505
+ params: this.query,
8506
+ });
8507
+ }
8508
+ }
8509
+ async persistModel(queryPayload) {
8510
+ await this.queryStreamController.saveToMainDB(queryPayload);
8511
+ }
8512
+ persistQueryStream({ response, direction, refresh, }) {
8513
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
8514
+ }
8515
+ startSubscription() {
8516
+ return this.queryStreamController.subscribeRTE([
8517
+ {
8518
+ fn: onLocalInvitationCreated,
8519
+ action: InvitationActionsEnum.OnLocalInvitationCreated,
8520
+ },
8521
+ {
8522
+ fn: onLocalInvitationUpdated,
8523
+ action: InvitationActionsEnum.OnLocalInvitationUpdated,
8524
+ },
8525
+ {
8526
+ fn: onLocalInvitationDeleted,
8527
+ action: InvitationActionsEnum.OnLocalInvitationDeleted,
8528
+ },
8529
+ ]);
8530
+ }
8531
+ notifyChange({ origin, loading, error }) {
8532
+ var _a, _b;
8533
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
8534
+ if (!collection)
8535
+ return;
8536
+ const data = this.applyFilter((_b = collection.data
8537
+ .map(id => pullFromCache(['invitation', 'get', id]))
8538
+ .filter(isNonNullable)
8539
+ .map(({ data }) => invitationLinkedObject(data))) !== null && _b !== void 0 ? _b : []);
8540
+ if (!this.shouldNotify(data) && origin === 'event')
8541
+ return;
8542
+ this.callback({
8543
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
8544
+ data,
8545
+ hasNextPage: !!this.paginationController.getNextToken(),
8546
+ loading,
8547
+ error,
8548
+ });
8549
+ }
8550
+ applyFilter(data) {
8551
+ let invitations = data;
8552
+ if (this.query.targetId) {
8553
+ invitations = invitations.filter(invitation => invitation.targetId === this.query.targetId);
8554
+ }
8555
+ if (this.query.statuses) {
8556
+ invitations = invitations.filter(invitation => { var _a; return (_a = this.query.statuses) === null || _a === void 0 ? void 0 : _a.includes(invitation.status); });
8557
+ }
8558
+ if (this.query.targetType) {
8559
+ invitations = invitations.filter(invitation => invitation.targetType === this.query.targetType);
8560
+ }
8561
+ if (this.query.type) {
8562
+ invitations = invitations.filter(invitation => invitation.type === this.query.type);
8563
+ }
8564
+ const sortFn = (() => {
8565
+ switch (this.query.sortBy) {
8566
+ case 'firstCreated':
8567
+ return sortByFirstCreated;
8568
+ case 'lastCreated':
8569
+ return sortByLastCreated;
8570
+ default:
8571
+ return sortByLastCreated;
8572
+ }
8573
+ })();
8574
+ invitations = invitations.sort(sortFn);
8575
+ return invitations;
8576
+ }
8577
+ }
7326
8578
 
7327
- const constructChannelDynamicValue = (channel) => {
7328
- const client = getActiveClient();
7329
- const rest = __rest(channel, ["messageCount"]);
7330
- return shallowClone(rest, {
7331
- get unreadCount() {
7332
- var _a, _b;
7333
- return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.unreadCount) !== null && _b !== void 0 ? _b : 0;
7334
- },
7335
- get subChannelsUnreadCount() {
7336
- return getSubChannelsUnreadCount(rest);
7337
- },
7338
- get isMentioned() {
7339
- var _a, _b;
7340
- if (client.useLegacyUnreadCount)
7341
- return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.isMentioned) !== null && _b !== void 0 ? _b : false;
7342
- return getChannelIsMentioned(rest);
7343
- },
8579
+ /**
8580
+ * Get invitations
8581
+ *
8582
+ * @param params the query parameters
8583
+ * @param callback the callback to be called when the invitations are updated
8584
+ * @returns invitations
8585
+ *
8586
+ * @category Invitation Live Collection
8587
+ *
8588
+ */
8589
+ const getInvitations = (params, callback, config) => {
8590
+ const { log, cache } = getActiveClient();
8591
+ if (!cache) {
8592
+ console.log(ENABLE_CACHE_MESSAGE);
8593
+ }
8594
+ const timestamp = Date.now();
8595
+ log(`getInvitations: (tmpid: ${timestamp}) > listen`);
8596
+ const invitationsLiveCollection = new InvitationsLiveCollectionController(params, callback);
8597
+ const disposers = invitationsLiveCollection.startSubscription();
8598
+ const cacheKey = invitationsLiveCollection.getCacheKey();
8599
+ disposers.push(() => {
8600
+ dropFromCache(cacheKey);
7344
8601
  });
8602
+ return () => {
8603
+ log(`getInvitations (tmpid: ${timestamp}) > dispose`);
8604
+ disposers.forEach(fn => fn());
8605
+ };
8606
+ };
8607
+
8608
+ const communityLinkedObject = (community) => {
8609
+ return Object.assign(Object.assign({}, community), { createInvitations: async (userIds) => {
8610
+ await createInvitations({
8611
+ type: "communityMemberInvite" /* InvitationTypeEnum.CommunityMemberInvite */,
8612
+ targetType: 'community',
8613
+ targetId: community.communityId,
8614
+ userIds,
8615
+ });
8616
+ }, getMemberInvitations: (params, callback) => {
8617
+ return getInvitations(Object.assign(Object.assign({}, params), { targetId: community.communityId, targetType: 'community', type: "communityMemberInvite" /* InvitationTypeEnum.CommunityMemberInvite */ }), callback);
8618
+ }, getInvitation: async () => {
8619
+ const { data } = await getInvitation('community', community.communityId);
8620
+ return data;
8621
+ }, join: async () => {
8622
+ return joinRequest(community.communityId);
8623
+ }, getJoinRequests: (params, callback) => {
8624
+ return getJoinRequests(Object.assign(Object.assign({}, params), { communityId: community.communityId }), callback);
8625
+ }, getMyJoinRequest: async () => {
8626
+ const { data } = await getMyJoinRequest(community.communityId);
8627
+ return data;
8628
+ } });
8629
+ };
8630
+
8631
+ const LinkedObject = {
8632
+ ad: adLinkedObject,
8633
+ comment: commentLinkedObject,
8634
+ post: postLinkedObject,
8635
+ user: userLinkedObject,
8636
+ category: categoryLinkedObject,
8637
+ stream: streamLinkedObject,
8638
+ story: storyLinkedObject,
8639
+ storyTarget: storyTargetLinkedObject,
8640
+ message: messageLinkedObject,
8641
+ reactor: reactorLinkedObject,
8642
+ channel: channelLinkedObject,
8643
+ pinnedPost: pinnedPostLinkedObject,
8644
+ notificationTray: notificationTrayLinkedObject,
8645
+ community: communityLinkedObject,
8646
+ invitation: invitationLinkedObject,
8647
+ joinRequest: joinRequestLinkedObject,
7345
8648
  };
7346
8649
 
7347
8650
  const constructChannelObject = (channel) => {
@@ -10063,38 +11366,6 @@ const onMessageMarked = (callback) => {
10063
11366
  return createEventSubscriber(client, 'messageMarker/onMessageMarked', 'marker.marked-message', filter);
10064
11367
  };
10065
11368
 
10066
- function isObject(value) {
10067
- return typeof value === 'object' && value !== null;
10068
- }
10069
- /**
10070
- * convert all object getter property to static value
10071
- */
10072
- const convertGetterPropsToStatic = (obj) => {
10073
- if (!isObject(obj)) {
10074
- return obj;
10075
- }
10076
- const entries = Object.entries(obj).map(([key, value]) => {
10077
- const descriptor = Object.getOwnPropertyDescriptor(obj, key);
10078
- if (typeof (descriptor === null || descriptor === void 0 ? void 0 : descriptor.get) === 'function') {
10079
- return [key, descriptor.get.call(obj)];
10080
- }
10081
- return [key, value];
10082
- });
10083
- return Object.fromEntries(entries);
10084
- };
10085
- const removeFunctionProperties = (obj) => {
10086
- if (!isObject(obj)) {
10087
- return obj;
10088
- }
10089
- const entries = Object.entries(obj).map(([key, value]) => {
10090
- if (typeof value === 'function') {
10091
- return [key, undefined];
10092
- }
10093
- return [key, value];
10094
- });
10095
- return Object.fromEntries(entries);
10096
- };
10097
-
10098
11369
  /**
10099
11370
  *
10100
11371
  * ```js
@@ -10204,7 +11475,7 @@ const getUserUnread = (callback) => {
10204
11475
  };
10205
11476
  };
10206
11477
 
10207
- var index$m = /*#__PURE__*/Object.freeze({
11478
+ var index$n = /*#__PURE__*/Object.freeze({
10208
11479
  __proto__: null,
10209
11480
  getActiveClient: getActiveClient,
10210
11481
  getActiveUser: getActiveUser,
@@ -10708,51 +11979,6 @@ const onLocalFollowRequestAccepted = (callback) => createLocalFollowEventSubscri
10708
11979
 
10709
11980
  const onLocalFollowRequestDeclined = (callback) => createLocalFollowEventSubscriber('local.follow.requestDeclined', callback);
10710
11981
 
10711
- class PaginationController {
10712
- constructor(queryParams) {
10713
- const { http } = getActiveClient();
10714
- this.queryParams = queryParams;
10715
- this.http = http;
10716
- }
10717
- loadFirstPage() {
10718
- return this.onFetch("first" /* Amity.LiveCollectionPageDirection.FIRST */);
10719
- }
10720
- loadNextPage() {
10721
- return this.onFetch("next" /* Amity.LiveCollectionPageDirection.NEXT */);
10722
- }
10723
- loadPreviousPage() {
10724
- return this.onFetch("prev" /* Amity.LiveCollectionPageDirection.PREV */);
10725
- }
10726
- async onFetch(direction = "first" /* Amity.LiveCollectionPageDirection.FIRST */) {
10727
- var _a, _b, _c, _d;
10728
- if (direction === 'prev' && !this.previousToken)
10729
- return;
10730
- if (direction === 'next' && !this.nextToken)
10731
- return;
10732
- let token;
10733
- if (direction === 'prev')
10734
- token = this.previousToken;
10735
- if (direction === 'next')
10736
- token = this.nextToken;
10737
- const queryResponse = await this.getRequest(this.queryParams, token);
10738
- if (direction === 'first') {
10739
- this.nextToken = (_a = queryResponse.paging) === null || _a === void 0 ? void 0 : _a.next;
10740
- this.previousToken = (_b = queryResponse.paging) === null || _b === void 0 ? void 0 : _b.previous;
10741
- }
10742
- if (direction === 'prev')
10743
- this.previousToken = (_c = queryResponse.paging) === null || _c === void 0 ? void 0 : _c.previous;
10744
- if (direction === 'next')
10745
- this.nextToken = (_d = queryResponse.paging) === null || _d === void 0 ? void 0 : _d.next;
10746
- return queryResponse;
10747
- }
10748
- getNextToken() {
10749
- return this.nextToken;
10750
- }
10751
- getPrevToken() {
10752
- return this.previousToken;
10753
- }
10754
- }
10755
-
10756
11982
  class FollowerPaginationController extends PaginationController {
10757
11983
  async getRequest(queryParams, token) {
10758
11984
  const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, userId } = queryParams, params = __rest(queryParams, ["limit", "userId"]);
@@ -10766,13 +11992,6 @@ class FollowerPaginationController extends PaginationController {
10766
11992
  }
10767
11993
  }
10768
11994
 
10769
- class QueryStreamController {
10770
- constructor(query, cacheKey) {
10771
- this.query = query;
10772
- this.cacheKey = cacheKey;
10773
- }
10774
- }
10775
-
10776
11995
  var EnumFollowActions;
10777
11996
  (function (EnumFollowActions) {
10778
11997
  EnumFollowActions["OnRequested"] = "onRequested";
@@ -10840,109 +12059,6 @@ class FollowerQueryStreamController extends QueryStreamController {
10840
12059
  }
10841
12060
  }
10842
12061
 
10843
- class PaginationNoPageController {
10844
- constructor(queryParams) {
10845
- const { http } = getActiveClient();
10846
- this.queryParams = queryParams;
10847
- this.http = http;
10848
- }
10849
- async onFetch() {
10850
- const queryResponse = await this.getRequest(this.queryParams);
10851
- return queryResponse;
10852
- }
10853
- }
10854
-
10855
- class LiveCollectionController {
10856
- constructor(paginationController, queryStreamId, cacheKey, callback) {
10857
- this.paginationController = paginationController;
10858
- this.queryStreamId = queryStreamId;
10859
- this.cacheKey = cacheKey;
10860
- this.callback = callback;
10861
- }
10862
- async refresh() {
10863
- try {
10864
- let result;
10865
- if (this.paginationController instanceof PaginationNoPageController) {
10866
- result = await this.paginationController.onFetch();
10867
- }
10868
- else {
10869
- result = await this.paginationController.loadFirstPage();
10870
- }
10871
- if (!result)
10872
- return;
10873
- await this.persistModel(result);
10874
- this.persistQueryStream({
10875
- response: result,
10876
- direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
10877
- refresh: true,
10878
- });
10879
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
10880
- }
10881
- catch (e) {
10882
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
10883
- }
10884
- }
10885
- loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
10886
- this.setup();
10887
- this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
10888
- if (initial) {
10889
- this.refresh();
10890
- }
10891
- else if (direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */) {
10892
- this.loadPrevPage();
10893
- }
10894
- else if (direction === "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
10895
- this.loadNextPage();
10896
- }
10897
- }
10898
- async loadNextPage() {
10899
- try {
10900
- if (this.paginationController instanceof PaginationNoPageController)
10901
- return;
10902
- const result = await this.paginationController.loadNextPage();
10903
- if (!result)
10904
- return;
10905
- await this.persistModel(result);
10906
- this.persistQueryStream({
10907
- response: result,
10908
- direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
10909
- });
10910
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
10911
- }
10912
- catch (e) {
10913
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
10914
- }
10915
- }
10916
- async loadPrevPage() {
10917
- try {
10918
- if (this.paginationController instanceof PaginationNoPageController)
10919
- return;
10920
- const result = await this.paginationController.loadPreviousPage();
10921
- if (!result)
10922
- return;
10923
- await this.persistModel(result);
10924
- this.persistQueryStream({
10925
- response: result,
10926
- direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */,
10927
- });
10928
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
10929
- }
10930
- catch (e) {
10931
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
10932
- }
10933
- }
10934
- shouldNotify(data) {
10935
- const newData = data.map(convertGetterPropsToStatic).map(removeFunctionProperties);
10936
- if (isEqual(this.snapshot, newData))
10937
- return false;
10938
- this.snapshot = newData;
10939
- return true;
10940
- }
10941
- getCacheKey() {
10942
- return this.cacheKey;
10943
- }
10944
- }
10945
-
10946
12062
  const onFollowerUserDeleted = ({ userId }) => (callback) => {
10947
12063
  const client = getActiveClient();
10948
12064
  const filter = (data) => {
@@ -11411,7 +12527,7 @@ const getMyFollowInfo = (callback) => {
11411
12527
  };
11412
12528
  /* end_public_function */
11413
12529
 
11414
- var index$l = /*#__PURE__*/Object.freeze({
12530
+ var index$m = /*#__PURE__*/Object.freeze({
11415
12531
  __proto__: null,
11416
12532
  blockUser: blockUser,
11417
12533
  unBlockUser: unBlockUser,
@@ -12426,9 +13542,9 @@ var AmityUserSearchMatchType;
12426
13542
  AmityUserSearchMatchType["PARTIAL"] = "partial";
12427
13543
  })(AmityUserSearchMatchType || (AmityUserSearchMatchType = {}));
12428
13544
 
12429
- var index$k = /*#__PURE__*/Object.freeze({
13545
+ var index$l = /*#__PURE__*/Object.freeze({
12430
13546
  __proto__: null,
12431
- Relationship: index$l,
13547
+ Relationship: index$m,
12432
13548
  getUserByIds: getUserByIds,
12433
13549
  updateUser: updateUser,
12434
13550
  flagUser: flagUser,
@@ -12736,7 +13852,7 @@ const updateAltText = async (fileId, altText) => {
12736
13852
  };
12737
13853
  /* end_public_function */
12738
13854
 
12739
- var index$j = /*#__PURE__*/Object.freeze({
13855
+ var index$k = /*#__PURE__*/Object.freeze({
12740
13856
  __proto__: null,
12741
13857
  getFile: getFile,
12742
13858
  uploadFile: uploadFile,
@@ -13075,46 +14191,15 @@ getComment$2.locally = (commentId) => {
13075
14191
  const client = getActiveClient();
13076
14192
  client.log('comment/getComment.locally', commentId);
13077
14193
  if (!client.cache)
13078
- return;
13079
- const cached = pullFromCache(['comment', 'get', commentId]);
13080
- if (!cached)
13081
- return;
13082
- return {
13083
- data: LinkedObject.comment(cached.data),
13084
- cachedAt: cached.cachedAt,
13085
- };
13086
- };
13087
-
13088
- /*
13089
- * verifies membership status
13090
- */
13091
- function isMember(membership) {
13092
- return membership !== 'none';
13093
- }
13094
- /*
13095
- * checks if currently logged in user is part of the community
13096
- */
13097
- function isCurrentUserPartOfCommunity(c, m) {
13098
- const { userId } = getActiveUser();
13099
- return c.communityId === m.communityId && m.userId === userId;
13100
- }
13101
- /*
13102
- * For mqtt events server will not send user specific data as it's broadcasted
13103
- * to multiple users and it also does not include communityUser
13104
- *
13105
- * Client SDK needs to check for the existing isJoined field in cache data before calculating.
13106
- * Althought this can be calculated, it's not scalable.
13107
- */
13108
- function updateMembershipStatus(communities, communityUsers) {
13109
- return communities.map(c => {
13110
- const cachedCommunity = pullFromCache(['community', 'get', c.communityId]);
13111
- if ((cachedCommunity === null || cachedCommunity === void 0 ? void 0 : cachedCommunity.data) && (cachedCommunity === null || cachedCommunity === void 0 ? void 0 : cachedCommunity.data.hasOwnProperty('isJoined'))) {
13112
- return Object.assign(Object.assign({}, cachedCommunity.data), c);
13113
- }
13114
- const isJoined = communityUsers.some(m => isCurrentUserPartOfCommunity(c, m) && isMember(m.communityMembership));
13115
- return Object.assign(Object.assign({}, c), { isJoined });
13116
- });
13117
- }
14194
+ return;
14195
+ const cached = pullFromCache(['comment', 'get', commentId]);
14196
+ if (!cached)
14197
+ return;
14198
+ return {
14199
+ data: LinkedObject.comment(cached.data),
14200
+ cachedAt: cached.cachedAt,
14201
+ };
14202
+ };
13118
14203
 
13119
14204
  const getMyReactionsInCache = (payload, eventPrefix) => {
13120
14205
  var _a, _b;
@@ -13430,53 +14515,6 @@ removeReaction.optimistically = (referenceType, referenceId, reactionName) => {
13430
14515
  return !((_d = reaction === null || reaction === void 0 ? void 0 : reaction.myReactions) === null || _d === void 0 ? void 0 : _d.includes(reactionName));
13431
14516
  };
13432
14517
 
13433
- const getMatchPostSetting = (value) => {
13434
- var _a;
13435
- return (_a = Object.keys(CommunityPostSettingMaps).find(key => value.needApprovalOnPostCreation ===
13436
- CommunityPostSettingMaps[key].needApprovalOnPostCreation &&
13437
- value.onlyAdminCanPost === CommunityPostSettingMaps[key].onlyAdminCanPost)) !== null && _a !== void 0 ? _a : DefaultCommunityPostSetting;
13438
- };
13439
- function addPostSetting({ communities }) {
13440
- return communities.map((_a) => {
13441
- var { needApprovalOnPostCreation, onlyAdminCanPost } = _a, restCommunityPayload = __rest(_a, ["needApprovalOnPostCreation", "onlyAdminCanPost"]);
13442
- return (Object.assign({ postSetting: getMatchPostSetting({
13443
- needApprovalOnPostCreation,
13444
- onlyAdminCanPost,
13445
- }) }, restCommunityPayload));
13446
- });
13447
- }
13448
- const prepareCommunityPayload = (rawPayload) => {
13449
- const communitiesWithPostSetting = addPostSetting({ communities: rawPayload.communities });
13450
- // map users with community
13451
- const mappedCommunityUsers = rawPayload.communityUsers.map(communityUser => {
13452
- const user = rawPayload.users.find(user => user.userId === communityUser.userId);
13453
- return Object.assign(Object.assign({}, communityUser), { user });
13454
- });
13455
- const communityWithMembershipStatus = updateMembershipStatus(communitiesWithPostSetting, mappedCommunityUsers);
13456
- return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers: mappedCommunityUsers });
13457
- };
13458
- const prepareCommunityMembershipPayload = (rawPayload) => {
13459
- const communitiesWithPostSetting = addPostSetting({ communities: rawPayload.communities });
13460
- // map users with community
13461
- const mappedCommunityUsers = rawPayload.communityUsers.map(communityUser => {
13462
- const user = rawPayload.users.find(user => user.userId === communityUser.userId);
13463
- return Object.assign(Object.assign({}, communityUser), { user });
13464
- });
13465
- const communityWithMembershipStatus = updateMembershipStatus(communitiesWithPostSetting, mappedCommunityUsers);
13466
- return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers: mappedCommunityUsers });
13467
- };
13468
- const prepareCommunityRequest = (params) => {
13469
- const { postSetting = undefined, storySetting } = params, restParam = __rest(params, ["postSetting", "storySetting"]);
13470
- return Object.assign(Object.assign(Object.assign({}, restParam), (postSetting ? CommunityPostSettingMaps[postSetting] : undefined)), {
13471
- // Convert story setting to the actual value. (Allow by default)
13472
- allowCommentInStory: typeof (storySetting === null || storySetting === void 0 ? void 0 : storySetting.enableComment) === 'boolean' ? storySetting.enableComment : true });
13473
- };
13474
- const prepareSemanticSearchCommunityPayload = (_a) => {
13475
- var communityPayload = __rest(_a, ["searchResult"]);
13476
- const processedCommunityPayload = prepareCommunityPayload(communityPayload);
13477
- return Object.assign({}, processedCommunityPayload);
13478
- };
13479
-
13480
14518
  const preparePostPayload = (payload) => {
13481
14519
  const { posts: postsData } = payload, postPayload = __rest(payload, ["posts"]);
13482
14520
  // Unpack community payload by mapping payload field to postSetting value.
@@ -14604,7 +15642,7 @@ const getReactions = (params, callback, config) => {
14604
15642
  };
14605
15643
  /* end_public_function */
14606
15644
 
14607
- var index$i = /*#__PURE__*/Object.freeze({
15645
+ var index$j = /*#__PURE__*/Object.freeze({
14608
15646
  __proto__: null,
14609
15647
  addReaction: addReaction,
14610
15648
  removeReaction: removeReaction,
@@ -15921,19 +16959,26 @@ getDeliveredUsers.locally = (query) => {
15921
16959
  /**
15922
16960
  * ```js
15923
16961
  * import { MessageRepository } from '@amityco/ts-sdk'
15924
- * const flagged = await MessageRepository.flagMessage(messageId)
16962
+ * const flagged = await MessageRepository.flagMessage(messageId, reason)
15925
16963
  * ```
15926
16964
  *
15927
16965
  * @param messageId of the message to flag
16966
+ * @param reason the reason to flag the message
15928
16967
  * @returns the created report result
15929
16968
  *
15930
16969
  * @category Message API
15931
16970
  * @async
15932
16971
  * */
15933
- const flagMessage = async (messageId) => {
16972
+ const flagMessage = async (messageId, reason) => {
15934
16973
  const client = getActiveClient();
15935
16974
  client.log('message/flag', messageId);
15936
- const { data: payload } = await client.http.post(`/api/v5/messages/${encodeURIComponent(messageId)}/flags`);
16975
+ const isPredefinedReason = reason &&
16976
+ Object.entries(exports.ContentFlagReasonEnum).some(([key, value]) => key !== exports.ContentFlagReasonEnum.Others && value === reason);
16977
+ const body = {
16978
+ reason: isPredefinedReason ? reason : exports.ContentFlagReasonEnum.Others,
16979
+ detail: !isPredefinedReason ? reason : '',
16980
+ };
16981
+ const { data: payload } = await client.http.post(`/api/v5/messages/${encodeURIComponent(messageId)}/flags`, body);
15937
16982
  if (client.cache) {
15938
16983
  const messagePayload = await prepareMessagePayload(payload);
15939
16984
  ingestInCache(messagePayload);
@@ -16420,7 +17465,7 @@ const getMessages = (params, callback, config) => {
16420
17465
  };
16421
17466
  /* end_public_function */
16422
17467
 
16423
- var index$h = /*#__PURE__*/Object.freeze({
17468
+ var index$i = /*#__PURE__*/Object.freeze({
16424
17469
  __proto__: null,
16425
17470
  createMessage: createMessage,
16426
17471
  updateMessage: updateMessage,
@@ -16946,7 +17991,7 @@ const stopMessageReceiptSync = (subChannelId) => {
16946
17991
  };
16947
17992
  /* end_public_function */
16948
17993
 
16949
- var index$g = /*#__PURE__*/Object.freeze({
17994
+ var index$h = /*#__PURE__*/Object.freeze({
16950
17995
  __proto__: null,
16951
17996
  getSubChannelByIds: getSubChannels$1,
16952
17997
  createSubChannel: createSubChannel,
@@ -18260,7 +19305,7 @@ const searchMembers$1 = (params, callback, config) => {
18260
19305
  };
18261
19306
  /* end_public_function */
18262
19307
 
18263
- var index$f = /*#__PURE__*/Object.freeze({
19308
+ var index$g = /*#__PURE__*/Object.freeze({
18264
19309
  __proto__: null,
18265
19310
  addMembers: addMembers$1,
18266
19311
  removeMembers: removeMembers$1,
@@ -18463,7 +19508,7 @@ const unmuteMembers = async (channelId, userIds) => {
18463
19508
  };
18464
19509
  /* end_public_function */
18465
19510
 
18466
- var index$e = /*#__PURE__*/Object.freeze({
19511
+ var index$f = /*#__PURE__*/Object.freeze({
18467
19512
  __proto__: null,
18468
19513
  addRole: addRole,
18469
19514
  removeRole: removeRole,
@@ -18473,10 +19518,10 @@ var index$e = /*#__PURE__*/Object.freeze({
18473
19518
  unmuteMembers: unmuteMembers
18474
19519
  });
18475
19520
 
18476
- var index$d = /*#__PURE__*/Object.freeze({
19521
+ var index$e = /*#__PURE__*/Object.freeze({
18477
19522
  __proto__: null,
18478
- Membership: index$f,
18479
- Moderation: index$e,
19523
+ Membership: index$g,
19524
+ Moderation: index$f,
18480
19525
  getChannelByIds: getChannelByIds$1,
18481
19526
  createChannel: createChannel,
18482
19527
  updateChannel: updateChannel,
@@ -18530,12 +19575,15 @@ const saveCommunityUsers = (communities, communityUsers) => {
18530
19575
  * @category Community API
18531
19576
  * @async
18532
19577
  */
18533
- const getCommunities$1 = async (communityIds) => {
19578
+ const getCommunities$1 = async (communityIds, includeDiscoverablePrivateCommunity) => {
18534
19579
  const client = getActiveClient();
18535
19580
  client.log('community/getCommunities', communityIds);
18536
19581
  // API-FIX: endpoint should not be /list, parameters should be querystring.
18537
19582
  const { data: payload } = await client.http.get(`/api/v3/communities/list`, {
18538
- params: { communityIds },
19583
+ params: {
19584
+ communityIds,
19585
+ includeDiscoverablePrivateCommunity: includeDiscoverablePrivateCommunity !== null && includeDiscoverablePrivateCommunity !== void 0 ? includeDiscoverablePrivateCommunity : true,
19586
+ },
18539
19587
  });
18540
19588
  const data = prepareCommunityPayload(payload);
18541
19589
  const cachedAt = client.cache && Date.now();
@@ -18544,7 +19592,7 @@ const getCommunities$1 = async (communityIds) => {
18544
19592
  saveCommunityUsers(data.communities, data.communityUsers);
18545
19593
  }
18546
19594
  return {
18547
- data: data.communities,
19595
+ data: data.communities.map(community => LinkedObject.community(community)),
18548
19596
  cachedAt,
18549
19597
  };
18550
19598
  };
@@ -18586,7 +19634,7 @@ getCommunities$1.locally = (communityIds) => {
18586
19634
  /**
18587
19635
  * ```js
18588
19636
  * import { createCommunity } from '@amityco/ts-sdk'
18589
- * const created = await createCommunity({ communityId: 'foobar', displayName: 'foobar' })
19637
+ * const created = await createCommunity({ communityId: 'foobar', displayName: 'foobar', isDiscoverable: true, requiresJoinApproval: false })
18590
19638
  * ```
18591
19639
  *
18592
19640
  * Creates an {@link Amity.Community}
@@ -18610,7 +19658,7 @@ const createCommunity = async (bundle) => {
18610
19658
  }
18611
19659
  const { communities } = data;
18612
19660
  return {
18613
- data: communities[0],
19661
+ data: LinkedObject.community(communities[0]),
18614
19662
  cachedAt,
18615
19663
  };
18616
19664
  };
@@ -18622,7 +19670,7 @@ const createCommunity = async (bundle) => {
18622
19670
  /**
18623
19671
  * ```js
18624
19672
  * import { updateCommunity } from '@amityco/ts-sdk'
18625
- * const updated = await updateCommunity(communityId, { displayName: 'foobar' })
19673
+ * const updated = await updateCommunity(communityId, { displayName: 'foobar', isDiscoverable: true, requiresJoinApproval: false })
18626
19674
  * ```
18627
19675
  *
18628
19676
  * Updates an {@link Amity.Community}
@@ -18647,7 +19695,7 @@ const updateCommunity = async (communityId, patch) => {
18647
19695
  }
18648
19696
  const { communities } = data;
18649
19697
  return {
18650
- data: communities.find(community => community.communityId === communityId),
19698
+ data: LinkedObject.community(communities.find(community => community.communityId === communityId)),
18651
19699
  cachedAt,
18652
19700
  };
18653
19701
  };
@@ -18667,11 +19715,16 @@ const updateCommunity = async (communityId, patch) => {
18667
19715
  * @category Community API
18668
19716
  * @async
18669
19717
  */
18670
- const getCommunity$1 = async (communityId) => {
19718
+ const getCommunity$1 = async (communityId, type, includeDiscoverablePrivateCommunity) => {
18671
19719
  const client = getActiveClient();
18672
19720
  client.log('community/getCommunity', communityId);
18673
19721
  // API-FIX: endpoint should not be /list, parameters should be querystring.
18674
- const { data: payload } = await client.http.get(`/api/v3/communities/${communityId}`);
19722
+ const { data: payload } = await client.http.get(`/api/v3/communities/${communityId}`, {
19723
+ params: {
19724
+ type: 'communityJoinRequest',
19725
+ includeDiscoverablePrivateCommunity: includeDiscoverablePrivateCommunity !== null && includeDiscoverablePrivateCommunity !== void 0 ? includeDiscoverablePrivateCommunity : true,
19726
+ },
19727
+ });
18675
19728
  const data = prepareCommunityPayload(payload);
18676
19729
  const cachedAt = client.cache && Date.now();
18677
19730
  if (client.cache) {
@@ -18680,7 +19733,7 @@ const getCommunity$1 = async (communityId) => {
18680
19733
  }
18681
19734
  const { communities } = data;
18682
19735
  return {
18683
- data: communities.find(community => community.communityId === communityId),
19736
+ data: LinkedObject.community(communities.find(community => community.communityId === communityId)),
18684
19737
  cachedAt,
18685
19738
  };
18686
19739
  };
@@ -18706,7 +19759,7 @@ getCommunity$1.locally = (communityId) => {
18706
19759
  if (!cached)
18707
19760
  return;
18708
19761
  return {
18709
- data: cached.data,
19762
+ data: LinkedObject.community(cached.data),
18710
19763
  cachedAt: cached.cachedAt,
18711
19764
  };
18712
19765
  };
@@ -18746,6 +19799,9 @@ const deleteCommunity = async (communityId) => {
18746
19799
  };
18747
19800
  /* end_public_function */
18748
19801
 
19802
+ /**
19803
+ * @deprecated This function will to be deprecated and use the new community.join().
19804
+ */
18749
19805
  /* begin_public_function
18750
19806
  id: community.join
18751
19807
  */
@@ -18886,10 +19942,11 @@ const onCommunityDeleted = (callback) => createCommunityEventSubscriber('communi
18886
19942
  */
18887
19943
  class CommunitiesPaginationController$1 extends PaginationController {
18888
19944
  async getRequest(queryParams, token) {
19945
+ var _a;
18889
19946
  const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
18890
19947
  const options = token ? { token } : { limit };
18891
19948
  const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
18892
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
19949
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, includeDiscoverablePrivateCommunity: (_a = params.includeDiscoverablePrivateCommunity) !== null && _a !== void 0 ? _a : true, options }),
18893
19950
  });
18894
19951
  return queryResponse;
18895
19952
  }
@@ -19856,7 +20913,7 @@ const searchMembers = (params, callback, config) => {
19856
20913
  };
19857
20914
  /* end_public_function */
19858
20915
 
19859
- var index$c = /*#__PURE__*/Object.freeze({
20916
+ var index$d = /*#__PURE__*/Object.freeze({
19860
20917
  __proto__: null,
19861
20918
  addMembers: addMembers,
19862
20919
  removeMembers: removeMembers,
@@ -20336,7 +21393,7 @@ class TrendingCommunityLiveCollectionController extends LiveCollectionController
20336
21393
  const data = (_b = collection.data
20337
21394
  .map(id => pullFromCache(['community', 'get', id]))
20338
21395
  .filter(isNonNullable)
20339
- .map(({ data }) => data)) !== null && _b !== void 0 ? _b : [];
21396
+ .map(({ data }) => communityLinkedObject(data))) !== null && _b !== void 0 ? _b : [];
20340
21397
  if (!this.shouldNotify(data) && origin === 'event')
20341
21398
  return;
20342
21399
  this.callback({
@@ -20498,7 +21555,7 @@ class RecommendedCommunityLiveCollectionController extends LiveCollectionControl
20498
21555
  const data = (_b = collection.data
20499
21556
  .map(id => pullFromCache(['community', 'get', id]))
20500
21557
  .filter(isNonNullable)
20501
- .map(({ data }) => data)) !== null && _b !== void 0 ? _b : [];
21558
+ .map(({ data }) => communityLinkedObject(data))) !== null && _b !== void 0 ? _b : [];
20502
21559
  if (!this.shouldNotify(data) && origin === 'event')
20503
21560
  return;
20504
21561
  this.callback({
@@ -20881,7 +21938,7 @@ const unbanMembers = async (communityId, userIds) => {
20881
21938
  };
20882
21939
  /* end_public_function */
20883
21940
 
20884
- var index$b = /*#__PURE__*/Object.freeze({
21941
+ var index$c = /*#__PURE__*/Object.freeze({
20885
21942
  __proto__: null,
20886
21943
  addRoles: addRoles,
20887
21944
  removeRoles: removeRoles,
@@ -20889,10 +21946,10 @@ var index$b = /*#__PURE__*/Object.freeze({
20889
21946
  unbanMembers: unbanMembers
20890
21947
  });
20891
21948
 
20892
- var index$a = /*#__PURE__*/Object.freeze({
21949
+ var index$b = /*#__PURE__*/Object.freeze({
20893
21950
  __proto__: null,
20894
- Moderation: index$b,
20895
- Membership: index$c,
21951
+ Moderation: index$c,
21952
+ Membership: index$d,
20896
21953
  getCommunityByIds: getCommunities$1,
20897
21954
  createCommunity: createCommunity,
20898
21955
  updateCommunity: updateCommunity,
@@ -21125,7 +22182,7 @@ const getCategories = (params, callback, config) => {
21125
22182
  };
21126
22183
  /* end_public_function */
21127
22184
 
21128
- var index$9 = /*#__PURE__*/Object.freeze({
22185
+ var index$a = /*#__PURE__*/Object.freeze({
21129
22186
  __proto__: null,
21130
22187
  getCategory: getCategory,
21131
22188
  getCategories: getCategories
@@ -21293,7 +22350,7 @@ getCustomRankingGlobalFeed.locally = (query) => {
21293
22350
  : undefined;
21294
22351
  };
21295
22352
 
21296
- var index$8 = /*#__PURE__*/Object.freeze({
22353
+ var index$9 = /*#__PURE__*/Object.freeze({
21297
22354
  __proto__: null,
21298
22355
  queryGlobalFeed: queryGlobalFeed,
21299
22356
  getCustomRankingGlobalFeed: getCustomRankingGlobalFeed
@@ -22622,7 +23679,7 @@ const getComments = (params, callback, config) => {
22622
23679
  };
22623
23680
  /* end_public_function */
22624
23681
 
22625
- var index$7 = /*#__PURE__*/Object.freeze({
23682
+ var index$8 = /*#__PURE__*/Object.freeze({
22626
23683
  __proto__: null,
22627
23684
  getCommentByIds: getCommentByIds,
22628
23685
  createComment: createComment,
@@ -23148,7 +24205,8 @@ class PinnedPostQueryStreamController extends QueryStreamController {
23148
24205
  const client = getActiveClient();
23149
24206
  const cachedAt = client.cache && Date.now();
23150
24207
  if (client.cache) {
23151
- ingestInCache(response, { cachedAt });
24208
+ const processedPayload = Object.assign(Object.assign({}, response), { users: response.users ? response.users.map(convertRawUserToInternalUser) : [] });
24209
+ ingestInCache(processedPayload, { cachedAt });
23152
24210
  }
23153
24211
  }
23154
24212
  appendToQueryStream(response, direction, refresh = false) {
@@ -23277,7 +24335,8 @@ class GlobalPinnedPostQueryStreamController extends QueryStreamController {
23277
24335
  const client = getActiveClient();
23278
24336
  const cachedAt = client.cache && Date.now();
23279
24337
  if (client.cache) {
23280
- ingestInCache(response, { cachedAt });
24338
+ const processedPayload = Object.assign(Object.assign({}, response), { users: response.users.map(convertRawUserToInternalUser) });
24339
+ ingestInCache(processedPayload, { cachedAt });
23281
24340
  }
23282
24341
  }
23283
24342
  appendToQueryStream(response, direction, refresh = false) {
@@ -23629,7 +24688,7 @@ const semanticSearchPosts = (params, callback, config) => {
23629
24688
  };
23630
24689
  };
23631
24690
 
23632
- var index$6 = /*#__PURE__*/Object.freeze({
24691
+ var index$7 = /*#__PURE__*/Object.freeze({
23633
24692
  __proto__: null,
23634
24693
  getPostByIds: getPostByIds,
23635
24694
  createPost: createPost,
@@ -24163,7 +25222,7 @@ const getStreams = (params, callback, config) => {
24163
25222
  };
24164
25223
  };
24165
25224
 
24166
- var index$5 = /*#__PURE__*/Object.freeze({
25225
+ var index$6 = /*#__PURE__*/Object.freeze({
24167
25226
  __proto__: null,
24168
25227
  createStream: createStream,
24169
25228
  updateStream: updateStream,
@@ -24450,7 +25509,7 @@ const getPoll = (pollId, callback) => {
24450
25509
  };
24451
25510
  /* end_public_function */
24452
25511
 
24453
- var index$4 = /*#__PURE__*/Object.freeze({
25512
+ var index$5 = /*#__PURE__*/Object.freeze({
24454
25513
  __proto__: null,
24455
25514
  createPoll: createPoll,
24456
25515
  closePoll: closePoll,
@@ -24461,7 +25520,7 @@ var index$4 = /*#__PURE__*/Object.freeze({
24461
25520
  getPoll: getPoll
24462
25521
  });
24463
25522
 
24464
- const privateKey = "-----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-----";
25523
+ const privateKey = "-----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-----";
24465
25524
  /*
24466
25525
  * The crypto algorithm used for importing key and signing string
24467
25526
  */
@@ -24821,7 +25880,7 @@ const getPlayer = async (parameters) => {
24821
25880
  return video;
24822
25881
  };
24823
25882
 
24824
- var index$3 = /*#__PURE__*/Object.freeze({
25883
+ var index$4 = /*#__PURE__*/Object.freeze({
24825
25884
  __proto__: null,
24826
25885
  getPlayer: getPlayer
24827
25886
  });
@@ -25994,7 +27053,7 @@ const getGlobalStoryTargets = (params, callback, config) => {
25994
27053
  };
25995
27054
  };
25996
27055
 
25997
- var index$2 = /*#__PURE__*/Object.freeze({
27056
+ var index$3 = /*#__PURE__*/Object.freeze({
25998
27057
  __proto__: null,
25999
27058
  createImageStory: createImageStory,
26000
27059
  createVideoStory: createVideoStory,
@@ -26031,7 +27090,7 @@ const getNetworkAds = async () => {
26031
27090
  };
26032
27091
  };
26033
27092
 
26034
- var index$1 = /*#__PURE__*/Object.freeze({
27093
+ var index$2 = /*#__PURE__*/Object.freeze({
26035
27094
  __proto__: null,
26036
27095
  getNetworkAds: getNetworkAds
26037
27096
  });
@@ -26422,7 +27481,7 @@ const markTraySeen = async (lastSeenAt) => {
26422
27481
  };
26423
27482
  /* end_public_function */
26424
27483
 
26425
- var index = /*#__PURE__*/Object.freeze({
27484
+ var index$1 = /*#__PURE__*/Object.freeze({
26426
27485
  __proto__: null,
26427
27486
  getNotificationTraySeen: getNotificationTraySeen,
26428
27487
  getNotificationTrayItems: getNotificationTrayItems,
@@ -26431,31 +27490,232 @@ var index = /*#__PURE__*/Object.freeze({
26431
27490
  onNotificationTraySeenUpdated: onNotificationTraySeenUpdated
26432
27491
  });
26433
27492
 
27493
+ class MyInvitationsPaginationController extends PaginationController {
27494
+ async getRequest(queryParams, token) {
27495
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
27496
+ const options = token ? { token } : { limit };
27497
+ const { data } = await this.http.get('/api/v1/invitations/me', { params: Object.assign(Object.assign({}, params), { options }) });
27498
+ await getCommunities$1(data.invitations.map(invitation => invitation.targetId));
27499
+ return data;
27500
+ }
27501
+ }
27502
+
27503
+ class MyInvitationsQueryStreamController extends QueryStreamController {
27504
+ constructor(query, cacheKey, notifyChange, preparePayload) {
27505
+ super(query, cacheKey);
27506
+ this.notifyChange = notifyChange;
27507
+ this.preparePayload = preparePayload;
27508
+ }
27509
+ async saveToMainDB(response) {
27510
+ const processedPayload = await this.preparePayload(response);
27511
+ const client = getActiveClient();
27512
+ const cachedAt = client.cache && Date.now();
27513
+ if (client.cache) {
27514
+ ingestInCache(processedPayload, { cachedAt });
27515
+ }
27516
+ }
27517
+ appendToQueryStream(response, direction, refresh = false) {
27518
+ var _a, _b;
27519
+ if (refresh) {
27520
+ pushToCache(this.cacheKey, {
27521
+ data: response.invitations.map(getResolver('invitation')),
27522
+ });
27523
+ }
27524
+ else {
27525
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27526
+ const invitations = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
27527
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
27528
+ ...new Set([...invitations, ...response.invitations.map(getResolver('invitation'))]),
27529
+ ] }));
27530
+ }
27531
+ }
27532
+ reactor(action) {
27533
+ return (invitations) => {
27534
+ var _a;
27535
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27536
+ if (!collection)
27537
+ return;
27538
+ if (action === InvitationActionsEnum.OnLocalInvitationUpdated) {
27539
+ const isExist = collection.data.find(id => id === invitations[0].invitationId);
27540
+ if (!isExist)
27541
+ return;
27542
+ }
27543
+ if (action === InvitationActionsEnum.OnLocalInvitationCreated) {
27544
+ const client = getActiveClient();
27545
+ const myInvitations = invitations.filter(invitation => invitation.invitedUserId === client.userId);
27546
+ collection.data = [
27547
+ ...new Set([
27548
+ ...myInvitations.map(invitation => invitation.invitationId),
27549
+ ...collection.data,
27550
+ ]),
27551
+ ];
27552
+ }
27553
+ if (action === InvitationActionsEnum.OnLocalInvitationDeleted) {
27554
+ collection.data = collection.data.filter(id => id !== invitations[0].invitationId);
27555
+ }
27556
+ pushToCache(this.cacheKey, collection);
27557
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
27558
+ };
27559
+ }
27560
+ subscribeRTE(createSubscriber) {
27561
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
27562
+ }
27563
+ }
27564
+
27565
+ class MyInvitationsLiveCollectionController extends LiveCollectionController {
27566
+ constructor(query, callback) {
27567
+ const queryStreamId = hash__default["default"](query);
27568
+ const cacheKey = ['invitation', 'collection', queryStreamId];
27569
+ const paginationController = new MyInvitationsPaginationController(query);
27570
+ super(paginationController, queryStreamId, cacheKey, callback);
27571
+ this.query = query;
27572
+ this.queryStreamController = new MyInvitationsQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareMyInvitationsPayload);
27573
+ this.callback = callback.bind(this);
27574
+ this.loadPage({ initial: true });
27575
+ }
27576
+ setup() {
27577
+ var _a;
27578
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27579
+ if (!collection) {
27580
+ pushToCache(this.cacheKey, {
27581
+ data: [],
27582
+ params: this.query,
27583
+ });
27584
+ }
27585
+ }
27586
+ async persistModel(queryPayload) {
27587
+ await this.queryStreamController.saveToMainDB(queryPayload);
27588
+ }
27589
+ persistQueryStream({ response, direction, refresh, }) {
27590
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
27591
+ }
27592
+ startSubscription() {
27593
+ return this.queryStreamController.subscribeRTE([
27594
+ {
27595
+ fn: onLocalInvitationCreated,
27596
+ action: InvitationActionsEnum.OnLocalInvitationCreated,
27597
+ },
27598
+ {
27599
+ fn: onLocalInvitationUpdated,
27600
+ action: InvitationActionsEnum.OnLocalInvitationUpdated,
27601
+ },
27602
+ {
27603
+ fn: onLocalInvitationDeleted,
27604
+ action: InvitationActionsEnum.OnLocalInvitationDeleted,
27605
+ },
27606
+ ]);
27607
+ }
27608
+ notifyChange({ origin, loading, error }) {
27609
+ var _a, _b;
27610
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27611
+ if (!collection)
27612
+ return;
27613
+ const data = this.applyFilter((_b = collection.data
27614
+ .map(id => pullFromCache(['invitation', 'get', id]))
27615
+ .filter(isNonNullable)
27616
+ .map(({ data }) => invitationLinkedObject(data))) !== null && _b !== void 0 ? _b : []);
27617
+ if (!this.shouldNotify(data) && origin === 'event')
27618
+ return;
27619
+ this.callback({
27620
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
27621
+ data,
27622
+ hasNextPage: !!this.paginationController.getNextToken(),
27623
+ loading,
27624
+ error,
27625
+ });
27626
+ }
27627
+ applyFilter(data) {
27628
+ let invitations = data;
27629
+ if (this.query.targetId) {
27630
+ invitations = invitations.filter(invitation => invitation.targetId === this.query.targetId);
27631
+ }
27632
+ if (this.query.statuses) {
27633
+ invitations = invitations.filter(invitation => { var _a; return (_a = this.query.statuses) === null || _a === void 0 ? void 0 : _a.includes(invitation.status); });
27634
+ }
27635
+ if (this.query.targetType) {
27636
+ invitations = invitations.filter(invitation => invitation.targetType === this.query.targetType);
27637
+ }
27638
+ if (this.query.type) {
27639
+ invitations = invitations.filter(invitation => invitation.type === this.query.type);
27640
+ }
27641
+ const sortFn = (() => {
27642
+ switch (this.query.sortBy) {
27643
+ case 'firstCreated':
27644
+ return sortByFirstCreated;
27645
+ case 'lastCreated':
27646
+ return sortByLastCreated;
27647
+ default:
27648
+ return sortByLastCreated;
27649
+ }
27650
+ })();
27651
+ invitations = invitations.sort(sortFn);
27652
+ return invitations;
27653
+ }
27654
+ }
27655
+
27656
+ /**
27657
+ * Get my community invitations
27658
+ *
27659
+ * @param params the query parameters
27660
+ * @param callback the callback to be called when the invitations are fetched
27661
+ * @returns invitations
27662
+ *
27663
+ * @category My Community Invitations Live Collection
27664
+ *
27665
+ */
27666
+ const getMyCommunityInvitations = (params, callback, config) => {
27667
+ const { log, cache } = getActiveClient();
27668
+ if (!cache) {
27669
+ console.log(ENABLE_CACHE_MESSAGE);
27670
+ }
27671
+ const timestamp = Date.now();
27672
+ log(`getMyCommunityInvitations: (tmpid: ${timestamp}) > listen`);
27673
+ const invitationsLiveCollection = new MyInvitationsLiveCollectionController(Object.assign(Object.assign({}, params), { targetType: 'community', statuses: ["pending" /* InvitationStatusEnum.Pending */] }), callback);
27674
+ const disposers = invitationsLiveCollection.startSubscription();
27675
+ const cacheKey = invitationsLiveCollection.getCacheKey();
27676
+ disposers.push(() => {
27677
+ dropFromCache(cacheKey);
27678
+ });
27679
+ return () => {
27680
+ log(`getInvitations (tmpid: ${timestamp}) > dispose`);
27681
+ disposers.forEach(fn => fn());
27682
+ };
27683
+ };
27684
+
27685
+ var index = /*#__PURE__*/Object.freeze({
27686
+ __proto__: null,
27687
+ onLocalInvitationCreated: onLocalInvitationCreated,
27688
+ onLocalInvitationUpdated: onLocalInvitationUpdated,
27689
+ onLocalInvitationDeleted: onLocalInvitationDeleted,
27690
+ getMyCommunityInvitations: getMyCommunityInvitations
27691
+ });
27692
+
26434
27693
  exports.API_REGIONS = API_REGIONS;
26435
- exports.AdRepository = index$1;
26436
- exports.CategoryRepository = index$9;
26437
- exports.ChannelRepository = index$d;
26438
- exports.Client = index$m;
26439
- exports.CommentRepository = index$7;
27694
+ exports.AdRepository = index$2;
27695
+ exports.CategoryRepository = index$a;
27696
+ exports.ChannelRepository = index$e;
27697
+ exports.Client = index$n;
27698
+ exports.CommentRepository = index$8;
26440
27699
  exports.CommunityPostSettingMaps = CommunityPostSettingMaps;
26441
27700
  exports.CommunityPostSettings = CommunityPostSettings;
26442
- exports.CommunityRepository = index$a;
27701
+ exports.CommunityRepository = index$b;
26443
27702
  exports.ContentFeedType = ContentFeedType;
26444
27703
  exports.DefaultCommunityPostSetting = DefaultCommunityPostSetting;
26445
- exports.FeedRepository = index$8;
26446
- exports.FileRepository = index$j;
27704
+ exports.FeedRepository = index$9;
27705
+ exports.FileRepository = index$k;
26447
27706
  exports.FileType = FileType;
26448
- exports.LiveStreamPlayer = index$3;
27707
+ exports.InvitationRepository = index;
27708
+ exports.LiveStreamPlayer = index$4;
26449
27709
  exports.MessageContentType = MessageContentType;
26450
- exports.MessageRepository = index$h;
26451
- exports.PollRepository = index$4;
27710
+ exports.MessageRepository = index$i;
27711
+ exports.PollRepository = index$5;
26452
27712
  exports.PostContentType = PostContentType;
26453
- exports.PostRepository = index$6;
26454
- exports.ReactionRepository = index$i;
26455
- exports.StoryRepository = index$2;
26456
- exports.StreamRepository = index$5;
26457
- exports.SubChannelRepository = index$g;
26458
- exports.UserRepository = index$k;
27713
+ exports.PostRepository = index$7;
27714
+ exports.ReactionRepository = index$j;
27715
+ exports.StoryRepository = index$3;
27716
+ exports.StreamRepository = index$6;
27717
+ exports.SubChannelRepository = index$h;
27718
+ exports.UserRepository = index$l;
26459
27719
  exports.VERSION = VERSION;
26460
27720
  exports.VideoResolution = VideoResolution;
26461
27721
  exports.VideoSize = VideoSize;
@@ -26508,7 +27768,7 @@ exports.isPaged = isPaged;
26508
27768
  exports.isReportedByMe = isReportedByMe;
26509
27769
  exports.isSkip = isSkip;
26510
27770
  exports.mergeInCache = mergeInCache;
26511
- exports.notificationTray = index;
27771
+ exports.notificationTray = index$1;
26512
27772
  exports.onChannelMarkerFetched = onChannelMarkerFetched;
26513
27773
  exports.onFeedMarkerFetched = onFeedMarkerFetched;
26514
27774
  exports.onFeedMarkerUpdated = onFeedMarkerUpdated;