@amityco/ts-sdk 0.0.1-beta.33 → 0.0.1-beta.36

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 (545) hide show
  1. package/dist/@types/core/events.d.ts +47 -22
  2. package/dist/@types/core/events.d.ts.map +1 -1
  3. package/dist/@types/core/model.d.ts +2 -0
  4. package/dist/@types/core/model.d.ts.map +1 -1
  5. package/dist/@types/core/payload.d.ts +15 -5
  6. package/dist/@types/core/payload.d.ts.map +1 -1
  7. package/dist/@types/domains/channel.d.ts +12 -7
  8. package/dist/@types/domains/channel.d.ts.map +1 -1
  9. package/dist/@types/domains/client.d.ts +19 -0
  10. package/dist/@types/domains/client.d.ts.map +1 -1
  11. package/dist/@types/domains/content.d.ts +2 -3
  12. package/dist/@types/domains/content.d.ts.map +1 -1
  13. package/dist/@types/domains/group.d.ts +6 -2
  14. package/dist/@types/domains/group.d.ts.map +1 -1
  15. package/dist/@types/domains/message.d.ts +37 -17
  16. package/dist/@types/domains/message.d.ts.map +1 -1
  17. package/dist/@types/domains/post.d.ts +2 -2
  18. package/dist/@types/domains/post.d.ts.map +1 -1
  19. package/dist/@types/domains/subChannel.d.ts +39 -0
  20. package/dist/@types/domains/subChannel.d.ts.map +1 -0
  21. package/dist/@types/index.d.ts +1 -0
  22. package/dist/@types/index.d.ts.map +1 -1
  23. package/dist/cache/api/tests/dropFromCache.test.d.ts +2 -0
  24. package/dist/cache/api/tests/dropFromCache.test.d.ts.map +1 -0
  25. package/dist/cache/api/tests/enableCache.test.d.ts +2 -0
  26. package/dist/cache/api/tests/enableCache.test.d.ts.map +1 -0
  27. package/dist/cache/api/tests/pullFromCache.test.d.ts +2 -0
  28. package/dist/cache/api/tests/pullFromCache.test.d.ts.map +1 -0
  29. package/dist/cache/api/tests/upsertInCache.test.d.ts +2 -0
  30. package/dist/cache/api/tests/upsertInCache.test.d.ts.map +1 -0
  31. package/dist/cache/utils/tests/encodeKey.test.d.ts +2 -0
  32. package/dist/cache/utils/tests/encodeKey.test.d.ts.map +1 -0
  33. package/dist/cache/utils/tests/partialMatch.test.d.ts +2 -0
  34. package/dist/cache/utils/tests/partialMatch.test.d.ts.map +1 -0
  35. package/dist/channel/api/banChannelMembers.d.ts.map +1 -1
  36. package/dist/channel/api/createChannel.d.ts +1 -1
  37. package/dist/channel/api/index.d.ts +2 -0
  38. package/dist/channel/api/index.d.ts.map +1 -1
  39. package/dist/channel/api/queryChannelMembers.d.ts.map +1 -1
  40. package/dist/channel/api/removeChannelMembers.d.ts.map +1 -1
  41. package/dist/channel/api/startReading.d.ts +17 -0
  42. package/dist/channel/api/startReading.d.ts.map +1 -0
  43. package/dist/channel/api/stopReading.d.ts +16 -0
  44. package/dist/channel/api/stopReading.d.ts.map +1 -0
  45. package/dist/channel/api/tests/createChannel.test.d.ts +2 -0
  46. package/dist/channel/api/tests/createChannel.test.d.ts.map +1 -0
  47. package/dist/channel/api/tests/joinChannel.test.d.ts +2 -0
  48. package/dist/channel/api/tests/joinChannel.test.d.ts.map +1 -0
  49. package/dist/channel/api/tests/removeChannelMembers.test.d.ts +2 -0
  50. package/dist/channel/api/tests/removeChannelMembers.test.d.ts.map +1 -0
  51. package/dist/channel/api/tests/startReading.test.d.ts +2 -0
  52. package/dist/channel/api/tests/startReading.test.d.ts.map +1 -0
  53. package/dist/channel/api/tests/stopReading.test.d.ts +2 -0
  54. package/dist/channel/api/tests/stopReading.test.d.ts.map +1 -0
  55. package/dist/channel/api/unbanChannelMembers.d.ts.map +1 -1
  56. package/dist/channel/events/index.d.ts +1 -0
  57. package/dist/channel/events/index.d.ts.map +1 -1
  58. package/dist/channel/events/onChannelJoined.d.ts +2 -2
  59. package/dist/channel/events/onChannelJoined.d.ts.map +1 -1
  60. package/dist/channel/events/onChannelLeft.d.ts +2 -2
  61. package/dist/channel/events/onChannelLeft.d.ts.map +1 -1
  62. package/dist/channel/events/onChannelMemberAdded.d.ts.map +1 -1
  63. package/dist/channel/events/onChannelMemberBanned.d.ts.map +1 -1
  64. package/dist/channel/events/onChannelMemberRemoved.d.ts.map +1 -1
  65. package/dist/channel/events/onChannelMemberUnbanned.d.ts.map +1 -1
  66. package/dist/channel/events/onChannelMuted.d.ts +17 -0
  67. package/dist/channel/events/onChannelMuted.d.ts.map +1 -0
  68. package/dist/channel/events/onChannelUpdated.d.ts +1 -1
  69. package/dist/channel/events/onChannelUpdated.d.ts.map +1 -1
  70. package/dist/channel/events/tests/onChannelCreated.test.d.ts +2 -0
  71. package/dist/channel/events/tests/onChannelCreated.test.d.ts.map +1 -0
  72. package/dist/channel/events/tests/onChannelJoined.test.d.ts +2 -0
  73. package/dist/channel/events/tests/onChannelJoined.test.d.ts.map +1 -0
  74. package/dist/channel/events/tests/onChannelMemberAdded.test.d.ts +2 -0
  75. package/dist/channel/events/tests/onChannelMemberAdded.test.d.ts.map +1 -0
  76. package/dist/channel/events/tests/onChannelMemberRemoved.test.d.ts +2 -0
  77. package/dist/channel/events/tests/onChannelMemberRemoved.test.d.ts.map +1 -0
  78. package/dist/channel/events/tests/onChannelUpdated.test.d.ts +2 -0
  79. package/dist/channel/events/tests/onChannelUpdated.test.d.ts.map +1 -0
  80. package/dist/channel/observers/index.d.ts +1 -0
  81. package/dist/channel/observers/index.d.ts.map +1 -1
  82. package/dist/channel/observers/liveChannel.d.ts +21 -0
  83. package/dist/channel/observers/liveChannel.d.ts.map +1 -0
  84. package/dist/channel/observers/liveChannelMembers.d.ts.map +1 -1
  85. package/dist/channel/observers/liveChannels.d.ts.map +1 -1
  86. package/dist/channel/observers/observeChannel.d.ts +1 -1
  87. package/dist/channel/observers/observeChannel.d.ts.map +1 -1
  88. package/dist/channel/observers/observeChannels.d.ts.map +1 -1
  89. package/dist/channel/utils/index.d.ts +2 -1
  90. package/dist/channel/utils/index.d.ts.map +1 -1
  91. package/dist/client/api/connectClient.d.ts.map +1 -1
  92. package/dist/client/api/getChatSettings.d.ts +15 -0
  93. package/dist/client/api/getChatSettings.d.ts.map +1 -0
  94. package/dist/client/api/getSocialSettings.d.ts +15 -0
  95. package/dist/client/api/getSocialSettings.d.ts.map +1 -0
  96. package/dist/client/api/tests/activeClient.test.d.ts +2 -0
  97. package/dist/client/api/tests/activeClient.test.d.ts.map +1 -0
  98. package/dist/client/api/tests/activeUser.test.d.ts +2 -0
  99. package/dist/client/api/tests/activeUser.test.d.ts.map +1 -0
  100. package/dist/client/api/tests/createClient.test.d.ts +2 -0
  101. package/dist/client/api/tests/createClient.test.d.ts.map +1 -0
  102. package/dist/client/tests/connectClient.test.d.ts +2 -0
  103. package/dist/client/tests/connectClient.test.d.ts.map +1 -0
  104. package/dist/comment/api/createComment.d.ts +1 -1
  105. package/dist/comment/api/createComment.d.ts.map +1 -1
  106. package/dist/comment/api/tests/createComment.test.d.ts +2 -0
  107. package/dist/comment/api/tests/createComment.test.d.ts.map +1 -0
  108. package/dist/comment/api/tests/getComments.test.d.ts +2 -0
  109. package/dist/comment/api/tests/getComments.test.d.ts.map +1 -0
  110. package/dist/comment/events/tests/onCommentCreated.test.d.ts +2 -0
  111. package/dist/comment/events/tests/onCommentCreated.test.d.ts.map +1 -0
  112. package/dist/comment/events/utils.d.ts +1 -1
  113. package/dist/comment/events/utils.d.ts.map +1 -1
  114. package/dist/community/api/queryCommunities.d.ts.map +1 -1
  115. package/dist/community/api/queryCommunityMembers.d.ts +6 -1
  116. package/dist/community/api/queryCommunityMembers.d.ts.map +1 -1
  117. package/dist/community/api/test/addCommunityMember.test.d.ts +2 -0
  118. package/dist/community/api/test/addCommunityMember.test.d.ts.map +1 -0
  119. package/dist/community/api/test/addCommunityMemberRole.test.d.ts +2 -0
  120. package/dist/community/api/test/addCommunityMemberRole.test.d.ts.map +1 -0
  121. package/dist/community/api/test/createCommunity.test.d.ts +2 -0
  122. package/dist/community/api/test/createCommunity.test.d.ts.map +1 -0
  123. package/dist/community/api/test/deleteCommunity.test.d.ts +2 -0
  124. package/dist/community/api/test/deleteCommunity.test.d.ts.map +1 -0
  125. package/dist/community/api/test/getCommunities.test.d.ts +2 -0
  126. package/dist/community/api/test/getCommunities.test.d.ts.map +1 -0
  127. package/dist/community/api/test/getCommunity.test.d.ts +2 -0
  128. package/dist/community/api/test/getCommunity.test.d.ts.map +1 -0
  129. package/dist/community/api/test/getRecommendedCommunities.test.d.ts +2 -0
  130. package/dist/community/api/test/getRecommendedCommunities.test.d.ts.map +1 -0
  131. package/dist/community/api/test/getTopTrendingCommunities.test.d.ts +2 -0
  132. package/dist/community/api/test/getTopTrendingCommunities.test.d.ts.map +1 -0
  133. package/dist/community/api/test/joinCommunity.test.d.ts +2 -0
  134. package/dist/community/api/test/joinCommunity.test.d.ts.map +1 -0
  135. package/dist/community/api/test/leaveCommunity.test.d.ts +2 -0
  136. package/dist/community/api/test/leaveCommunity.test.d.ts.map +1 -0
  137. package/dist/community/api/test/queryCommunity.test.d.ts +2 -0
  138. package/dist/community/api/test/queryCommunity.test.d.ts.map +1 -0
  139. package/dist/community/api/test/queryCommunityMembers.test.d.ts +2 -0
  140. package/dist/community/api/test/queryCommunityMembers.test.d.ts.map +1 -0
  141. package/dist/community/api/test/removeCommunityMemberRole.test.d.ts +2 -0
  142. package/dist/community/api/test/removeCommunityMemberRole.test.d.ts.map +1 -0
  143. package/dist/community/api/test/removeCommunityMembers.test.d.ts +2 -0
  144. package/dist/community/api/test/removeCommunityMembers.test.d.ts.map +1 -0
  145. package/dist/community/api/test/updateCommunity.test.d.ts +2 -0
  146. package/dist/community/api/test/updateCommunity.test.d.ts.map +1 -0
  147. package/dist/community/events/test/onCommunityCreated.test.d.ts +2 -0
  148. package/dist/community/events/test/onCommunityCreated.test.d.ts.map +1 -0
  149. package/dist/community/events/test/onCommunityDeleted.test.d.ts +2 -0
  150. package/dist/community/events/test/onCommunityDeleted.test.d.ts.map +1 -0
  151. package/dist/community/events/test/onCommunityJoined.test.d.ts +2 -0
  152. package/dist/community/events/test/onCommunityJoined.test.d.ts.map +1 -0
  153. package/dist/community/events/test/onCommunityLeft.test.d.ts +2 -0
  154. package/dist/community/events/test/onCommunityLeft.test.d.ts.map +1 -0
  155. package/dist/community/events/test/onCommunityUpdated.test.d.ts +2 -0
  156. package/dist/community/events/test/onCommunityUpdated.test.d.ts.map +1 -0
  157. package/dist/community/events/test/onCommunityUserAdded.test.d.ts +2 -0
  158. package/dist/community/events/test/onCommunityUserAdded.test.d.ts.map +1 -0
  159. package/dist/community/events/test/onCommunityUserBanned.test.d.ts +2 -0
  160. package/dist/community/events/test/onCommunityUserBanned.test.d.ts.map +1 -0
  161. package/dist/community/events/test/onCommunityUserRemoved.test.d.ts +2 -0
  162. package/dist/community/events/test/onCommunityUserRemoved.test.d.ts.map +1 -0
  163. package/dist/community/events/test/onCommunityUserUnbaned.test.d.ts +2 -0
  164. package/dist/community/events/test/onCommunityUserUnbaned.test.d.ts.map +1 -0
  165. package/dist/community/events/test/utils.test.d.ts +2 -0
  166. package/dist/community/events/test/utils.test.d.ts.map +1 -0
  167. package/dist/community/events/utils.d.ts +2 -2
  168. package/dist/community/events/utils.d.ts.map +1 -1
  169. package/dist/core/events.d.ts +3 -3
  170. package/dist/core/events.d.ts.map +1 -1
  171. package/dist/core/model/idResolvers.d.ts.map +1 -1
  172. package/dist/core/model/identifyModel.d.ts.map +1 -1
  173. package/dist/core/model/index.d.ts +5 -0
  174. package/dist/core/model/index.d.ts.map +1 -1
  175. package/dist/core/query/filtering.d.ts.map +1 -1
  176. package/dist/core/query/query.d.ts.map +1 -1
  177. package/dist/core/subscription.d.ts +26 -1
  178. package/dist/core/subscription.d.ts.map +1 -1
  179. package/dist/core/tests/subscription.test.d.ts +2 -0
  180. package/dist/core/tests/subscription.test.d.ts.map +1 -0
  181. package/dist/feed/api/queryGlobalFeed.d.ts +1 -1
  182. package/dist/feed/api/queryGlobalFeed.d.ts.map +1 -1
  183. package/dist/feed/api/test/queryGlobalFeed.test.d.ts +2 -0
  184. package/dist/feed/api/test/queryGlobalFeed.test.d.ts.map +1 -0
  185. package/dist/follow/events/utils.d.ts +1 -1
  186. package/dist/follow/events/utils.d.ts.map +1 -1
  187. package/dist/group/utils/index.d.ts +2 -0
  188. package/dist/group/utils/index.d.ts.map +1 -0
  189. package/dist/group/utils/test/withUsers.test.d.ts +2 -0
  190. package/dist/group/utils/test/withUsers.test.d.ts.map +1 -0
  191. package/dist/group/utils/withUser.d.ts +38 -0
  192. package/dist/group/utils/withUser.d.ts.map +1 -0
  193. package/dist/index.cjs.js +2027 -812
  194. package/dist/index.d.ts +3 -0
  195. package/dist/index.d.ts.map +1 -1
  196. package/dist/index.esm.js +2002 -811
  197. package/dist/index.umd.js +4 -4
  198. package/dist/message/api/createMessage.d.ts +15 -9
  199. package/dist/message/api/createMessage.d.ts.map +1 -1
  200. package/dist/message/api/deleteMessage.d.ts +2 -2
  201. package/dist/message/api/getMessage.d.ts.map +1 -1
  202. package/dist/message/api/getMessages.d.ts.map +1 -1
  203. package/dist/message/api/queryMessages.d.ts.map +1 -1
  204. package/dist/message/api/updateMessage.d.ts +1 -1
  205. package/dist/message/api/updateMessage.d.ts.map +1 -1
  206. package/dist/message/events/index.d.ts +5 -1
  207. package/dist/message/events/index.d.ts.map +1 -1
  208. package/dist/message/events/onMessageCreated.d.ts.map +1 -1
  209. package/dist/message/events/onMessageDeleted.d.ts.map +1 -1
  210. package/dist/message/events/onMessageFlagCleared.d.ts +17 -0
  211. package/dist/message/events/onMessageFlagCleared.d.ts.map +1 -0
  212. package/dist/message/events/onMessageFlagged.d.ts +17 -0
  213. package/dist/message/events/onMessageFlagged.d.ts.map +1 -0
  214. package/dist/message/events/onMessageReactionAdded.d.ts +18 -0
  215. package/dist/message/events/onMessageReactionAdded.d.ts.map +1 -0
  216. package/dist/message/events/onMessageReactionRemoved.d.ts +18 -0
  217. package/dist/message/events/onMessageReactionRemoved.d.ts.map +1 -0
  218. package/dist/message/events/onMessageUnflagged.d.ts +17 -0
  219. package/dist/message/events/onMessageUnflagged.d.ts.map +1 -0
  220. package/dist/message/events/onMessageUpdated.d.ts.map +1 -1
  221. package/dist/message/observers/liveMessage.d.ts +7 -4
  222. package/dist/message/observers/liveMessage.d.ts.map +1 -1
  223. package/dist/message/observers/liveMessages.d.ts +7 -6
  224. package/dist/message/observers/liveMessages.d.ts.map +1 -1
  225. package/dist/message/observers/observeMessage.d.ts +1 -0
  226. package/dist/message/observers/observeMessage.d.ts.map +1 -1
  227. package/dist/message/observers/observeMessages.d.ts +5 -4
  228. package/dist/message/observers/observeMessages.d.ts.map +1 -1
  229. package/dist/message/tests/events.test.d.ts +2 -0
  230. package/dist/message/tests/events.test.d.ts.map +1 -0
  231. package/dist/message/utils/index.d.ts +18 -0
  232. package/dist/message/utils/index.d.ts.map +1 -0
  233. package/dist/post/api/queryPosts.d.ts.map +1 -1
  234. package/dist/post/api/tests/queryPosts.test.d.ts +2 -0
  235. package/dist/post/api/tests/queryPosts.test.d.ts.map +1 -0
  236. package/dist/post/events/tests/onPostApproved.test.d.ts +2 -0
  237. package/dist/post/events/tests/onPostApproved.test.d.ts.map +1 -0
  238. package/dist/post/events/tests/onPostCreated.test.d.ts +2 -0
  239. package/dist/post/events/tests/onPostCreated.test.d.ts.map +1 -0
  240. package/dist/post/events/tests/onPostDeclined.test.d.ts +2 -0
  241. package/dist/post/events/tests/onPostDeclined.test.d.ts.map +1 -0
  242. package/dist/post/events/tests/onPostDeleted.test.d.ts +2 -0
  243. package/dist/post/events/tests/onPostDeleted.test.d.ts.map +1 -0
  244. package/dist/post/events/tests/onPostFlagged.test.d.ts +2 -0
  245. package/dist/post/events/tests/onPostFlagged.test.d.ts.map +1 -0
  246. package/dist/post/events/tests/onPostReactionAdded.test.d.ts +2 -0
  247. package/dist/post/events/tests/onPostReactionAdded.test.d.ts.map +1 -0
  248. package/dist/post/events/tests/onPostReactionRemoved.test.d.ts +2 -0
  249. package/dist/post/events/tests/onPostReactionRemoved.test.d.ts.map +1 -0
  250. package/dist/post/events/tests/onPostUnflagged.test.d.ts +2 -0
  251. package/dist/post/events/tests/onPostUnflagged.test.d.ts.map +1 -0
  252. package/dist/post/events/tests/onPostUpdated.test.d.ts +2 -0
  253. package/dist/post/events/tests/onPostUpdated.test.d.ts.map +1 -0
  254. package/dist/post/events/utils.d.ts +1 -1
  255. package/dist/post/events/utils.d.ts.map +1 -1
  256. package/dist/post/observers/livePosts.d.ts.map +1 -1
  257. package/dist/post/observers/tests/livePosts.test.d.ts +2 -0
  258. package/dist/post/observers/tests/livePosts.test.d.ts.map +1 -0
  259. package/dist/reaction/api/addReaction.d.ts.map +1 -1
  260. package/dist/reaction/api/removeReaction.d.ts.map +1 -1
  261. package/dist/reaction/events/onReactionAdded.d.ts.map +1 -1
  262. package/dist/reaction/events/onReactionRemoved.d.ts.map +1 -1
  263. package/dist/reaction/events/onReactorAdded.d.ts.map +1 -1
  264. package/dist/reaction/events/onReactorRemoved.d.ts.map +1 -1
  265. package/dist/report/api/createReport.d.ts.map +1 -1
  266. package/dist/report/api/deleteReport.d.ts.map +1 -1
  267. package/dist/report/api/isReportedByMe.d.ts.map +1 -1
  268. package/dist/subChannel/api/createSubChannel.d.ts +16 -0
  269. package/dist/subChannel/api/createSubChannel.d.ts.map +1 -0
  270. package/dist/subChannel/api/deleteSubChannel.d.ts +16 -0
  271. package/dist/subChannel/api/deleteSubChannel.d.ts.map +1 -0
  272. package/dist/subChannel/api/getSubChannel.d.ts +32 -0
  273. package/dist/subChannel/api/getSubChannel.d.ts.map +1 -0
  274. package/dist/subChannel/api/getSubChannels.d.ts +32 -0
  275. package/dist/subChannel/api/getSubChannels.d.ts.map +1 -0
  276. package/dist/subChannel/api/index.d.ts +7 -0
  277. package/dist/subChannel/api/index.d.ts.map +1 -0
  278. package/dist/subChannel/api/querySubChannels.d.ts +32 -0
  279. package/dist/subChannel/api/querySubChannels.d.ts.map +1 -0
  280. package/dist/subChannel/api/updateSubChannel.d.ts +17 -0
  281. package/dist/subChannel/api/updateSubChannel.d.ts.map +1 -0
  282. package/dist/subChannel/events/index.d.ts +4 -0
  283. package/dist/subChannel/events/index.d.ts.map +1 -0
  284. package/dist/subChannel/events/onSubChannelCreated.d.ts +17 -0
  285. package/dist/subChannel/events/onSubChannelCreated.d.ts.map +1 -0
  286. package/dist/subChannel/events/onSubChannelDeleted.d.ts +17 -0
  287. package/dist/subChannel/events/onSubChannelDeleted.d.ts.map +1 -0
  288. package/dist/subChannel/events/onSubChannelFetched.d.ts +3 -0
  289. package/dist/subChannel/events/onSubChannelFetched.d.ts.map +1 -0
  290. package/dist/subChannel/events/onSubChannelUpdated.d.ts +17 -0
  291. package/dist/subChannel/events/onSubChannelUpdated.d.ts.map +1 -0
  292. package/dist/subChannel/observers/index.d.ts +3 -0
  293. package/dist/subChannel/observers/index.d.ts.map +1 -0
  294. package/dist/subChannel/observers/liveSubChannel.d.ts +21 -0
  295. package/dist/subChannel/observers/liveSubChannel.d.ts.map +1 -0
  296. package/dist/subChannel/observers/liveSubChannels.d.ts +21 -0
  297. package/dist/subChannel/observers/liveSubChannels.d.ts.map +1 -0
  298. package/dist/subChannel/observers/tests/liveSubChannel.test.d.ts +2 -0
  299. package/dist/subChannel/observers/tests/liveSubChannel.test.d.ts.map +1 -0
  300. package/dist/subChannel/observers/tests/liveSubChannels.test.d.ts +2 -0
  301. package/dist/subChannel/observers/tests/liveSubChannels.test.d.ts.map +1 -0
  302. package/dist/subChannel/utils/index.d.ts +8 -0
  303. package/dist/subChannel/utils/index.d.ts.map +1 -0
  304. package/dist/user/events/index.d.ts +0 -1
  305. package/dist/user/events/index.d.ts.map +1 -1
  306. package/dist/user/events/utils.d.ts +1 -1
  307. package/dist/user/events/utils.d.ts.map +1 -1
  308. package/dist/user/observers/liveUser.d.ts +7 -4
  309. package/dist/user/observers/liveUser.d.ts.map +1 -1
  310. package/dist/utils/index.d.ts +4 -0
  311. package/dist/utils/index.d.ts.map +1 -0
  312. package/dist/utils/tests/dummy/channel.d.ts +47 -22
  313. package/dist/utils/tests/dummy/channel.d.ts.map +1 -1
  314. package/dist/utils/tests/dummy/community.d.ts +33 -1
  315. package/dist/utils/tests/dummy/community.d.ts.map +1 -1
  316. package/dist/utils/tests/dummy/index.d.ts +3 -1
  317. package/dist/utils/tests/dummy/index.d.ts.map +1 -1
  318. package/dist/utils/tests/dummy/member.d.ts +2 -0
  319. package/dist/utils/tests/dummy/member.d.ts.map +1 -0
  320. package/dist/utils/tests/dummy/message.d.ts +2 -1
  321. package/dist/utils/tests/dummy/message.d.ts.map +1 -1
  322. package/dist/utils/tests/dummy/post.d.ts +15 -0
  323. package/dist/utils/tests/dummy/post.d.ts.map +1 -1
  324. package/dist/utils/tests/dummy/subChannel.d.ts +3 -0
  325. package/dist/utils/tests/dummy/subChannel.d.ts.map +1 -0
  326. package/dist/utils/tests/dummy/user.d.ts +1 -0
  327. package/dist/utils/tests/dummy/user.d.ts.map +1 -1
  328. package/dist/utils/tests/utils.d.ts +1 -0
  329. package/dist/utils/tests/utils.d.ts.map +1 -1
  330. package/package.json +1 -1
  331. package/src/@types/core/events.ts +56 -28
  332. package/src/@types/core/model.ts +2 -0
  333. package/src/@types/core/payload.ts +21 -5
  334. package/src/@types/domains/channel.ts +23 -6
  335. package/src/@types/domains/client.ts +21 -0
  336. package/src/@types/domains/content.ts +4 -3
  337. package/src/@types/domains/group.ts +6 -2
  338. package/src/@types/domains/message.ts +59 -26
  339. package/src/@types/domains/post.ts +2 -2
  340. package/src/@types/domains/subChannel.ts +48 -0
  341. package/src/@types/index.ts +1 -0
  342. package/src/cache/api/tests/dropFromCache.test.ts +59 -0
  343. package/src/cache/api/tests/enableCache.test.ts +15 -0
  344. package/src/cache/api/tests/pullFromCache.test.ts +42 -0
  345. package/src/cache/api/tests/upsertInCache.test.ts +60 -0
  346. package/src/cache/utils/tests/encodeKey.test.ts +19 -0
  347. package/src/cache/utils/tests/partialMatch.test.ts +13 -0
  348. package/src/channel/api/addChannelMembers.ts +2 -2
  349. package/src/channel/api/banChannelMembers.ts +5 -3
  350. package/src/channel/api/createChannel.ts +1 -1
  351. package/src/channel/api/getChannels.ts +2 -2
  352. package/src/channel/api/index.ts +3 -0
  353. package/src/channel/api/queryChannelMembers.ts +15 -10
  354. package/src/channel/api/queryChannels.ts +1 -1
  355. package/src/channel/api/removeChannelMembers.ts +9 -1
  356. package/src/channel/api/startReading.ts +53 -0
  357. package/src/channel/api/stopReading.ts +49 -0
  358. package/src/channel/api/tests/addChannelMembers.test.ts +36 -8
  359. package/src/channel/api/tests/createChannel.test.ts +53 -0
  360. package/src/channel/api/tests/getChannel.test.ts +3 -2
  361. package/src/channel/api/tests/joinChannel.test.ts +52 -0
  362. package/src/channel/api/tests/queryChannelMembers.test.ts +27 -11
  363. package/src/channel/api/tests/queryChannels.test.ts +2 -2
  364. package/src/channel/api/tests/removeChannelMembers.test.ts +95 -0
  365. package/src/channel/api/tests/startReading.test.ts +25 -0
  366. package/src/channel/api/tests/stopReading.test.ts +25 -0
  367. package/src/channel/api/unbanChannelMembers.ts +6 -3
  368. package/src/channel/events/index.ts +1 -0
  369. package/src/channel/events/onChannelCreated.ts +1 -1
  370. package/src/channel/events/onChannelDeleted.ts +1 -1
  371. package/src/channel/events/onChannelJoined.ts +12 -7
  372. package/src/channel/events/onChannelLeft.ts +12 -7
  373. package/src/channel/events/onChannelMemberAdded.ts +8 -6
  374. package/src/channel/events/onChannelMemberBanned.ts +7 -4
  375. package/src/channel/events/onChannelMemberRemoved.ts +7 -9
  376. package/src/channel/events/onChannelMemberUnbanned.ts +7 -4
  377. package/src/channel/events/onChannelMuted.ts +34 -0
  378. package/src/channel/events/onChannelUpdated.ts +10 -1
  379. package/src/channel/events/tests/onChannelCreated.test.ts +55 -0
  380. package/src/channel/events/tests/onChannelJoined.test.ts +56 -0
  381. package/src/channel/events/tests/onChannelMemberAdded.test.ts +56 -0
  382. package/src/channel/events/tests/onChannelMemberBanned.test.ts +13 -12
  383. package/src/channel/events/tests/onChannelMemberRemoved.test.ts +56 -0
  384. package/src/channel/events/tests/onChannelMemberUnbanned.test.ts +13 -12
  385. package/src/channel/events/tests/onChannelUpdated.test.ts +55 -0
  386. package/src/channel/observers/index.ts +1 -0
  387. package/src/channel/observers/liveChannel.ts +108 -0
  388. package/src/channel/observers/liveChannelMembers.ts +40 -34
  389. package/src/channel/observers/liveChannels.ts +25 -14
  390. package/src/channel/observers/observeChannel.ts +2 -0
  391. package/src/channel/observers/observeChannels.ts +2 -0
  392. package/src/channel/observers/tests/liveChannelMembers.test.ts +107 -95
  393. package/src/channel/observers/tests/liveChannels.test.ts +385 -126
  394. package/src/channel/utils/index.ts +54 -1
  395. package/src/channel/utils/tests/prepareChannelPayload.test.ts +22 -22
  396. package/src/client/api/connectClient.ts +11 -4
  397. package/src/client/api/createClient.ts +1 -1
  398. package/src/client/api/getChatSettings.ts +22 -0
  399. package/src/client/api/getSocialSettings.ts +24 -0
  400. package/src/client/api/tests/activeClient.test.ts +20 -0
  401. package/src/client/api/tests/activeUser.test.ts +20 -0
  402. package/src/client/api/tests/createClient.test.ts +40 -0
  403. package/src/client/tests/connectClient.test.ts +35 -0
  404. package/src/comment/api/createComment.ts +3 -3
  405. package/src/comment/api/tests/createComment.test.ts +49 -0
  406. package/src/comment/api/tests/getComments.test.ts +36 -0
  407. package/src/comment/events/tests/onCommentCreated.test.ts +27 -0
  408. package/src/comment/events/utils.ts +1 -1
  409. package/src/comment/observers/liveComments.ts +8 -8
  410. package/src/community/api/queryCommunities.ts +3 -2
  411. package/src/community/api/queryCommunityMembers.ts +59 -14
  412. package/src/community/api/test/addCommunityMember.test.ts +71 -0
  413. package/src/community/api/test/addCommunityMemberRole.test.ts +67 -0
  414. package/src/community/api/test/createCommunity.test.ts +61 -0
  415. package/src/community/api/test/deleteCommunity.test.ts +74 -0
  416. package/src/community/api/test/getCommunities.test.ts +73 -0
  417. package/src/community/api/test/getCommunity.test.ts +69 -0
  418. package/src/community/api/test/getRecommendedCommunities.test.ts +102 -0
  419. package/src/community/api/test/getTopTrendingCommunities.test.ts +102 -0
  420. package/src/community/api/test/joinCommunity.test.ts +70 -0
  421. package/src/community/api/test/leaveCommunity.test.ts +78 -0
  422. package/src/community/api/test/queryCommunity.test.ts +108 -0
  423. package/src/community/api/test/queryCommunityMembers.test.ts +122 -0
  424. package/src/community/api/test/removeCommunityMemberRole.test.ts +67 -0
  425. package/src/community/api/test/removeCommunityMembers.test.ts +75 -0
  426. package/src/community/api/test/updateCommunity.test.ts +65 -0
  427. package/src/community/events/test/onCommunityCreated.test.ts +46 -0
  428. package/src/community/events/test/onCommunityDeleted.test.ts +35 -0
  429. package/src/community/events/test/onCommunityJoined.test.ts +50 -0
  430. package/src/community/events/test/onCommunityLeft.test.ts +50 -0
  431. package/src/community/events/test/onCommunityUpdated.test.ts +49 -0
  432. package/src/community/events/test/onCommunityUserAdded.test.ts +50 -0
  433. package/src/community/events/test/onCommunityUserBanned.test.ts +50 -0
  434. package/src/community/events/test/onCommunityUserRemoved.test.ts +50 -0
  435. package/src/community/events/test/onCommunityUserUnbaned.test.ts +50 -0
  436. package/src/community/events/test/utils.test.ts +158 -0
  437. package/src/community/events/utils.ts +18 -10
  438. package/src/core/events.ts +9 -20
  439. package/src/core/model/idResolvers.ts +1 -0
  440. package/src/core/model/identifyModel.ts +1 -0
  441. package/src/core/model/index.ts +15 -0
  442. package/src/core/query/filtering.ts +2 -9
  443. package/src/core/query/query.ts +2 -34
  444. package/src/core/subscription.ts +47 -9
  445. package/src/core/tests/query/query/runQuery.test.ts +15 -38
  446. package/src/core/tests/subscription.test.ts +15 -0
  447. package/src/feed/api/queryGlobalFeed.ts +1 -1
  448. package/src/feed/api/test/queryGlobalFeed.test.ts +138 -0
  449. package/src/follow/events/utils.ts +1 -1
  450. package/src/follow/observers/liveFollowers.ts +8 -8
  451. package/src/follow/observers/liveFollowings.ts +8 -8
  452. package/src/group/utils/index.ts +1 -0
  453. package/src/group/utils/test/withUsers.test.ts +103 -0
  454. package/src/group/utils/withUser.ts +92 -0
  455. package/src/index.ts +4 -0
  456. package/src/message/api/createMessage.ts +60 -29
  457. package/src/message/api/deleteMessage.ts +6 -6
  458. package/src/message/api/getMessage.ts +5 -4
  459. package/src/message/api/getMessages.ts +7 -5
  460. package/src/message/api/queryMessages.ts +13 -25
  461. package/src/message/api/tests/createMessage.test.ts +129 -37
  462. package/src/message/api/tests/deleteMessage.test.ts +18 -12
  463. package/src/message/api/tests/getMessage.test.ts +6 -4
  464. package/src/message/api/tests/getMessages.test.ts +7 -8
  465. package/src/message/api/tests/queryMessages.test.ts +20 -23
  466. package/src/message/api/tests/updateMessage.test.ts +13 -12
  467. package/src/message/api/updateMessage.ts +12 -9
  468. package/src/message/events/index.ts +7 -1
  469. package/src/message/events/onMessageCreated.ts +50 -3
  470. package/src/message/events/onMessageDeleted.ts +14 -2
  471. package/src/message/events/onMessageFetched.ts +1 -1
  472. package/src/message/events/onMessageFlagCleared.ts +34 -0
  473. package/src/message/events/onMessageFlagged.ts +33 -0
  474. package/src/message/events/onMessageReactionAdded.ts +35 -0
  475. package/src/message/events/onMessageReactionRemoved.ts +40 -0
  476. package/src/message/events/onMessageUnflagged.ts +32 -0
  477. package/src/message/events/onMessageUpdated.ts +14 -10
  478. package/src/message/observers/liveMessage.ts +42 -23
  479. package/src/message/observers/liveMessages.ts +30 -16
  480. package/src/message/observers/observeMessage.ts +1 -0
  481. package/src/message/observers/observeMessages.ts +6 -5
  482. package/src/message/tests/events.test.ts +53 -0
  483. package/src/message/tests/observers/liveMessage.test.ts +46 -49
  484. package/src/message/tests/observers/liveMessages.test.ts +45 -37
  485. package/src/message/utils/index.ts +129 -0
  486. package/src/post/api/queryPosts.ts +9 -0
  487. package/src/post/api/tests/queryPosts.test.ts +149 -0
  488. package/src/post/events/tests/onPostApproved.test.ts +33 -0
  489. package/src/post/events/tests/onPostCreated.test.ts +33 -0
  490. package/src/post/events/tests/onPostDeclined.test.ts +33 -0
  491. package/src/post/events/tests/onPostDeleted.test.ts +33 -0
  492. package/src/post/events/tests/onPostFlagged.test.ts +33 -0
  493. package/src/post/events/tests/onPostReactionAdded.test.ts +40 -0
  494. package/src/post/events/tests/onPostReactionRemoved.test.ts +40 -0
  495. package/src/post/events/tests/onPostUnflagged.test.ts +33 -0
  496. package/src/post/events/tests/onPostUpdated.test.ts +33 -0
  497. package/src/post/events/utils.ts +1 -1
  498. package/src/post/observers/livePosts.ts +32 -12
  499. package/src/post/observers/tests/livePosts.test.ts +302 -0
  500. package/src/reaction/api/addReaction.ts +1 -0
  501. package/src/reaction/api/removeReaction.ts +6 -1
  502. package/src/reaction/events/onReactionAdded.ts +4 -7
  503. package/src/reaction/events/onReactionRemoved.ts +4 -7
  504. package/src/reaction/events/onReactorAdded.ts +4 -2
  505. package/src/reaction/events/onReactorRemoved.ts +4 -7
  506. package/src/reaction/observers/liveReactions.ts +6 -6
  507. package/src/reaction/utils/dispatchReactable.ts +1 -1
  508. package/src/report/api/createReport.ts +28 -18
  509. package/src/report/api/deleteReport.ts +28 -18
  510. package/src/report/api/isReportedByMe.ts +9 -2
  511. package/src/subChannel/api/createSubChannel.ts +41 -0
  512. package/src/subChannel/api/deleteSubChannel.ts +53 -0
  513. package/src/subChannel/api/getSubChannel.ts +85 -0
  514. package/src/subChannel/api/getSubChannels.ts +77 -0
  515. package/src/subChannel/api/index.ts +8 -0
  516. package/src/subChannel/api/querySubChannels.ts +115 -0
  517. package/src/subChannel/api/updateSubChannel.ts +43 -0
  518. package/src/subChannel/events/index.ts +3 -0
  519. package/src/subChannel/events/onSubChannelCreated.ts +32 -0
  520. package/src/subChannel/events/onSubChannelDeleted.ts +44 -0
  521. package/src/subChannel/events/onSubChannelFetched.ts +12 -0
  522. package/src/subChannel/events/onSubChannelUpdated.ts +32 -0
  523. package/src/subChannel/observers/index.ts +2 -0
  524. package/src/subChannel/observers/liveSubChannel.ts +84 -0
  525. package/src/subChannel/observers/liveSubChannels.ts +137 -0
  526. package/src/subChannel/observers/tests/liveSubChannel.test.ts +212 -0
  527. package/src/subChannel/observers/tests/liveSubChannels.test.ts +206 -0
  528. package/src/subChannel/utils/index.ts +50 -0
  529. package/src/user/events/index.ts +0 -1
  530. package/src/user/events/utils.ts +1 -1
  531. package/src/user/observers/liveUser.ts +29 -23
  532. package/src/user/tests/observers/liveUser.test.ts +5 -9
  533. package/src/utils/index.ts +52 -0
  534. package/src/utils/tests/dummy/channel.ts +123 -117
  535. package/src/utils/tests/dummy/community.ts +67 -3
  536. package/src/utils/tests/dummy/index.ts +3 -1
  537. package/src/utils/tests/dummy/member.ts +18 -0
  538. package/src/utils/tests/dummy/message.ts +37 -16
  539. package/src/utils/tests/dummy/post.ts +34 -0
  540. package/src/utils/tests/dummy/subChannel.ts +29 -0
  541. package/src/utils/tests/dummy/user.ts +2 -0
  542. package/src/utils/tests/utils.ts +2 -0
  543. package/dist/channel/utils/prepareChannelPayload.d.ts +0 -3
  544. package/dist/channel/utils/prepareChannelPayload.d.ts.map +0 -1
  545. package/src/channel/utils/prepareChannelPayload.ts +0 -31
package/dist/index.esm.js CHANGED
@@ -91,6 +91,78 @@ const isProduction = ((_a$1 = safeProcess.env) === null || _a$1 === void 0 ? voi
91
91
  var _a, _b;
92
92
  const VERSION$1 = (_b = (_a = safeProcess.env) === null || _a === void 0 ? void 0 : _a.VERSION) !== null && _b !== void 0 ? _b : '__dev__';
93
93
 
94
+ // cache constants
95
+ const CACHE_KEY_GET = 'get';
96
+ const CACHE_KEY_TOMBSTONE = 'dead';
97
+ const CACHE_LIFESPAN = 1 * 60 * 1000; // 1 minute
98
+ const CACHE_LIFESPAN_TOMBSTONE = 3 * 60 * 1000; // 3 minutes
99
+ /**
100
+ * Shallow-clones an object and sort its keys
101
+ *
102
+ * @param source a plain object to clone
103
+ * @returns a clone of source, with keys sorted with default javascript sorting
104
+ *
105
+ * @category Cache
106
+ * @hidden
107
+ */
108
+ const normalize = (source) => Object.keys(source)
109
+ .sort()
110
+ .reduce((acc, key) => (Object.assign(Object.assign({}, acc), { [key]: source[key] })), {});
111
+ /**
112
+ * Encodes a given {@link Amity.CacheKey} to a plain string
113
+ *
114
+ * @param key the key to encode
115
+ * @returns an encoded string
116
+ *
117
+ * @category Cache
118
+ * @hidden
119
+ */
120
+ const encodeKey = (key) => JSON.stringify(key, (_, val) => (typeof val === 'object' ? normalize(val) : val));
121
+ /**
122
+ * Decodes a string back into a {@link Amity.CacheKey}
123
+
124
+ *
125
+ * @param key the string key to decode
126
+ * @returns a plain Amity.CacheKey object.
127
+ *
128
+ * @category Cache
129
+ * @hidden
130
+ */
131
+ const decodeKey = (key) => JSON.parse(key);
132
+ /**
133
+ * Performs a recursive partial deep equal check on two objects.
134
+ *
135
+ * @param predicate the reference object containing the partial information
136
+ * @param candidate the object to check against
137
+ * @returns true if the candidate contains all the values of the predicate
138
+ *
139
+ * @category Cache
140
+ */
141
+ const partialMatch = (predicate, candidate) => {
142
+ if (predicate === candidate)
143
+ return true;
144
+ // if one or the other is nullish, there can't be equality
145
+ if (!predicate || !candidate)
146
+ return false;
147
+ // we only perform recursive check on objects
148
+ if (typeof predicate !== 'object') {
149
+ return false;
150
+ }
151
+ // recursively call for partial match based on the predicate
152
+ return Object.keys(predicate).every(key => partialMatch(predicate[key], candidate[key]));
153
+ };
154
+ /**
155
+ * checks if passed error code is included in
156
+ * Tombstone errors list
157
+ *
158
+ * @param errorCode as {@link Amity.ServerError}
159
+ * @returns success boolean if the given errorCode
160
+ * is included in Tombstone errors list
161
+ *
162
+ * @category Cache
163
+ */
164
+ const checkIfShouldGoesToTombstone = (errorCode) => [400400 /* Amity.ServerError.ITEM_NOT_FOUND */, 400300 /* Amity.ServerError.FORBIDDEN */].includes(errorCode);
165
+
94
166
  /**
95
167
  * Type guard to find if the a given decoded backend token uses "skip/limit" pagination style
96
168
  *
@@ -240,12 +312,180 @@ const toPageRaw = (token) => {
240
312
  return undefined;
241
313
  };
242
314
 
315
+ /* eslint-disable no-use-before-define */
316
+ /**
317
+ * Type guard to check and cast that a given async function is has the ".locally" property
318
+ *
319
+ * @param func any SDK APi function
320
+ * @returns success boolean if the function has a 'locally' twin
321
+ *
322
+ * @hidden
323
+ */
324
+ const isFetcher = (func) => 'locally' in func;
325
+ /**
326
+ * Type guard to check and cast that a given async function is has the ".optimistically" property
327
+ *
328
+ * @param func any SDK APi function
329
+ * @returns success boolean if the function has an 'optimistically' twin
330
+ *
331
+ * @hidden
332
+ */
333
+ const isMutator = (func) => 'optimistically' in func;
334
+ /**
335
+ * Type guard to check and cast that a given async function is has
336
+ * the ".locally" or ".optimistically" property
337
+ *
338
+ * @param func any SDK APi function
339
+ * @returns success boolean if the function has an offline twin
340
+ *
341
+ * @hidden
342
+ */
343
+ const isOffline = (func) => isFetcher(func) || isMutator(func);
344
+ /**
345
+ * Type guard to check and cast that a given object has the "cachedAt" property
346
+ *
347
+ * @param model any object to check on
348
+ * @returns success boolean if the object has property "cachedAt"
349
+ *
350
+ * @hidden
351
+ */
352
+ const isCachable = (model) => model === null || model === void 0 ? void 0 : model.hasOwnProperty('cachedAt');
353
+ /**
354
+ * Checks if a model is considered local (cachedAt === -1)
355
+ *
356
+ * @param model any cachable object to check
357
+ * @returns success boolean if the object is marked as local
358
+ *
359
+ * @hidden
360
+ */
361
+ const isLocal = (model) => {
362
+ return isCachable(model) && (model === null || model === void 0 ? void 0 : model.cachedAt) === -1;
363
+ };
364
+ /**
365
+ * Checks if a model is considered fresh
366
+ *
367
+ * @param model any cachable object to check
368
+ * @param lifeSpan the supposedly duration for which the object is considered synced
369
+ * @returns success boolean if the object is below the given lifespan
370
+ *
371
+ * @hidden
372
+ */
373
+ const isFresh = (model, lifeSpan = CACHE_LIFESPAN) => {
374
+ var _a;
375
+ return Date.now() - ((_a = model === null || model === void 0 ? void 0 : model.cachedAt) !== null && _a !== void 0 ? _a : 0) <= lifeSpan;
376
+ };
377
+ /**
378
+ * ```js
379
+ * import { createQuery, getUser } from '@amityco/ts-sdk'
380
+ * const query = createQuery(getUser, 'foobar')
381
+ * ```
382
+ *
383
+ * Creates a wrapper for the API call you wish to call.
384
+ * This wrapper is necessary to create for optimistically calls
385
+ *
386
+ *
387
+ * @param func A compatible API function from the ts sdk
388
+ * @param args The arguments to pass to the function passed as `fn`
389
+ * @returns A wrapper containing both the function and its future arguments
390
+ *
391
+ * @category Query
392
+ */
393
+ const createQuery = (func, ...args) => ({ func, args });
394
+ /**
395
+ * ```js
396
+ * import { queryOptions } from '@amityco/ts-sdk'
397
+ * const options = queryOptions('no_fetch', lifeSpan)
398
+ * ```
399
+ *
400
+ * Creates a query options object based on the query policy passed
401
+ *
402
+ * @param policy The policy to apply to a query
403
+ * @returns A properly set query options object
404
+ *
405
+ * @category Query
406
+ */
407
+ const queryOptions = (policy, lifeSpan = CACHE_LIFESPAN) => {
408
+ if (policy === 'cache_only')
409
+ return { lifeSpan: Infinity };
410
+ return { lifeSpan: lifeSpan < CACHE_LIFESPAN ? CACHE_LIFESPAN : lifeSpan };
411
+ };
412
+ /**
413
+ * ```js
414
+ * import { createQuery, getUser, runQuery } from '@amityco/ts-sdk'
415
+ * const query = createQuery(getUser, client, 'foobar')
416
+ * runQuery(query, user => console.log(user))
417
+ * ```
418
+ *
419
+ * Calls an API function wrapped around a Amity.Query, and executes the callback whenever
420
+ * a value is available. The value can be picked either from the local cache and/or
421
+ * from the server afterwards depending on the query options passed
422
+ *
423
+ * @param query A query object wrapping the call to be made
424
+ * @param callback A function to execute when a value is available
425
+ * @param options the query options
426
+ *
427
+ * @category Query
428
+ */
429
+ const runQuery = ({ func, args }, callback, options = queryOptions('cache_then_server')) => {
430
+ let local;
431
+ const { lifeSpan } = queryOptions('cache_then_server', options.lifeSpan);
432
+ // offline first
433
+ if (isOffline(func)) {
434
+ try {
435
+ local = isMutator(func) ? func.optimistically(...args) : func.locally(...args);
436
+ }
437
+ catch (error) {
438
+ callback === null || callback === void 0 ? void 0 : callback(createSnapshot(undefined, {
439
+ origin: 'local',
440
+ loading: false,
441
+ error,
442
+ }));
443
+ }
444
+ const shouldAbort = isCachable(local) && isFresh(local, lifeSpan);
445
+ callback === null || callback === void 0 ? void 0 : callback(createSnapshot(local, {
446
+ origin: 'local',
447
+ loading: !(isFetcher(func) && shouldAbort),
448
+ }));
449
+ if (shouldAbort)
450
+ return;
451
+ }
452
+ else {
453
+ callback === null || callback === void 0 ? void 0 : callback(createSnapshot(undefined, {
454
+ origin: 'local',
455
+ loading: true,
456
+ }));
457
+ }
458
+ func(...args)
459
+ .then(fresh => {
460
+ // @ts-ignore i know.
461
+ // isLocal(local) && syncInCache(local, fresh)
462
+ callback === null || callback === void 0 ? void 0 : callback(createSnapshot(fresh, {
463
+ origin: 'server',
464
+ loading: false,
465
+ }));
466
+ })
467
+ .catch(error => {
468
+ callback === null || callback === void 0 ? void 0 : callback(createSnapshot(undefined, {
469
+ origin: 'server',
470
+ loading: false,
471
+ error,
472
+ }));
473
+ });
474
+ };
475
+ // eslint-disable-next-line no-redeclare
476
+ function createSnapshot(data, options) {
477
+ if (isPaged(data) || isCachable(data))
478
+ return Object.assign(Object.assign({}, options), data);
479
+ return Object.assign(Object.assign({}, options), { data });
480
+ }
481
+
243
482
  /** @hidden */
244
483
  const idResolvers = {
245
484
  user: ({ userId }) => userId,
246
485
  file: ({ fileId }) => fileId,
247
486
  role: ({ roleId }) => roleId,
248
487
  channel: ({ channelId }) => channelId,
488
+ subChannel: ({ subChannelId }) => subChannelId,
249
489
  channelUsers: ({ channelId, userId }) => `${channelId}#${userId}`,
250
490
  message: ({ messageId }) => messageId,
251
491
  community: ({ communityId }) => communityId,
@@ -282,6 +522,7 @@ const CRITERIAS = {
282
522
  user: ['userId', 'avatarFileId'],
283
523
  role: ['roleId'],
284
524
  channel: ['channelId', 'rateLimit'],
525
+ subChannel: ['subChannelId'],
285
526
  channelUsers: ['channelId', 'userId', 'membership'],
286
527
  message: ['messageId'],
287
528
  community: ['communityId', 'postSetting'],
@@ -340,6 +581,7 @@ const PAYLOAD2MODEL = {
340
581
  files: 'file',
341
582
  roles: 'role',
342
583
  channels: 'channel',
584
+ messageFeeds: 'subChannel',
343
585
  channelUsers: 'channelUsers',
344
586
  messages: 'message',
345
587
  communities: 'community',
@@ -353,277 +595,17 @@ const PAYLOAD2MODEL = {
353
595
  videoStreamings: 'stream',
354
596
  follows: 'follow',
355
597
  followCounts: 'followCount',
356
- };
598
+ };
599
+ /** hidden */
600
+ const hasUpdates = (prevData, nextData) => {
601
+ return new Date(prevData.updatedAt) < new Date(nextData.updatedAt);
602
+ };
603
+ /** hidden */
604
+ function getFutureDate(date = new Date().toISOString()) {
605
+ return new Date(new Date(date).getTime() + 1).toISOString();
606
+ }
357
607
 
358
- // cache constants
359
- const CACHE_KEY_GET = 'get';
360
- const CACHE_KEY_TOMBSTONE = 'dead';
361
- const CACHE_LIFESPAN = 1 * 60 * 1000; // 1 minute
362
- const CACHE_LIFESPAN_TOMBSTONE = 3 * 60 * 1000; // 3 minutes
363
- /**
364
- * Shallow-clones an object and sort its keys
365
- *
366
- * @param source a plain object to clone
367
- * @returns a clone of source, with keys sorted with default javascript sorting
368
- *
369
- * @category Cache
370
- * @hidden
371
- */
372
- const normalize = (source) => Object.keys(source)
373
- .sort()
374
- .reduce((acc, key) => (Object.assign(Object.assign({}, acc), { [key]: source[key] })), {});
375
- /**
376
- * Encodes a given {@link Amity.CacheKey} to a plain string
377
- *
378
- * @param key the key to encode
379
- * @returns an encoded string
380
- *
381
- * @category Cache
382
- * @hidden
383
- */
384
- const encodeKey = (key) => JSON.stringify(key, (_, val) => (typeof val === 'object' ? normalize(val) : val));
385
- /**
386
- * Decodes a string back into a {@link Amity.CacheKey}
387
-
388
- *
389
- * @param key the string key to decode
390
- * @returns a plain Amity.CacheKey object.
391
- *
392
- * @category Cache
393
- * @hidden
394
- */
395
- const decodeKey = (key) => JSON.parse(key);
396
- /**
397
- * Performs a recursive partial deep equal check on two objects.
398
- *
399
- * @param predicate the reference object containing the partial information
400
- * @param candidate the object to check against
401
- * @returns true if the candidate contains all the values of the predicate
402
- *
403
- * @category Cache
404
- */
405
- const partialMatch = (predicate, candidate) => {
406
- if (predicate === candidate)
407
- return true;
408
- // if one or the other is nullish, there can't be equality
409
- if (!predicate || !candidate)
410
- return false;
411
- // we only perform recursive check on objects
412
- if (typeof predicate !== 'object') {
413
- return false;
414
- }
415
- // recursively call for partial match based on the predicate
416
- return Object.keys(predicate).every(key => partialMatch(predicate[key], candidate[key]));
417
- };
418
- /**
419
- * checks if passed error code is included in
420
- * Tombstone errors list
421
- *
422
- * @param errorCode as {@link Amity.ServerError}
423
- * @returns success boolean if the given errorCode
424
- * is included in Tombstone errors list
425
- *
426
- * @category Cache
427
- */
428
- const checkIfShouldGoesToTombstone = (errorCode) => [400400 /* Amity.ServerError.ITEM_NOT_FOUND */, 400300 /* Amity.ServerError.FORBIDDEN */].includes(errorCode);
429
-
430
- /* eslint-disable no-use-before-define */
431
- /**
432
- * Type guard to check and cast that a given async function is has the ".locally" property
433
- *
434
- * @param func any SDK APi function
435
- * @returns success boolean if the function has a 'locally' twin
436
- *
437
- * @hidden
438
- */
439
- const isFetcher = (func) => 'locally' in func;
440
- /**
441
- * Type guard to check and cast that a given async function is has the ".optimistically" property
442
- *
443
- * @param func any SDK APi function
444
- * @returns success boolean if the function has an 'optimistically' twin
445
- *
446
- * @hidden
447
- */
448
- const isMutator = (func) => 'optimistically' in func;
449
- /**
450
- * Type guard to check and cast that a given async function is has
451
- * the ".locally" or ".optimistically" property
452
- *
453
- * @param func any SDK APi function
454
- * @returns success boolean if the function has an offline twin
455
- *
456
- * @hidden
457
- */
458
- const isOffline = (func) => isFetcher(func) || isMutator(func);
459
- /**
460
- * Type guard to check and cast that a given object has the "cachedAt" property
461
- *
462
- * @param model any object to check on
463
- * @returns success boolean if the object has property "cachedAt"
464
- *
465
- * @hidden
466
- */
467
- const isCachable = (model) => model === null || model === void 0 ? void 0 : model.hasOwnProperty('cachedAt');
468
- /**
469
- * Checks if a model is considered local (cachedAt === -1)
470
- *
471
- * @param model any cachable object to check
472
- * @returns success boolean if the object is marked as local
473
- *
474
- * @hidden
475
- */
476
- const isLocal = (model) => {
477
- return isCachable(model) && (model === null || model === void 0 ? void 0 : model.cachedAt) === -1;
478
- };
479
- /**
480
- * Checks if a model is considered fresh
481
- *
482
- * @param model any cachable object to check
483
- * @param lifeSpan the supposedly duration for which the object is considered synced
484
- * @returns success boolean if the object is below the given lifespan
485
- *
486
- * @hidden
487
- */
488
- const isFresh = (model, lifeSpan = CACHE_LIFESPAN) => {
489
- var _a;
490
- return Date.now() - ((_a = model === null || model === void 0 ? void 0 : model.cachedAt) !== null && _a !== void 0 ? _a : 0) <= lifeSpan;
491
- };
492
- /**
493
- * ```js
494
- * import { createQuery, getUser } from '@amityco/ts-sdk'
495
- * const query = createQuery(getUser, 'foobar')
496
- * ```
497
- *
498
- * Creates a wrapper for the API call you wish to call.
499
- * This wrapper is necessary to create for optimistically calls
500
- *
501
- *
502
- * @param func A compatible API function from the ts sdk
503
- * @param args The arguments to pass to the function passed as `fn`
504
- * @returns A wrapper containing both the function and its future arguments
505
- *
506
- * @category Query
507
- */
508
- const createQuery = (func, ...args) => ({ func, args });
509
- /**
510
- * ```js
511
- * import { queryOptions } from '@amityco/ts-sdk'
512
- * const options = queryOptions('no_fetch', lifeSpan)
513
- * ```
514
- *
515
- * Creates a query options object based on the query policy passed
516
- *
517
- * @param policy The policy to apply to a query
518
- * @returns A properly set query options object
519
- *
520
- * @category Query
521
- */
522
- const queryOptions = (policy, lifeSpan = CACHE_LIFESPAN) => {
523
- if (policy === 'cache_only')
524
- return { lifeSpan: Infinity };
525
- return { lifeSpan: lifeSpan < CACHE_LIFESPAN ? CACHE_LIFESPAN : lifeSpan };
526
- };
527
- /**
528
- * ```js
529
- * import { createQuery, getUser, runQuery } from '@amityco/ts-sdk'
530
- * const query = createQuery(getUser, client, 'foobar')
531
- * runQuery(query, user => console.log(user))
532
- * ```
533
- *
534
- * Calls an API function wrapped around a Amity.Query, and executes the callback whenever
535
- * a value is available. The value can be picked either from the local cache and/or
536
- * from the server afterwards depending on the query options passed
537
- *
538
- * @param query A query object wrapping the call to be made
539
- * @param callback A function to execute when a value is available
540
- * @param options the query options
541
- *
542
- * @category Query
543
- */
544
- const runQuery = ({ func, args }, callback, options = queryOptions('cache_then_server')) => {
545
- let local;
546
- const { lifeSpan } = queryOptions('cache_then_server', options.lifeSpan);
547
- // offline first
548
- if (isOffline(func)) {
549
- try {
550
- local = isMutator(func) ? func.optimistically(...args) : func.locally(...args);
551
- }
552
- catch (error) {
553
- callback === null || callback === void 0 ? void 0 : callback(createSnapshot(undefined, {
554
- origin: 'local',
555
- loading: false,
556
- error,
557
- }));
558
- }
559
- const shouldAbort = isCachable(local) && isFresh(local, lifeSpan);
560
- callback === null || callback === void 0 ? void 0 : callback(createSnapshot(local, {
561
- origin: 'local',
562
- loading: !(isFetcher(func) && shouldAbort),
563
- }));
564
- if (shouldAbort)
565
- return;
566
- }
567
- else {
568
- callback === null || callback === void 0 ? void 0 : callback(createSnapshot(undefined, {
569
- origin: 'local',
570
- loading: true,
571
- }));
572
- }
573
- let optimisticArgs = args;
574
- /* get args for optimistic method calls
575
- *
576
- * On optimistic updates, the modal key for the update needs to be passed to
577
- * the server so as to avoid duplicate modal creation
578
- *
579
- * ex: on creating a new message pass the modalKey is messageId, pass this
580
- * id onto the server so that a duplicate with seperate messageId is not
581
- * created.
582
- */
583
- if (isMutator(func)) {
584
- // @ts-ignore
585
- const modelKey = local && local.data && identifyModelKey(local.data);
586
- if (modelKey) {
587
- /*
588
- * modal key is only required for create as update and delete queries pass
589
- * the modal key in the param itself
590
- * For update & delete the first argument is always an id which is of type
591
- * string, whereas for create the first and only argument is the param object
592
- *
593
- * When creating an AmityObject optimistically we need to pass the modal key
594
- * on to the server. ex: for create message modal key will be 'messageId`
595
- */
596
- if (typeof args[0] !== 'string') {
597
- // @ts-ignore
598
- optimisticArgs = [Object.assign(Object.assign({}, args[0]), { [modelKey]: local.data[modelKey] })];
599
- }
600
- }
601
- }
602
- func(...optimisticArgs)
603
- .then(fresh => {
604
- // @ts-ignore i know.
605
- // isLocal(local) && syncInCache(local, fresh)
606
- callback === null || callback === void 0 ? void 0 : callback(createSnapshot(fresh, {
607
- origin: 'server',
608
- loading: false,
609
- }));
610
- })
611
- .catch(error => {
612
- callback === null || callback === void 0 ? void 0 : callback(createSnapshot(undefined, {
613
- origin: 'server',
614
- loading: false,
615
- error,
616
- }));
617
- });
618
- };
619
- // eslint-disable-next-line no-redeclare
620
- function createSnapshot(data, options) {
621
- if (isPaged(data) || isCachable(data))
622
- return Object.assign(Object.assign({}, options), data);
623
- return Object.assign(Object.assign({}, options), { data });
624
- }
625
-
626
- /* eslint-disable max-classes-per-file */
608
+ /* eslint-disable max-classes-per-file */
627
609
  /**
628
610
  * Generic ASC error
629
611
  * @category Errors
@@ -1079,16 +1061,10 @@ const filterByChannelMembership = (collection, membership, userId) => {
1079
1061
  'get',
1080
1062
  channelUserCacheKey,
1081
1063
  ])) === null || _a === void 0 ? void 0 : _a.data;
1082
- // if channel user is defined for user, user is a member
1083
- if (membership === 'member' && channelUser) {
1084
- return true;
1085
- }
1086
- // if channel user by user id not found, user is not a member of that
1087
- // channel
1088
- if (membership === 'notMember' && !channelUser) {
1064
+ if (membership === 'member' && channelUser && channelUser.membership !== 'none') {
1089
1065
  return true;
1090
1066
  }
1091
- return false;
1067
+ return membership === 'notMember' && (!channelUser || channelUser.membership === 'none');
1092
1068
  });
1093
1069
  };
1094
1070
 
@@ -1149,19 +1125,6 @@ const WS_EVENTS = [
1149
1125
  'connect_error',
1150
1126
  'reconnect_error',
1151
1127
  'reconnect_failed',
1152
- 'v3.channel.didCreate',
1153
- 'v3.channel.didUpdate',
1154
- 'v3.channel.didDelete',
1155
- 'v3.channel.didJoin',
1156
- 'v3.channel.didLeave',
1157
- 'v3.channel.didAddUsers',
1158
- 'v3.channel.didRemoveUsers',
1159
- 'v3.channel.didBan',
1160
- 'v3.channel.didUnban',
1161
- 'v3.message.didFetch',
1162
- 'v3.message.didCreate',
1163
- 'v3.message.didUpdate',
1164
- 'v3.message.didDelete',
1165
1128
  ];
1166
1129
  const MQTT_EVENTS = [
1167
1130
  'connect',
@@ -1188,16 +1151,23 @@ const createEventEmitter = () => {
1188
1151
  */
1189
1152
  const proxyWebsocketEvents = (ws, emitter) => {
1190
1153
  WS_EVENTS.forEach(event => {
1191
- ws.on(event, (param) => emitter.emit(event, param));
1154
+ ws.on(event, (param) => {
1155
+ console.log('ws', event, param);
1156
+ emitter.emit(event, param);
1157
+ });
1192
1158
  });
1193
1159
  };
1194
1160
  const proxyMqttEvents = (mqttClient, emitter) => {
1195
1161
  MQTT_EVENTS.forEach(event => {
1196
- mqttClient.on(event, (...params) => emitter.emit(event, params.length === 1 ? params[0] : params));
1162
+ mqttClient.on(event, (...params) => {
1163
+ console.log('mqtt', event, params);
1164
+ emitter.emit(event, params.length === 1 ? params[0] : params);
1165
+ });
1197
1166
  });
1198
1167
  // @ts-ignore
1199
1168
  mqttClient.on('message', (topic, payload) => {
1200
1169
  const message = JSON.parse(payload.toString());
1170
+ console.log('mqtt message', message);
1201
1171
  emitter.emit(message.eventType, message.data);
1202
1172
  });
1203
1173
  };
@@ -1277,6 +1247,7 @@ const getCommunityUserTopic = (path, level) => {
1277
1247
  return path;
1278
1248
  }
1279
1249
  };
1250
+ const getNetworkId = (user) => user.path.split('/user/')[0];
1280
1251
  const getCommunityTopic = ({ path }, level = SubscriptionLevels.COMMUNITY) => getCommunityUserTopic(path, level);
1281
1252
  const getUserTopic = ({ path }, level = SubscriptionLevels.USER) => getCommunityUserTopic(level === SubscriptionLevels.USER ? path : path.replace(/^(\w*)/, '$1/social'), level);
1282
1253
  const getPostTopic = ({ path }, level = SubscriptionLevels.POST) => {
@@ -1292,24 +1263,54 @@ const getCommentTopic = ({ path }) => {
1292
1263
  };
1293
1264
  const getMyFollowersTopic = () => {
1294
1265
  const user = getActiveUser();
1295
- const [networkId] = user.path.split('/user/');
1296
- return `${networkId}/membership/${user._id}/+/+`;
1266
+ return `${getNetworkId(user)}/membership/${user._id}/+/+`;
1297
1267
  };
1298
1268
  const getMyFollowingsTopic = () => {
1299
1269
  const user = getActiveUser();
1300
- const [networkId] = user.path.split('/user/');
1301
- return `${networkId}/membership/+/${user._id}/+`;
1270
+ return `${getNetworkId(user)}/membership/+/${user._id}/+`;
1302
1271
  };
1303
- /** @hidden */
1272
+ const getChannelTopic = (channel) => `${channel.path}/#`;
1273
+ const getSubChannelTopic = (subChannel) => `${subChannel.path}/#`;
1274
+ const getMessageTopic = (message) => message.path;
1275
+ /**
1276
+ * @hidden
1277
+ *
1278
+ * Create a topic to subscribe to network level events like 'user is deleted from the network'
1279
+ */
1304
1280
  const getNetworkTopic = () => {
1305
- const user = getActiveUser();
1306
- const [networkId] = user.path.split('/user/');
1307
- return networkId;
1281
+ return getNetworkId(getActiveUser());
1308
1282
  };
1309
- let mqttAccessToken;
1310
- let mqttUserId;
1311
- function subscribeTopic(topic, callback) {
1312
- const { mqtt, emitter, accessToken } = getActiveClient();
1283
+ /**
1284
+ * @hidden
1285
+ *
1286
+ * Create a topic to subscribe to channel events for 'conversation', 'community' channel
1287
+ */
1288
+ const getSmartFeedChannelTopic = () => {
1289
+ const user = getActiveUser();
1290
+ return `${getNetworkId(user)}/smartfeed/${user._id}/channels`;
1291
+ };
1292
+ /**
1293
+ * @hidden
1294
+ *
1295
+ * Create a topic to subscribe to sub channel events for 'conversation', 'community' channel
1296
+ */
1297
+ const getSmartFeedSubChannelTopic = () => {
1298
+ const user = getActiveUser();
1299
+ return `${getNetworkId(user)}/smartfeed/${user._id}/messagefeeds`;
1300
+ };
1301
+ /**
1302
+ * @hidden
1303
+ *
1304
+ * Create a topic to subscribe to message events for 'conversation', 'community' channel
1305
+ */
1306
+ const getSmartFeedMessageTopic = () => {
1307
+ const user = getActiveUser();
1308
+ return `${getNetworkId(user)}/smartfeed/${user._id}/messages`;
1309
+ };
1310
+ let mqttAccessToken;
1311
+ let mqttUserId;
1312
+ function subscribeTopic(topic, callback) {
1313
+ const { mqtt, emitter, accessToken } = getActiveClient();
1313
1314
  const user = getActiveUser();
1314
1315
  if (mqttAccessToken !== accessToken || mqttUserId !== user._id) {
1315
1316
  mqttAccessToken = accessToken;
@@ -20320,7 +20321,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
20320
20321
  getFeedSettings,
20321
20322
  };
20322
20323
  try {
20323
- getActiveClient();
20324
+ return getActiveClient();
20324
20325
  }
20325
20326
  catch (_c) {
20326
20327
  setActiveClient(client);
@@ -20571,9 +20572,8 @@ const connectClient = async (params, config) => {
20571
20572
  // @ts-ignore: in that particular case, typing can be
20572
20573
  // ignored since we enforce default values just before.
20573
20574
  const { accessToken, users } = await getToken(params);
20574
- // manually setup the token for http transport
20575
+ // manually setup the token for http, ws transport
20575
20576
  client.http.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
20576
- // manually setup the token for ws transport
20577
20577
  client.ws.io.opts.query = { token: accessToken };
20578
20578
  // FIXME: events are duplicated if connectClient is called few times without disconnectClient
20579
20579
  // wire websocket events to our event emitter
@@ -20589,6 +20589,9 @@ const connectClient = async (params, config) => {
20589
20589
  setActiveUser(users[0]);
20590
20590
  if ((config === null || config === void 0 ? void 0 : config.disableRTE) !== true) {
20591
20591
  subscribeTopic(getNetworkTopic());
20592
+ subscribeTopic(getSmartFeedChannelTopic());
20593
+ subscribeTopic(getSmartFeedSubChannelTopic());
20594
+ subscribeTopic(getSmartFeedMessageTopic());
20592
20595
  }
20593
20596
  const subscriptions = [
20594
20597
  onClientBanned(() => {
@@ -20941,23 +20944,6 @@ const updateUser = async (userId, patch) => {
20941
20944
  };
20942
20945
  };
20943
20946
 
20944
- /**
20945
- * ```js
20946
- * import { onUserFetched } from '@amityco/ts-sdk'
20947
- * const dispose = onUserFetched(user => {
20948
- * // ...
20949
- * })
20950
- * ```
20951
- *
20952
- * Fired when a {@link Amity.User} has been fetched
20953
- *
20954
- * @param callback The function to call when the event was fired
20955
- * @returns an {@link Amity.Unsubscriber} function to stop listening
20956
- *
20957
- * @category User Events
20958
- */
20959
- const onUserFetched = (callback) => createUserEventSubscriber('user.fetched', callback);
20960
-
20961
20947
  /**
20962
20948
  * ```js
20963
20949
  * import { onUserUpdated } from '@amityco/ts-sdk'
@@ -21035,52 +21021,72 @@ const UNSYNCED_OBJECT_CACHED_AT_VALUE = -5;
21035
21021
 
21036
21022
  /**
21037
21023
  * ```js
21038
- * import { liveUser } from '@amityco/ts-sdk'
21024
+ * import { onUserFetched } from '@amityco/ts-sdk'
21025
+ * const dispose = onUserFetched(user => {
21026
+ * // ...
21027
+ * })
21028
+ * ```
21029
+ *
21030
+ * Fired when a {@link Amity.User} has been fetched
21031
+ *
21032
+ * @param callback The function to call when the event was fired
21033
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
21034
+ *
21035
+ * @category User Events
21036
+ */
21037
+ const onUserFetched = (callback) => createUserEventSubscriber('user.fetched', callback);
21038
+
21039
+ /**
21040
+ * ```js
21041
+ * import { liveUser } from '@amityco/ts-sdk';
21039
21042
  *
21040
- * let users = []
21041
- * const unsub = liveUser(userId, response => merge(users, response.data))
21043
+ * let user;
21044
+ *
21045
+ * const unsubscribe = liveUser(userId, response => {
21046
+ * user = response.data;
21047
+ * });
21042
21048
  * ```
21043
21049
  *
21044
21050
  * Observe all mutation on a given {@link Amity.User}
21045
21051
  *
21046
21052
  * @param userId the ID of the user to observe
21047
21053
  * @param callback the function to call when new data are available
21048
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the users
21054
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the user
21049
21055
  *
21050
21056
  * @category Message Live Object
21051
21057
  */
21052
21058
  const liveUser = (userId, callback) => {
21053
21059
  const { log, cache } = getActiveClient();
21054
- let user;
21060
+ const timestamp = Date.now();
21061
+ log(`liveUser(tmpid: ${timestamp}) > listen`);
21055
21062
  if (!cache) {
21056
21063
  console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
21057
21064
  }
21058
- const timestamp = Date.now();
21059
- log(`liveUser(tmpid: ${timestamp}) > listen`);
21065
+ let user;
21060
21066
  const disposers = [];
21061
21067
  const dispatcher = (data) => {
21062
- var _a;
21063
- // we check updatedAt to see if the current snapshot is new so
21064
- // we won't send old data back, only fresh new data
21065
- if (user && ((_a = data.data) === null || _a === void 0 ? void 0 : _a.updatedAt) === (user === null || user === void 0 ? void 0 : user.updatedAt) && data.origin !== 'server')
21066
- return;
21067
- callback(data);
21068
21068
  user = data.data;
21069
+ callback(data);
21069
21070
  };
21070
- const realtimeRouter = (user, action) => {
21071
- dispatcher({ loading: false, data: user, origin: 'event' });
21071
+ const realtimeRouter = (eventUser) => {
21072
+ if (userId !== eventUser.userId) {
21073
+ return;
21074
+ }
21075
+ if (user && !hasUpdates(user, eventUser)) {
21076
+ return;
21077
+ }
21078
+ dispatcher({ loading: false, data: eventUser, origin: 'event' });
21072
21079
  };
21073
21080
  const onFetch = () => {
21074
21081
  const query = createQuery(getUser, userId, true);
21075
21082
  runQuery(query, ({ loading, data, error, origin }) => {
21076
21083
  dispatcher({ loading, data, origin, error });
21077
21084
  if (error) {
21078
- // Terminate observe functionality on error
21079
21085
  disposers.forEach(fn => fn());
21080
21086
  }
21081
21087
  });
21082
21088
  };
21083
- disposers.push(onUserFetched(user => realtimeRouter(user)), onUserUpdated(user => realtimeRouter(user)), onUserDeleted(user => realtimeRouter(user)), onUserFlagged(user => realtimeRouter(user)), onUserUnflagged(user => realtimeRouter(user)), onUserFlagCleared(user => realtimeRouter(user)));
21089
+ disposers.push(onUserFetched(realtimeRouter), onUserUpdated(realtimeRouter), onUserDeleted(realtimeRouter), onUserFlagged(realtimeRouter), onUserUnflagged(realtimeRouter), onUserFlagCleared(realtimeRouter));
21084
21090
  onFetch();
21085
21091
  return () => {
21086
21092
  log(`liveUser(tmpid: ${timestamp}) > dispose`);
@@ -21494,7 +21500,7 @@ getRole.locally = (roleId) => {
21494
21500
  const dispatchReactable = (referenceType, model) => {
21495
21501
  if (referenceType === 'message')
21496
21502
  // @ts-ignore: refactor later
21497
- fireEvent('v3.message.didUpdate', { messages: [model] });
21503
+ fireEvent('local.message.updated', { messages: [model] });
21498
21504
  else if (referenceType === 'post')
21499
21505
  // @ts-ignore: refactor later
21500
21506
  fireEvent('post.updated', { posts: [model] });
@@ -21503,6 +21509,100 @@ const dispatchReactable = (referenceType, model) => {
21503
21509
  fireEvent('comment.updated', { comments: [model] });
21504
21510
  };
21505
21511
 
21512
+ /** @hidden */
21513
+ /*
21514
+ * @param message payload from http request without myReactions
21515
+ * add myReactions to http response if the event was a reaction event
21516
+ */
21517
+ const prepareMessagePayloadForCache = (payload) => {
21518
+ const client = getActiveClient();
21519
+ const cached = pullFromCache(['message', 'get', payload.messageId]);
21520
+ // '[]' in cases where the new reaction is the first one
21521
+ const myReactions = (cached === null || cached === void 0 ? void 0 : cached.data.myReactions) || [];
21522
+ // add myReactions to the payload
21523
+ Object.assign(payload, { myReactions });
21524
+ // check if there are any updates to the reactions
21525
+ const latestReaction = payload === null || payload === void 0 ? void 0 : payload.latestReaction;
21526
+ const isLatestReactionMine = latestReaction && latestReaction.userId === client.userId;
21527
+ if (!isLatestReactionMine) {
21528
+ return;
21529
+ }
21530
+ // new reaction added
21531
+ if (latestReaction.eventName === 'add' && !myReactions.includes(latestReaction.reactionName)) {
21532
+ Object.assign(payload, {
21533
+ myReactions: [...myReactions, latestReaction.reactionName],
21534
+ });
21535
+ }
21536
+ // existing reaction removed
21537
+ if (latestReaction.eventName === 'remove' && myReactions.includes(latestReaction.reactionName)) {
21538
+ Object.assign(payload, {
21539
+ myReactions: myReactions.filter(x => x !== latestReaction.reactionName),
21540
+ });
21541
+ }
21542
+ };
21543
+
21544
+ function convertFromRaw$2(_a) {
21545
+ var { channelPublicId, childCount, creatorPublicId, mentionedUsers, messageFeedId, myReactions, reactionCount, reactions, referenceId, segment } = _a, rest = __rest(_a, ["channelPublicId", "childCount", "creatorPublicId", "mentionedUsers", "messageFeedId", "myReactions", "reactionCount", "reactions", "referenceId", "segment"]);
21546
+ let cache;
21547
+ if (referenceId) {
21548
+ try {
21549
+ cache = pullFromCache(['message', 'get', referenceId]);
21550
+ // eslint-disable-next-line no-empty
21551
+ }
21552
+ catch (_b) { }
21553
+ }
21554
+ if (!cache) {
21555
+ try {
21556
+ cache = pullFromCache(['message', 'get', rest.messageId]);
21557
+ // eslint-disable-next-line no-empty
21558
+ }
21559
+ catch (_c) { }
21560
+ }
21561
+ const out = Object.assign(Object.assign({}, rest), { channelId: channelPublicId, channelSegment: segment, childrenNumber: childCount, creatorId: creatorPublicId, reactions: reactions !== null && reactions !== void 0 ? reactions : {}, reactionsCount: reactionCount, subChannelId: messageFeedId, uniqueId: cache ? cache.data.uniqueId : rest.messageId });
21562
+ if (mentionedUsers) {
21563
+ out.mentionees = mentionedUsers.map(mention => {
21564
+ if (mention.type === 'channel') {
21565
+ return mention;
21566
+ }
21567
+ return { type: 'user', userIds: mention.userPublicIds };
21568
+ });
21569
+ }
21570
+ if (myReactions) {
21571
+ // http response
21572
+ out.myReactions = myReactions;
21573
+ }
21574
+ else {
21575
+ // mqtt event
21576
+ try {
21577
+ prepareMessagePayloadForCache(out);
21578
+ // eslint-disable-next-line no-empty
21579
+ }
21580
+ catch (_d) { }
21581
+ }
21582
+ return out;
21583
+ }
21584
+ const prepareMessagePayload = (payload) => {
21585
+ return Object.assign(Object.assign({}, payload), { messages: payload.messages.map(convertFromRaw$2) });
21586
+ };
21587
+ const convertResponseFromRaw = (response) => {
21588
+ return Object.assign(Object.assign({}, response), { data: Object.assign(Object.assign({}, response.data), { messages: response.data.messages.map(convertFromRaw$2) }) });
21589
+ };
21590
+ function convertParams(_a) {
21591
+ var { subChannelId, mentionees } = _a, rest = __rest(_a, ["subChannelId", "mentionees"]);
21592
+ return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees }, rest);
21593
+ }
21594
+ function convertQueryParams$1(_a) {
21595
+ var { page, sortBy, subChannelId, tags } = _a, rest = __rest(_a, ["page", "sortBy", "subChannelId", "tags"]);
21596
+ const out = Object.assign(Object.assign({}, rest), { messageFeedId: subChannelId, options: { token: toToken(page || { limit: 10 }, 'afterbeforeraw') } });
21597
+ if (sortBy !== undefined) {
21598
+ out.options.sortBy = sortBy;
21599
+ }
21600
+ if (tags) {
21601
+ out.includeTags = tags;
21602
+ }
21603
+ return out;
21604
+ }
21605
+
21506
21606
  /**
21507
21607
  * ```js
21508
21608
  * import { getMessage } from '@amityco/ts-sdk'
@@ -21527,7 +21627,9 @@ const getMessage = async (messageId, isLive = false) => {
21527
21627
  let data;
21528
21628
  try {
21529
21629
  // API-FIX: endpoint should not be /list, parameters should be querystring.
21530
- const response = await client.http.get(`/api/v3/messages/${encodeURIComponent(messageId)}`);
21630
+ const response = await client.http
21631
+ .get(`/api/v5/messages/${encodeURIComponent(messageId)}`)
21632
+ .then(convertResponseFromRaw);
21531
21633
  data = response.data;
21532
21634
  }
21533
21635
  catch (error) {
@@ -21540,7 +21642,7 @@ const getMessage = async (messageId, isLive = false) => {
21540
21642
  if (client.cache)
21541
21643
  ingestInCache(data, { cachedAt });
21542
21644
  const { messages } = data;
21543
- fireEvent('v3.message.didFetch', { messages });
21645
+ fireEvent('local.message.fetched', { messages });
21544
21646
  return {
21545
21647
  data: messages.find(message => message.messageId === messageId),
21546
21648
  cachedAt,
@@ -21590,15 +21692,16 @@ getMessage.locally = (messageId) => {
21590
21692
  const getMessages = async (messageIds) => {
21591
21693
  const client = getActiveClient();
21592
21694
  client.log('message/getMessages', messageIds);
21593
- // API-FIX: endpoint should not be /list, parameters should be querystring.
21594
- const { data } = await client.http.get(`/api/v3/messages/list`, {
21595
- params: { messageIds },
21596
- });
21695
+ const { data } = await client.http
21696
+ .get(`/api/v5/messages/list`, {
21697
+ params: { messageIds: messageIds.map(encodeURIComponent) },
21698
+ })
21699
+ .then(convertResponseFromRaw);
21597
21700
  const cachedAt = client.cache && Date.now();
21598
21701
  if (client.cache)
21599
21702
  ingestInCache(data, { cachedAt });
21600
21703
  const { messages } = data;
21601
- fireEvent('v3.message.didFetch', { messages });
21704
+ fireEvent('local.message.fetched', { messages });
21602
21705
  return {
21603
21706
  data: messages,
21604
21707
  cachedAt,
@@ -21653,31 +21756,25 @@ getMessages.locally = (messageIds) => {
21653
21756
  const queryMessages = async (query) => {
21654
21757
  const client = getActiveClient();
21655
21758
  client.log('message/queryMessages', query);
21656
- const { page = { limit: 10 } } = query, params = __rest(query, ["page"]);
21759
+ const params = convertQueryParams$1(query);
21657
21760
  // API-FIX: parameters should be querystring. (1)
21658
21761
  // API-FIX: backend should answer Amity.Response (2)
21659
21762
  // API-FIX: pagination should not be indexed on channelSegment (3)
21660
21763
  // const { data } = await client.http.get<Amity.Response<Amity.Paged<Amity.MessagePayload>>>(
21661
- const { data } = await client.http.get(`/api/v3/messages`, {
21662
- params: Object.assign(Object.assign({}, params), { options: {
21663
- token: toToken(page, 'afterbefore'),
21664
- } }),
21665
- });
21764
+ const response = await client.http
21765
+ .get(`/api/v5/messages`, { params })
21766
+ .then(convertResponseFromRaw);
21666
21767
  // API-FIX: backend should answer Amity.Response (2)
21667
21768
  // const { paging, messages } = unwrapPayload(data)
21668
- const { paging } = data, payload = __rest(data, ["paging"]);
21669
- const { messages } = payload;
21769
+ const _a = response.data, { paging } = _a, data = __rest(_a, ["paging"]);
21770
+ const { messages } = data;
21670
21771
  const cachedAt = client.cache && Date.now();
21671
21772
  if (client.cache) {
21672
- ingestInCache(payload, { cachedAt });
21673
- const cacheKey = [
21674
- 'message',
21675
- 'query',
21676
- Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
21677
- ];
21773
+ ingestInCache(data, { cachedAt });
21774
+ const cacheKey = ['message', 'query', params];
21678
21775
  pushToCache(cacheKey, { messages: messages.map(getResolver('message')), paging });
21679
21776
  }
21680
- fireEvent('v3.message.didFetch', { messages });
21777
+ fireEvent('local.message.fetched', { messages });
21681
21778
  const nextPage = toPage(paging.next);
21682
21779
  const prevPage = toPage(paging.previous);
21683
21780
  return { data: messages, cachedAt, prevPage, nextPage };
@@ -21701,8 +21798,8 @@ queryMessages.locally = (query) => {
21701
21798
  client.log('message/queryMessages.locally', query);
21702
21799
  if (!client.cache)
21703
21800
  return;
21704
- const { page = { limit: 10 } } = query, params = __rest(query, ["page"]);
21705
- const queryKey = ['message', 'query', Object.assign(Object.assign({}, params), { options: Object.assign({}, page) })];
21801
+ const params = convertQueryParams$1(query);
21802
+ const queryKey = ['message', 'query', params];
21706
21803
  const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
21707
21804
  if (!(data === null || data === void 0 ? void 0 : data.messages.length))
21708
21805
  return;
@@ -21719,13 +21816,20 @@ queryMessages.locally = (query) => {
21719
21816
 
21720
21817
  const uuid = () => nativeIdGenerator.v4().toString();
21721
21818
 
21819
+ // FIXME: temp solution
21820
+ let uniqueId;
21722
21821
  /**
21723
21822
  * ```js
21724
- * import { createMessage } from '@amityco/ts-sdk'
21725
- * const created = await createMessage({
21726
- * channelId: 'foobar',
21727
- * data: { text: 'hello world' }
21728
- * })
21823
+ * import { createMessage, createQuery, runQuery } from '@amityco/ts-sdk'
21824
+ *
21825
+ * const query = createQuery(createMessage, {
21826
+ * subChannelId: 'foobar',
21827
+ * data: { text: 'hello world' },
21828
+ * });
21829
+ *
21830
+ * runQuery(query, ({ data: message, loading }) => {
21831
+ * console.log(message);
21832
+ * });
21729
21833
  * ```
21730
21834
  *
21731
21835
  * Creates an {@link Amity.Message}
@@ -21738,13 +21842,19 @@ const uuid = () => nativeIdGenerator.v4().toString();
21738
21842
  */
21739
21843
  const createMessage = async (bundle) => {
21740
21844
  const client = getActiveClient();
21741
- client.log('user/createMessage', bundle);
21742
- const { data } = await client.http.post('/api/v3/messages', bundle);
21845
+ client.log('message/createMessage', bundle);
21846
+ const referenceId = uniqueId;
21847
+ uniqueId = undefined;
21848
+ const { data } = await client.http
21849
+ .post('/api/v5/messages', Object.assign(Object.assign({}, convertParams(bundle)), { referenceId }))
21850
+ .then(convertResponseFromRaw);
21743
21851
  const cachedAt = client.cache && Date.now();
21744
- if (client.cache)
21852
+ if (client.cache) {
21853
+ dropFromCache(['message', 'get', referenceId]);
21745
21854
  ingestInCache(data, { cachedAt });
21855
+ }
21746
21856
  const { messages } = data;
21747
- fireEvent('v3.message.didCreate', { messages });
21857
+ fireEvent('local.message.created', { messages });
21748
21858
  return {
21749
21859
  data: messages[0],
21750
21860
  cachedAt,
@@ -21753,7 +21863,8 @@ const createMessage = async (bundle) => {
21753
21863
  /**
21754
21864
  * ```js
21755
21865
  * import { createMessage } from '@amityco/ts-sdk'
21756
- * const created = createMessage.locally({
21866
+ *
21867
+ * const created = createMessage.optimistically({
21757
21868
  * channelId: 'foobar',
21758
21869
  * data: { text: 'hello world' }
21759
21870
  * })
@@ -21778,17 +21889,26 @@ createMessage.optimistically = (bundle) => {
21778
21889
  * Updated to handle client requirement to add messageId while uploading
21779
21890
  * message with image. Temporary!
21780
21891
  */
21781
- const bundleWithMessageId = Object.assign({ messageId: uuid() }, bundle);
21782
- // only log if cache is enabled
21783
- client.log('user/createMessage.locally', bundleWithMessageId);
21784
- const channel = pullFromCache(['channel', 'get', bundleWithMessageId.channelId]);
21785
- upsertInCache(['channel', 'get', bundleWithMessageId.channelId], Object.assign(Object.assign({}, channel === null || channel === void 0 ? void 0 : channel.data), { messageCount: ((_a = channel === null || channel === void 0 ? void 0 : channel.data.messageCount) !== null && _a !== void 0 ? _a : 0) + 1 }));
21892
+ const localId = `LOCAL_${uuid()}`;
21893
+ uniqueId = localId;
21894
+ const bundleWithMessageId = Object.assign({ messageId: localId, uniqueId: localId }, bundle);
21895
+ client.log('message/createMessage.optimistically', bundleWithMessageId);
21896
+ const subChannel = pullFromCache(['subChannel', 'get', bundle.subChannelId]);
21897
+ if (subChannel) {
21898
+ upsertInCache(['subChannel', 'get', bundle.subChannelId], Object.assign(Object.assign({}, subChannel.data), { messageCount: subChannel.data.messageCount + 1 }));
21899
+ if (subChannel.data.channelId === subChannel.data.subChannelId) {
21900
+ const channel = pullFromCache(['channel', 'get', subChannel.data.channelId]);
21901
+ if (channel === null || channel === void 0 ? void 0 : channel.data) {
21902
+ upsertInCache(['channel', 'get', subChannel.data.channelId], Object.assign(Object.assign({}, channel.data), { messageCount: ((_a = channel.data.messageCount) !== null && _a !== void 0 ? _a : 0) + 1 }));
21903
+ }
21904
+ }
21905
+ }
21786
21906
  // as reused to update created and updated time, which should be the same
21787
21907
  const createdTime = new Date().toISOString();
21788
- const message = Object.assign({ userId: client.userId, channelSegment: ((_b = channel === null || channel === void 0 ? void 0 : channel.data.messageCount) !== null && _b !== void 0 ? _b : 0) + 1, createdAt: createdTime, updatedAt: createdTime }, bundleWithMessageId);
21908
+ const message = Object.assign({ creatorId: client.userId, channelSegment: ((_b = subChannel === null || subChannel === void 0 ? void 0 : subChannel.data.messageCount) !== null && _b !== void 0 ? _b : 0) + 1, childrenNumber: 0, createdAt: createdTime, updatedAt: createdTime }, bundleWithMessageId);
21789
21909
  const cachedAt = UNSYNCED_OBJECT_CACHED_AT_VALUE;
21790
21910
  pushToCache(['message', 'get', message.messageId], message, { cachedAt });
21791
- fireEvent('v3.message.didCreate', { messages: [message] });
21911
+ fireEvent('local.message.created', { messages: [message] });
21792
21912
  return {
21793
21913
  cachedAt,
21794
21914
  data: message,
@@ -21814,13 +21934,15 @@ createMessage.optimistically = (bundle) => {
21814
21934
  */
21815
21935
  const updateMessage = async (messageId, patch) => {
21816
21936
  const client = getActiveClient();
21817
- client.log('user/updateMessage', patch);
21818
- const { data } = await client.http.put(`/api/v3/messages/${encodeURIComponent(messageId)}`, patch);
21937
+ client.log('message/updateMessage', patch);
21938
+ const { data } = await client.http
21939
+ .put(`/api/v5/messages/${encodeURIComponent(messageId)}`, convertParams(patch))
21940
+ .then(convertResponseFromRaw);
21819
21941
  const cachedAt = client.cache && Date.now();
21820
21942
  if (client.cache)
21821
21943
  ingestInCache(data, { cachedAt });
21822
21944
  const { messages } = data;
21823
- fireEvent('v3.message.didUpdate', { messages });
21945
+ fireEvent('local.message.updated', { messages });
21824
21946
  return {
21825
21947
  data: messages.find(message => message.messageId === messageId),
21826
21948
  cachedAt,
@@ -21829,7 +21951,7 @@ const updateMessage = async (messageId, patch) => {
21829
21951
  /**
21830
21952
  * ```js
21831
21953
  * import { updateMessage } from '@amityco/ts-sdk'
21832
- * const updated = updateMessage.locally('foobar', {
21954
+ * const updated = updateMessage.optimistically('foobar', {
21833
21955
  * data: { text: 'hello world' }
21834
21956
  * })
21835
21957
  * ```
@@ -21844,7 +21966,7 @@ const updateMessage = async (messageId, patch) => {
21844
21966
  */
21845
21967
  updateMessage.optimistically = (messageId, patch) => {
21846
21968
  const client = getActiveClient();
21847
- client.log('user/updateMessage', patch);
21969
+ client.log('message/updateMessage.optimistically', patch);
21848
21970
  if (!client.cache)
21849
21971
  return;
21850
21972
  const message = pullFromCache(['message', 'get', messageId]);
@@ -21853,7 +21975,7 @@ updateMessage.optimistically = (messageId, patch) => {
21853
21975
  const cachedAt = -1;
21854
21976
  const updated = Object.assign(Object.assign(Object.assign({}, message.data), patch), { updatedAt: new Date().toISOString() });
21855
21977
  upsertInCache(['message', 'get', messageId], updated, { cachedAt });
21856
- fireEvent('v3.message.didUpdate', { messages: [updated] });
21978
+ fireEvent('local.message.updated', { messages: [updated] });
21857
21979
  return {
21858
21980
  data: updated,
21859
21981
  cachedAt,
@@ -21868,7 +21990,7 @@ updateMessage.optimistically = (messageId, patch) => {
21868
21990
  *
21869
21991
  * Delete a {@link Amity.Message}
21870
21992
  *
21871
- * @param The ID of the {@link Amity.Message} to delete
21993
+ * @param messageId the ID of the {@link Amity.Message} to delete
21872
21994
  * @return A success boolean if the {@link Amity.Message} was deleted
21873
21995
  *
21874
21996
  * @category Message API
@@ -21878,15 +22000,15 @@ const deleteMessage = async (messageId) => {
21878
22000
  const client = getActiveClient();
21879
22001
  client.log('message/deleteMessage', messageId);
21880
22002
  // API-FIX: This endpoint has not been implemented yet.
21881
- await client.http.delete(`/api/v3/messages/${encodeURIComponent(messageId)}`);
22003
+ await client.http.delete(`/api/v5/messages/${encodeURIComponent(messageId)}`);
21882
22004
  const deleted = await getMessage(messageId);
21883
- fireEvent('v3.message.didDelete', { messages: [deleted.data] });
22005
+ fireEvent('local.message.deleted', { messages: [deleted.data] });
21884
22006
  return deleted.data;
21885
22007
  };
21886
22008
  /**
21887
22009
  * ```js
21888
22010
  * import { deleteMessage } from '@amityco/ts-sdk'
21889
- * const success = deleteMessage.locally('foobar')
22011
+ * const success = deleteMessage.optimistically('foobar')
21890
22012
  * ```
21891
22013
  *
21892
22014
  * Deletes a {@link Amity.Message}
@@ -21898,14 +22020,14 @@ const deleteMessage = async (messageId) => {
21898
22020
  */
21899
22021
  deleteMessage.optimistically = (messageId) => {
21900
22022
  const client = getActiveClient();
21901
- client.log('message/deleteMessage', messageId);
22023
+ client.log('message/deleteMessage.optimistically', messageId);
21902
22024
  const message = pullFromCache(['message', 'get', messageId]);
21903
22025
  if (!message)
21904
22026
  return;
21905
22027
  const cachedAt = -1;
21906
22028
  const deleted = Object.assign(Object.assign({}, message.data), { isDeleted: true, updatedAt: new Date().toISOString() });
21907
22029
  upsertInCache(['message', 'get', messageId], deleted, { cachedAt });
21908
- fireEvent('v3.message.didDelete', { messages: [deleted] });
22030
+ fireEvent('local.message.deleted', { messages: [deleted] });
21909
22031
  return {
21910
22032
  data: deleted,
21911
22033
  cachedAt,
@@ -21930,11 +22052,20 @@ const queryPosts = async (query) => {
21930
22052
  const client = getActiveClient();
21931
22053
  client.log('post/queryPosts', query);
21932
22054
  const { page = { limit: 10 } } = query, params = __rest(query, ["page"]);
22055
+ const { dataTypes, matchingOnlyParentPost } = params;
21933
22056
  // API-FIX: parameters should be querystring. (1)
21934
22057
  // API-FIX: backend should answer Amity.Response (2)
21935
22058
  // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.PostPayload>>>(
21936
22059
  const { data } = await client.http.get(`/api/v4/posts`, {
21937
- params: Object.assign(Object.assign({}, params), { options: {
22060
+ params: Object.assign(Object.assign({}, params), {
22061
+ /*
22062
+ * when creating post like image, file, video BE will create 2 posts
22063
+ * 1. parent post to store text with dataType=text
22064
+ * 2. child post to store dataTypes post data
22065
+ *
22066
+ * By default BE queries only parent post
22067
+ */
22068
+ matchingOnlyParentPost: matchingOnlyParentPost !== null && matchingOnlyParentPost !== void 0 ? matchingOnlyParentPost : !(dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length), options: {
21938
22069
  token: toToken(page, 'afterbeforeraw'),
21939
22070
  } }),
21940
22071
  });
@@ -22232,12 +22363,13 @@ const queryCommunities = async (query) => {
22232
22363
  const client = getActiveClient();
22233
22364
  client.log('channel/queryCommunities', query);
22234
22365
  // safe decapsulation
22235
- const _a = query !== null && query !== void 0 ? query : {}, { page, displayName, membership } = _a, params = __rest(_a, ["page", "displayName", "membership"]);
22366
+ const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
22367
+ const _b = params !== null && params !== void 0 ? params : {}, { displayName, membership } = _b, restParams = __rest(_b, ["displayName", "membership"]);
22236
22368
  // API-FIX: parameters should be querystring.
22237
22369
  // API-FIX: backend doesnt answer Amity.Response
22238
22370
  // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<CommunityPayload>>>(
22239
22371
  const { data } = await client.http.get(`/api/v3/communities`, {
22240
- params: Object.assign(Object.assign({}, params), { keyword: displayName, filter: membership, options: {
22372
+ params: Object.assign(Object.assign({}, restParams), { keyword: displayName, filter: membership, options: {
22241
22373
  token: toToken(page, 'skiplimit'),
22242
22374
  } }),
22243
22375
  });
@@ -22532,6 +22664,58 @@ const leaveCommunity = async (communityId) => {
22532
22664
  return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership !== 'member');
22533
22665
  };
22534
22666
 
22667
+ /**
22668
+ * Attach user object to membership model
22669
+ * - If cache is not enabled, set user to undefined ({..., user: undefined})
22670
+ * - If user object is not found in cache, set user to undefined
22671
+ * ({..., user: undefined})
22672
+ * - If a user is found in the cache, it attaches the user from the cache
22673
+ * ({..., user: { userId, displayName,... }})
22674
+ *
22675
+ * @param member The membership model object
22676
+ * @param userIdProp The user ID prop name of membership object
22677
+ * @param userProp The user prop name of destination object
22678
+ * @returns The membership model object that is already mapped to user
22679
+ * @hidden
22680
+ */
22681
+ const withUser = (member, userIdProp = 'userId', userProp = 'user') => (Object.assign({ get [userProp]() {
22682
+ var _a;
22683
+ const client = getActiveClient();
22684
+ if (!client.cache)
22685
+ return undefined;
22686
+ const userCache = (_a = pullFromCache(['user', 'get', member[userIdProp]])) === null || _a === void 0 ? void 0 : _a.data;
22687
+ if (!userCache) {
22688
+ return undefined;
22689
+ }
22690
+ return userCache;
22691
+ } }, member));
22692
+ /**
22693
+ * Mapping membership model with user object
22694
+ *
22695
+ * @param members The membership model objects
22696
+ * @param userIdProp The user ID prop name of membership object
22697
+ * @param userProp The user prop name of destination object
22698
+ * @returns The membership model objects that is already
22699
+ * mapped to users
22700
+ * @hidden
22701
+ */
22702
+ const withUsers = (members, userIdProp = 'userId', userProp = 'user') => members.map(member => withUser(member, userIdProp, userProp));
22703
+ /**
22704
+ * Transform members prop in any payload with attached users members
22705
+ *
22706
+ * @param payload The payload contain members prop
22707
+ * @param memberProp A name of members prop
22708
+ * @param userIdProp The user ID prop name of membership object
22709
+ * @param userProp The user prop name of destination object
22710
+ * @returns The transforming payload
22711
+ * @hidden
22712
+ */
22713
+ const prepareMembershipPayload = (payload, memberProp, userIdProp = 'userId', userProp = 'user') => {
22714
+ const _a = payload, _b = memberProp, memberPayload = _a[_b], rest = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
22715
+ const members = withUsers(memberPayload, userIdProp, userProp);
22716
+ return Object.assign(Object.assign({}, rest), { [memberProp]: members });
22717
+ };
22718
+
22535
22719
  /**
22536
22720
  * ```js
22537
22721
  * import { queryCommunityMembers } from '@amityco/ts-sdk'
@@ -22549,17 +22733,27 @@ const leaveCommunity = async (communityId) => {
22549
22733
  const queryCommunityMembers = async (query) => {
22550
22734
  const client = getActiveClient();
22551
22735
  client.log('community/queryCommunityMembers', query);
22552
- const _a = query !== null && query !== void 0 ? query : {}, { page, communityId } = _a, params = __rest(_a, ["page", "communityId"]);
22553
- const { data } = await client.http.get(`/api/v3/communities/${communityId}/users`, {
22736
+ const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
22737
+ const { data: queryPayload } = await client.http.get(`/api/v3/communities/${params.communityId}/users`, {
22554
22738
  params: Object.assign(Object.assign({}, params), { options: {
22555
22739
  token: toToken(page, 'skiplimit'),
22556
22740
  } }),
22557
22741
  });
22558
- const { paging } = data, payload = __rest(data, ["paging"]);
22559
- const { communityUsers } = payload;
22742
+ const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
22743
+ const preparedPayload = prepareMembershipPayload(payload, 'communityUsers');
22744
+ const { communityUsers } = preparedPayload;
22560
22745
  const cachedAt = client.cache && Date.now();
22561
22746
  if (client.cache) {
22562
- ingestInCache(payload, { cachedAt });
22747
+ ingestInCache(preparedPayload, { cachedAt });
22748
+ const cacheKey = [
22749
+ 'communityUsers',
22750
+ 'query',
22751
+ Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
22752
+ ];
22753
+ pushToCache(cacheKey, {
22754
+ communityUsers: communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
22755
+ paging,
22756
+ });
22563
22757
  }
22564
22758
  const nextPage = toPage(paging.next);
22565
22759
  const prevPage = toPage(paging.previous);
@@ -22579,9 +22773,29 @@ const queryCommunityMembers = async (query) => {
22579
22773
  * @category Post API
22580
22774
  */
22581
22775
  queryCommunityMembers.locally = (query) => {
22776
+ var _a, _b;
22582
22777
  const client = getActiveClient();
22583
22778
  client.log('community/queryCommunityMembers', query);
22584
- // TODO
22779
+ if (!client.cache)
22780
+ return;
22781
+ const _c = query !== null && query !== void 0 ? query : {}, { page } = _c, params = __rest(_c, ["page"]);
22782
+ const cacheKey = [
22783
+ 'communityUsers',
22784
+ 'query',
22785
+ Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
22786
+ ];
22787
+ const { data, cachedAt } = (_a = pullFromCache(cacheKey)) !== null && _a !== void 0 ? _a : {};
22788
+ if (!(data === null || data === void 0 ? void 0 : data.communityUsers.length))
22789
+ return;
22790
+ const communityUsers = data.communityUsers
22791
+ .map(key => pullFromCache(['communityUsers', 'get', key]))
22792
+ .filter(Boolean)
22793
+ .map(({ data }) => data);
22794
+ const prevPage = toPage(data === null || data === void 0 ? void 0 : data.paging.previous);
22795
+ const nextPage = toPage(data === null || data === void 0 ? void 0 : data.paging.next);
22796
+ return communityUsers.length === ((_b = data === null || data === void 0 ? void 0 : data.communityUsers) === null || _b === void 0 ? void 0 : _b.length)
22797
+ ? { data: communityUsers, cachedAt, prevPage, nextPage }
22798
+ : undefined;
22585
22799
  };
22586
22800
 
22587
22801
  /**
@@ -23290,38 +23504,6 @@ const preparePayloadForCache = (event, payload) => {
23290
23504
  }
23291
23505
  };
23292
23506
 
23293
- /** @hidden */
23294
- /*
23295
- * @param message payload from http request without myReactions
23296
- * add myReactions to http response if the event was a reaction event
23297
- */
23298
- const prepareMessagePayloadForCache = (payload) => {
23299
- const client = getActiveClient();
23300
- const cached = pullFromCache(['message', 'get', payload.messageId]);
23301
- // '[]' in cases where the new reaction is the first one
23302
- const myReactions = (cached === null || cached === void 0 ? void 0 : cached.data.myReactions) || [];
23303
- // add myReactions to the payload
23304
- Object.assign(payload, { myReactions });
23305
- // check if there are any updates to the reactions
23306
- const latestReaction = payload === null || payload === void 0 ? void 0 : payload.latestReaction;
23307
- const isLatestReactionMine = latestReaction && latestReaction.userId === client.userId;
23308
- if (!isLatestReactionMine) {
23309
- return;
23310
- }
23311
- // new reaction added
23312
- if (latestReaction.eventName === 'add' && !myReactions.includes(latestReaction.reactionName)) {
23313
- Object.assign(payload, {
23314
- myReactions: [...myReactions, latestReaction.reactionName],
23315
- });
23316
- }
23317
- // existing reaction removed
23318
- if (latestReaction.eventName === 'remove' && myReactions.includes(latestReaction.reactionName)) {
23319
- Object.assign(payload, {
23320
- myReactions: myReactions.filter(x => x !== latestReaction.reactionName),
23321
- });
23322
- }
23323
- };
23324
-
23325
23507
  /**
23326
23508
  * ```js
23327
23509
  * import { addReaction } from '@amityco/ts-sdk'
@@ -23349,6 +23531,7 @@ const addReaction = async (referenceType, referenceId, reactionName) => {
23349
23531
  referenceId,
23350
23532
  referenceType,
23351
23533
  reactionName,
23534
+ referenceVersion: referenceType === 'message' ? 5 : undefined,
23352
23535
  });
23353
23536
  if (client.cache) {
23354
23537
  const model = pullFromCache([
@@ -23425,7 +23608,12 @@ const removeReaction = async (referenceType, referenceId, reactionName) => {
23425
23608
  reactionName,
23426
23609
  });
23427
23610
  await client.http.delete(`/api/v2/reactions`, {
23428
- data: { referenceId, referenceType, reactionName },
23611
+ data: {
23612
+ referenceId,
23613
+ referenceType,
23614
+ reactionName,
23615
+ referenceVersion: referenceType === 'message' ? 5 : undefined,
23616
+ },
23429
23617
  });
23430
23618
  if (client.cache) {
23431
23619
  const model = pullFromCache([
@@ -23938,8 +24126,9 @@ const onReactionAdded = (referenceType, referenceId, callback) => {
23938
24126
  */
23939
24127
  if (referenceType === 'message') {
23940
24128
  const client = getActiveClient();
23941
- const filter = (payload) => {
24129
+ const filter = (rawPayload) => {
23942
24130
  var _a;
24131
+ const payload = prepareMessagePayload(rawPayload);
23943
24132
  const cached = pullFromCache([
23944
24133
  'message',
23945
24134
  'get',
@@ -23951,7 +24140,7 @@ const onReactionAdded = (referenceType, referenceId, callback) => {
23951
24140
  callbackWrapper(payload.messages[0]);
23952
24141
  }
23953
24142
  };
23954
- return createEventSubscriber(client, 'reaction/onReactionAdded', 'v3.message.didUpdate', filter);
24143
+ return createEventSubscriber(client, 'reaction/onReactionAdded', 'message.updated', filter);
23955
24144
  }
23956
24145
  if (referenceType === 'post') {
23957
24146
  return onPostReactionAdded(callbackWrapper);
@@ -23984,8 +24173,9 @@ const onReactionRemoved = (referenceType, referenceId, callback) => {
23984
24173
  };
23985
24174
  if (referenceType === 'message') {
23986
24175
  const client = getActiveClient();
23987
- const filter = (payload) => {
24176
+ const filter = (rawPayload) => {
23988
24177
  var _a;
24178
+ const payload = prepareMessagePayload(rawPayload);
23989
24179
  const cached = pullFromCache([
23990
24180
  'message',
23991
24181
  'get',
@@ -23997,7 +24187,7 @@ const onReactionRemoved = (referenceType, referenceId, callback) => {
23997
24187
  callbackWrapper(payload.messages[0]);
23998
24188
  }
23999
24189
  };
24000
- return createEventSubscriber(client, 'reaction/onReactionRemoved', 'v3.message.didUpdate', filter);
24190
+ return createEventSubscriber(client, 'reaction/onReactionRemoved', 'message.updated', filter);
24001
24191
  }
24002
24192
  if (referenceType === 'post') {
24003
24193
  return onPostReactionRemoved(callbackWrapper);
@@ -24030,7 +24220,8 @@ const onReactorAdded = (referenceType, referenceId, callback) => {
24030
24220
  }
24031
24221
  };
24032
24222
  if (referenceType === 'message') {
24033
- const filter = (payload) => {
24223
+ const filter = (rawPayload) => {
24224
+ const payload = prepareMessagePayload(rawPayload);
24034
24225
  if (!payload.messages[0].latestReaction)
24035
24226
  return;
24036
24227
  const _a = payload.messages[0].latestReaction, { eventName, referenceId, referenceType, userDisplayName } = _a, reactor = __rest(_a, ["eventName", "referenceId", "referenceType", "userDisplayName"]);
@@ -24040,7 +24231,7 @@ const onReactorAdded = (referenceType, referenceId, callback) => {
24040
24231
  ingestInCache({ reactions: [reactor] });
24041
24232
  callbackWrapper('message', payload.messages[0].messageId, reactor);
24042
24233
  };
24043
- return createEventSubscriber(client, 'reaction/onReactorAdded', 'v3.message.didUpdate', filter);
24234
+ return createEventSubscriber(client, 'reaction/onReactorAdded', 'message.updated', filter);
24044
24235
  }
24045
24236
  if (referenceType === 'post') {
24046
24237
  const filter = (payload) => {
@@ -24085,7 +24276,8 @@ const onReactorRemoved = (referenceType, referenceId, callback) => {
24085
24276
  }
24086
24277
  };
24087
24278
  if (referenceType === 'message') {
24088
- const filter = (payload) => {
24279
+ const filter = (rawPayload) => {
24280
+ const payload = prepareMessagePayload(rawPayload);
24089
24281
  if (!payload.messages[0].latestReaction)
24090
24282
  return;
24091
24283
  const _a = payload.messages[0].latestReaction, { eventName, referenceId, referenceType } = _a, reactor = __rest(_a, ["eventName", "referenceId", "referenceType"]);
@@ -24095,7 +24287,7 @@ const onReactorRemoved = (referenceType, referenceId, callback) => {
24095
24287
  ingestInCache({ reactions: [reactor] });
24096
24288
  callbackWrapper('message', payload.messages[0].messageId, reactor);
24097
24289
  };
24098
- return createEventSubscriber(client, 'reaction/onReactorRemoved', 'v3.message.didUpdate', filter);
24290
+ return createEventSubscriber(client, 'reaction/onReactorRemoved', 'message.updated', filter);
24099
24291
  }
24100
24292
  if (referenceType === 'post') {
24101
24293
  const filter = (payload) => {
@@ -24165,7 +24357,7 @@ const liveReactions = (params, callback, config) => {
24165
24357
  error: data.error,
24166
24358
  });
24167
24359
  };
24168
- const realtimeRouter = (reaction, action) => {
24360
+ const realtimeRouter = (action) => (reaction) => {
24169
24361
  var _a;
24170
24362
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24171
24363
  if (!collection)
@@ -24202,7 +24394,7 @@ const liveReactions = (params, callback, config) => {
24202
24394
  responder(data);
24203
24395
  }, queryOptions(policy));
24204
24396
  };
24205
- disposers.push(onReactorAdded(queryParams.referenceType, queryParams.referenceId, reaction => realtimeRouter(reaction, 'onAdded')), onReactorRemoved(queryParams.referenceType, queryParams.referenceId, reaction => realtimeRouter(reaction, 'onRemoved')));
24397
+ disposers.push(onReactorAdded(queryParams.referenceType, queryParams.referenceId, realtimeRouter('onAdded')), onReactorRemoved(queryParams.referenceType, queryParams.referenceId, realtimeRouter('onRemoved')));
24206
24398
  onFetch();
24207
24399
  return () => {
24208
24400
  log(`liveReactions(tmpid: ${timestamp}) > dispose`);
@@ -24249,16 +24441,26 @@ var REFERENCE_TYPES = {
24249
24441
  const createReport = async (referenceType, referenceId) => {
24250
24442
  const client = getActiveClient();
24251
24443
  client.log('report/createReport', { referenceType, referenceId });
24252
- const { domainName } = REFERENCE_TYPES[referenceType];
24253
- const { data } = await client.http.post(`/api/${referenceType === 'user'
24254
- ? `v4/me/flags/${encodeURIComponent(referenceId)}`
24255
- : `v3/${domainName}/${encodeURIComponent(referenceId)}/flag`}`);
24444
+ const getAPIUrl = () => {
24445
+ if (referenceType === 'user') {
24446
+ return `/api/v4/me/flags/${encodeURIComponent(referenceId)}`;
24447
+ }
24448
+ if (referenceType === 'message') {
24449
+ return `/api/v5/messages/${encodeURIComponent(referenceId)}/flags`;
24450
+ }
24451
+ const { domainName } = REFERENCE_TYPES[referenceType];
24452
+ return `/api/v3/${domainName}/${encodeURIComponent(referenceId)}/flag`;
24453
+ };
24454
+ const { data } = await client.http.post(getAPIUrl());
24256
24455
  if (client.cache)
24257
- ingestInCache(data);
24258
- const event = referenceType === 'message'
24259
- ? 'v3.message.didUpdate'
24260
- : `${referenceType}.flagged`;
24261
- fireEvent(event, data);
24456
+ ingestInCache(referenceType === 'message' ? prepareMessagePayload(data) : data);
24457
+ if (referenceType === 'message') {
24458
+ fireEvent('message.flagged', data);
24459
+ }
24460
+ else {
24461
+ // @ts-ignore
24462
+ fireEvent(`${referenceType}.flagged`, data);
24463
+ }
24262
24464
  return !!data;
24263
24465
  };
24264
24466
 
@@ -24278,17 +24480,27 @@ const createReport = async (referenceType, referenceId) => {
24278
24480
  const deleteReport = async (referenceType, referenceId) => {
24279
24481
  const client = getActiveClient();
24280
24482
  client.log('report/deleteReport', { referenceType, referenceId });
24281
- const { domainName } = REFERENCE_TYPES[referenceType];
24282
- const { data } = await client.http.delete(`/api/${referenceType === 'user'
24283
- ? `v4/me/flags/${encodeURIComponent(referenceId)}`
24284
- : `v3/${domainName}/${encodeURIComponent(referenceId)}/unflag`}`);
24483
+ const getAPIUrl = () => {
24484
+ if (referenceType === 'user') {
24485
+ return `/api/v4/me/flags/${encodeURIComponent(referenceId)}`;
24486
+ }
24487
+ if (referenceType === 'message') {
24488
+ return `/api/v5/messages/${encodeURIComponent(referenceId)}/flags`;
24489
+ }
24490
+ const { domainName } = REFERENCE_TYPES[referenceType];
24491
+ return `/api/v3/${domainName}/${encodeURIComponent(referenceId)}/unflag`;
24492
+ };
24493
+ const { data } = await client.http.delete(getAPIUrl());
24285
24494
  if (client.cache)
24286
- ingestInCache(data);
24287
- const event = referenceType === 'message'
24288
- ? 'v3.message.didUpdate'
24289
- : `${referenceType}.unflagged`;
24290
- fireEvent(event, data);
24291
- return !!data;
24495
+ ingestInCache(referenceType === 'message' ? prepareMessagePayload(data) : data);
24496
+ if (referenceType === 'message') {
24497
+ fireEvent('message.unflagged', data);
24498
+ }
24499
+ else {
24500
+ // @ts-ignore
24501
+ fireEvent(`${referenceType}.unflagged`, data);
24502
+ }
24503
+ return !!data;
24292
24504
  };
24293
24505
 
24294
24506
  /**
@@ -24309,26 +24521,45 @@ const isReportedByMe = async (referenceType, referenceId) => {
24309
24521
  const client = getActiveClient();
24310
24522
  client.log('report/isReportedByMe', { referenceType, referenceId });
24311
24523
  const { eventName, primaryKey } = REFERENCE_TYPES[referenceType];
24524
+ if (referenceType === 'message') {
24525
+ const { data } = await client.http.get(`/api/v5/messages/${encodeURIComponent(referenceId)}/flags`);
24526
+ return data.result;
24527
+ }
24312
24528
  const { result, isFlagByMe } = (_a = (await synchronousWSCall(client, eventName, {
24313
24529
  [primaryKey]: referenceId,
24314
24530
  }))) !== null && _a !== void 0 ? _a : {};
24315
24531
  return (_b = result !== null && result !== void 0 ? result : isFlagByMe) !== null && _b !== void 0 ? _b : false;
24316
24532
  };
24317
24533
 
24318
- /** @hidden */
24534
+ function convertFromRaw$1(_a, params) {
24535
+ var { _id } = _a, rest = __rest(_a, ["_id"]);
24536
+ return Object.assign(Object.assign(Object.assign({}, rest), params), { defaultSubChannelId: _id });
24537
+ }
24538
+ function getSegmentParams(rawChannel) {
24539
+ let cached;
24540
+ try {
24541
+ cached = pullFromCache(['channel', 'get', rawChannel.channelId]);
24542
+ // eslint-disable-next-line no-empty
24543
+ }
24544
+ catch (_a) { }
24545
+ if (cached) {
24546
+ return {
24547
+ defaultSubChannelHasUnreadMention: cached.data.defaultSubChannelHasUnreadMention,
24548
+ defaultSubChannelUnreadCount: cached.data.defaultSubChannelUnreadCount,
24549
+ localReadToSegment: cached.data.localReadToSegment,
24550
+ localLastMentionSegment: cached.data.localLastMentionSegment,
24551
+ };
24552
+ }
24553
+ return {
24554
+ defaultSubChannelHasUnreadMention: false,
24555
+ defaultSubChannelUnreadCount: 0,
24556
+ // @ts-ignore
24557
+ localReadToSegment: rawChannel.messageCount > 0 ? rawChannel.messageCount - 1 : 0,
24558
+ localLastMentionSegment: 0,
24559
+ };
24560
+ }
24319
24561
  const prepareChannelPayload = (payload) => {
24320
- const client = getActiveClient();
24321
- const channels = payload.channels.map(channel => {
24322
- const channelUser = payload.channelUsers.find(channelUser => channelUser.userId === client.userId && channel.channelId === channelUser.channelId);
24323
- const hasMention = channelUser
24324
- ? channelUser.readToSegment < channelUser.lastMentionedSegment
24325
- : false;
24326
- const unreadCount = channelUser && channelUser.membership === 'member' && channel.messageCount
24327
- ? Math.max(0, channel.messageCount - channelUser.readToSegment)
24328
- : 0;
24329
- return Object.assign(Object.assign({}, channel), { hasMention,
24330
- unreadCount });
24331
- });
24562
+ const channels = payload.channels.map(channel => convertFromRaw$1(channel, getSegmentParams(channel)));
24332
24563
  return Object.assign(Object.assign({}, payload), { channels });
24333
24564
  };
24334
24565
 
@@ -24464,10 +24695,10 @@ getChannels.locally = (channelIds) => {
24464
24695
  const cached = channelIds
24465
24696
  .map(channelId => pullFromCache(['channel', 'get', channelId]))
24466
24697
  .filter(Boolean);
24467
- const channels = cached.map(({ data }) => data);
24468
- const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
24469
24698
  if ((cached === null || cached === void 0 ? void 0 : cached.length) < channelIds.length)
24470
24699
  return;
24700
+ const channels = cached.map(({ data }) => data);
24701
+ const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
24471
24702
  return {
24472
24703
  data: channels,
24473
24704
  cachedAt: oldest.cachedAt,
@@ -24542,7 +24773,7 @@ getChannel.locally = (channelId) => {
24542
24773
  /**
24543
24774
  * ```js
24544
24775
  * import { createChannel } from '@amityco/ts-sdk'
24545
- * const created = await createChannel({ channelId: 'foobar', displayName: 'foobar' })
24776
+ * const created = await createChannel({ displayName: 'foobar' })
24546
24777
  * ```
24547
24778
  *
24548
24779
  * Creates an {@link Amity.Channel}
@@ -24694,18 +24925,19 @@ const leaveChannel = async (channelId) => {
24694
24925
  const queryChannelMembers = async (query) => {
24695
24926
  const client = getActiveClient();
24696
24927
  client.log('channel/queryChannelMembers', query);
24697
- const _a = query !== null && query !== void 0 ? query : {}, { page = { limit: 10 } } = _a, params = __rest(_a, ["page"]);
24928
+ const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
24698
24929
  const { data: queryPayload } = await client.http.get(`/api/v4/channels/${encodeURIComponent(params.channelId)}/users`, {
24699
24930
  params: Object.assign(Object.assign({}, params), { options: {
24700
24931
  token: toToken(page, 'skiplimit'),
24701
24932
  } }),
24702
24933
  });
24703
24934
  const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
24704
- const data = prepareChannelPayload(payload);
24705
- const { channelUsers } = data;
24935
+ const channelPayload = prepareChannelPayload(payload);
24936
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
24937
+ const { channelUsers } = preparedPayload;
24706
24938
  const cachedAt = client.cache && Date.now();
24707
24939
  if (client.cache) {
24708
- ingestInCache(data);
24940
+ ingestInCache(preparedPayload);
24709
24941
  const cacheKey = [
24710
24942
  'channelUsers',
24711
24943
  'query',
@@ -24718,7 +24950,12 @@ const queryChannelMembers = async (query) => {
24718
24950
  }
24719
24951
  const nextPage = toPage(paging.next);
24720
24952
  const prevPage = toPage(paging.previous);
24721
- return { data: channelUsers, cachedAt, nextPage, prevPage };
24953
+ return {
24954
+ data: channelUsers,
24955
+ cachedAt,
24956
+ nextPage,
24957
+ prevPage,
24958
+ };
24722
24959
  };
24723
24960
  /**
24724
24961
  * ```js
@@ -24739,7 +24976,7 @@ queryChannelMembers.locally = (query) => {
24739
24976
  client.log('channel/queryChannelMembers.locally', query);
24740
24977
  if (!client.cache)
24741
24978
  return;
24742
- const { page = { limit: 10 } } = query, params = __rest(query, ["page"]);
24979
+ const { page } = query, params = __rest(query, ["page"]);
24743
24980
  const cacheKey = [
24744
24981
  'channelUsers',
24745
24982
  'query',
@@ -24785,7 +25022,7 @@ const addChannelMembers = async (channelId, userIds) => {
24785
25022
  /*
24786
25023
  * should fire event for each user that was added
24787
25024
  */
24788
- userIds.forEach(id => fireEvent('v3.channel.didAddUsers', Object.assign(Object.assign({}, data), { channelUsers: data.channelUsers.filter(u => u.userId === id) })));
25025
+ userIds.forEach(id => fireEvent('channel.membersAdded', Object.assign(Object.assign({}, payload), { channelUsers: data.channelUsers.filter(u => u.userId === id) })));
24789
25026
  const { channelUsers } = data;
24790
25027
  return !!channelUsers.find(channelUser => channelUser.channelId === channelId && channelUser.membership === 'member');
24791
25028
  };
@@ -24812,7 +25049,10 @@ const removeChannelMembers = async (channelId, userIds) => {
24812
25049
  const data = prepareChannelPayload(payload);
24813
25050
  if (client.cache)
24814
25051
  ingestInCache(data);
24815
- fireEvent('v3.channel.didRemoveUsers', data);
25052
+ /*
25053
+ * should fire event for each user that was removed
25054
+ */
25055
+ userIds.forEach(id => fireEvent('channel.membersRemoved', Object.assign(Object.assign({}, payload), { channelUsers: data.channelUsers.filter(u => u.userId === id) })));
24816
25056
  const { channelUsers } = data;
24817
25057
  return !!channelUsers.find(channelUser => channelUser.channelId === channelId && channelUser.membership !== 'member');
24818
25058
  };
@@ -24891,11 +25131,12 @@ const banChannelMembers = async (channelId, userIds) => {
24891
25131
  const { data: payload } = await client.http.put(`/api/v3/channels/${channelId}/users/ban`, {
24892
25132
  userIds,
24893
25133
  });
24894
- const data = prepareChannelPayload(payload);
25134
+ const channelPayload = prepareChannelPayload(payload);
25135
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25136
+ const { channelUsers } = preparedPayload;
24895
25137
  const cachedAt = client.cache && Date.now();
24896
25138
  if (client.cache)
24897
- ingestInCache(data, { cachedAt });
24898
- const { channelUsers } = data;
25139
+ ingestInCache(preparedPayload, { cachedAt });
24899
25140
  return {
24900
25141
  data: channelUsers === null || channelUsers === void 0 ? void 0 : channelUsers.filter(user => user.membership === 'banned'),
24901
25142
  cachedAt,
@@ -24922,17 +25163,92 @@ const unbanChannelMembers = async (channelId, userIds) => {
24922
25163
  const { data: payload } = await client.http.put(`/api/v3/channels/${encodeURIComponent(channelId)}/users/unban`, {
24923
25164
  userIds,
24924
25165
  });
24925
- const data = prepareChannelPayload(payload);
25166
+ const channelPayload = prepareChannelPayload(payload);
25167
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
24926
25168
  const cachedAt = client.cache && Date.now();
24927
25169
  if (client.cache)
24928
- ingestInCache(data, { cachedAt });
24929
- const { channelUsers } = data;
25170
+ ingestInCache(preparedPayload, { cachedAt });
25171
+ const { channelUsers } = preparedPayload;
24930
25172
  return {
24931
25173
  data: channelUsers === null || channelUsers === void 0 ? void 0 : channelUsers.filter(user => user.membership === 'member'),
24932
25174
  cachedAt,
24933
25175
  };
24934
25176
  };
24935
25177
 
25178
+ /**
25179
+ * ```js
25180
+ * import { startReading } from '@amityco/ts-sdk'
25181
+ * const success = await startReading('foo')
25182
+ * ```
25183
+ *
25184
+ * Mark all messages as read and start reading message inside channel
25185
+ *
25186
+ * @param {string} subChannelId - The channel ID to start reading.
25187
+ * @param {string} userId - The user ID of channel member.
25188
+ * @return {Promise<boolean>>} A success boolean if the channel reading of the sub channel had begun.
25189
+ *
25190
+ * @category Message API
25191
+ * @async
25192
+ */
25193
+ const startReading = async (subChannelId, userId = getActiveClient().userId) => {
25194
+ const client = getActiveClient();
25195
+ client.log('message/startReading', { subChannelId });
25196
+ const subChannel = pullFromCache(['subChannel', 'get', subChannelId]);
25197
+ if (!subChannel) {
25198
+ return;
25199
+ }
25200
+ const { channelId } = subChannel.data;
25201
+ const channel = pullFromCache(['channel', 'get', channelId]);
25202
+ if (!channel || channel.data.defaultSubChannelId !== subChannelId) {
25203
+ return;
25204
+ }
25205
+ const update = Object.assign(Object.assign({}, channel.data), {
25206
+ // @ts-ignore
25207
+ localReading: true, defaultSubChannelUnreadCount: 0, defaultSubChannelHasUnreadMention: false });
25208
+ pushToCache(['channel', 'get', channelId], update);
25209
+ client.emitter.emit('local.channel.updated', { channels: [update] });
25210
+ const result = await synchronousWSCall(client, 'channel.startReading', {
25211
+ channelId,
25212
+ });
25213
+ return !!result;
25214
+ };
25215
+
25216
+ /**
25217
+ * ```js
25218
+ * import { stopReading } from '@amityco/ts-sdk'
25219
+ * const success = await stopReading('foo')
25220
+ * ```
25221
+ *
25222
+ * Stop reading message inside channel
25223
+ *
25224
+ * @param {string} subChannelId - The channel ID to stop reading.
25225
+ * @return {Promise<boolean>>} A success boolean if the sub channel reading was halted.
25226
+ *
25227
+ * @category Message API
25228
+ * @async
25229
+ */
25230
+ const stopReading = async (subChannelId) => {
25231
+ const client = getActiveClient();
25232
+ client.log('message/stopReading', { subChannelId });
25233
+ const subChannel = pullFromCache(['subChannel', 'get', subChannelId]);
25234
+ if (!subChannel) {
25235
+ return;
25236
+ }
25237
+ const { channelId } = subChannel.data;
25238
+ const channel = pullFromCache(['channel', 'get', channelId]);
25239
+ if (!channel || channel.data.defaultSubChannelId !== subChannelId) {
25240
+ return;
25241
+ }
25242
+ const update = Object.assign(Object.assign({}, channel.data), {
25243
+ // @ts-ignore
25244
+ localReading: false });
25245
+ pushToCache(['channel', 'get', channelId], update);
25246
+ const result = await synchronousWSCall(client, 'channel.stopReading', {
25247
+ channelId,
25248
+ });
25249
+ return !!result;
25250
+ };
25251
+
24936
25252
  /**
24937
25253
  * ```js
24938
25254
  * import { onChannelCreated } from '@amityco/ts-sdk'
@@ -24955,7 +25271,7 @@ const onChannelCreated = (callback) => {
24955
25271
  ingestInCache(data);
24956
25272
  callback(data.channels[0]);
24957
25273
  };
24958
- return createEventSubscriber(client, 'onChannelCreated', 'v3.channel.didCreate', filter);
25274
+ return createEventSubscriber(client, 'onChannelCreated', 'channel.created', filter);
24959
25275
  };
24960
25276
 
24961
25277
  /**
@@ -24980,7 +25296,13 @@ const onChannelUpdated = (callback) => {
24980
25296
  ingestInCache(data);
24981
25297
  callback(data.channels[0]);
24982
25298
  };
24983
- return createEventSubscriber(client, 'onChannelUpdated', 'v3.channel.didUpdate', filter);
25299
+ const disposers = [
25300
+ createEventSubscriber(client, 'onChannelUpdated', 'channel.updated', filter),
25301
+ createEventSubscriber(client, 'local.channel.updated', 'local.channel.updated', payload => callback(payload.channels[0])),
25302
+ ];
25303
+ return () => {
25304
+ disposers.forEach(fn => fn());
25305
+ };
24984
25306
  };
24985
25307
 
24986
25308
  /**
@@ -25005,13 +25327,13 @@ const onChannelDeleted = (callback) => {
25005
25327
  ingestInCache(data);
25006
25328
  callback(data.channels[0]);
25007
25329
  };
25008
- return createEventSubscriber(client, 'onChannelDeleted', 'v3.channel.didDelete', filter);
25330
+ return createEventSubscriber(client, 'onChannelDeleted', 'channel.deleted', filter);
25009
25331
  };
25010
25332
 
25011
25333
  /**
25012
25334
  * ```js
25013
25335
  * import { onChannelJoined } from '@amityco/ts-sdk'
25014
- * const dispose = onChannelJoined(channel => {
25336
+ * const dispose = onChannelJoined((channel, member) => {
25015
25337
  * // ...
25016
25338
  * })
25017
25339
  * ```
@@ -25026,17 +25348,19 @@ const onChannelDeleted = (callback) => {
25026
25348
  const onChannelJoined = (callback) => {
25027
25349
  const client = getActiveClient();
25028
25350
  const filter = (payload) => {
25029
- const data = prepareChannelPayload(payload);
25030
- ingestInCache(data);
25031
- callback(data.channels[0]);
25351
+ const channelPayload = prepareChannelPayload(payload);
25352
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25353
+ const { channels, channelUsers } = preparedPayload;
25354
+ ingestInCache(preparedPayload);
25355
+ callback(channels[0], channelUsers[0]);
25032
25356
  };
25033
- return createEventSubscriber(client, 'onChannelJoined', 'v3.channel.didJoin', filter);
25357
+ return createEventSubscriber(client, 'onChannelJoined', 'channel.joined', filter);
25034
25358
  };
25035
25359
 
25036
25360
  /**
25037
25361
  * ```js
25038
25362
  * import { onChannelLeft } from '@amityco/ts-sdk'
25039
- * const dispose = onChannelLeft(channel => {
25363
+ * const dispose = onChannelLeft((channel, member) => {
25040
25364
  * // ...
25041
25365
  * })
25042
25366
  * ```
@@ -25049,13 +25373,40 @@ const onChannelJoined = (callback) => {
25049
25373
  * @category Channel Events
25050
25374
  */
25051
25375
  const onChannelLeft = (callback) => {
25376
+ const client = getActiveClient();
25377
+ const filter = (payload) => {
25378
+ const channelPayload = prepareChannelPayload(payload);
25379
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25380
+ const { channels, channelUsers } = preparedPayload;
25381
+ ingestInCache(preparedPayload);
25382
+ callback(channels[0], channelUsers[0]);
25383
+ };
25384
+ return createEventSubscriber(client, 'onChannelLeft', 'channel.left', filter);
25385
+ };
25386
+
25387
+ /**
25388
+ * ```js
25389
+ * import { onChannelMuted } from '@amityco/ts-sdk'
25390
+ * const dispose = onChannelMuted(channel => {
25391
+ * // ...
25392
+ * })
25393
+ * ```
25394
+ *
25395
+ * Fired when any {@link Amity.Channel} have been muted
25396
+ *
25397
+ * @param callback The function to call when the event was fired
25398
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
25399
+ *
25400
+ * @category Channel Events
25401
+ */
25402
+ const onChannelMuted = (callback) => {
25052
25403
  const client = getActiveClient();
25053
25404
  const filter = (payload) => {
25054
25405
  const data = prepareChannelPayload(payload);
25055
25406
  ingestInCache(data);
25056
25407
  callback(data.channels[0]);
25057
25408
  };
25058
- return createEventSubscriber(client, 'onChannelLeft', 'v3.channel.didLeave', filter);
25409
+ return createEventSubscriber(client, 'onChannelMuted', 'channel.setMuted', filter);
25059
25410
  };
25060
25411
 
25061
25412
  /**
@@ -25076,11 +25427,13 @@ const onChannelLeft = (callback) => {
25076
25427
  const onChannelMemberAdded = (callback) => {
25077
25428
  const client = getActiveClient();
25078
25429
  const filter = (payload) => {
25079
- const data = prepareChannelPayload(payload);
25080
- ingestInCache(data);
25081
- callback(data.channels[0], data.channelUsers[0]);
25430
+ const channelPayload = prepareChannelPayload(payload);
25431
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25432
+ const { channels, channelUsers } = preparedPayload;
25433
+ ingestInCache(preparedPayload);
25434
+ callback(channels[0], channelUsers.find(cu => cu.membership === 'member'));
25082
25435
  };
25083
- return createEventSubscriber(client, 'onChannelMemberAdded', 'v3.channel.didAddUsers', filter);
25436
+ return createEventSubscriber(client, 'onChannelMemberAdded', 'channel.membersAdded', filter);
25084
25437
  };
25085
25438
 
25086
25439
  /**
@@ -25101,11 +25454,13 @@ const onChannelMemberAdded = (callback) => {
25101
25454
  const onChannelMemberRemoved = (callback) => {
25102
25455
  const client = getActiveClient();
25103
25456
  const filter = (payload) => {
25104
- const data = prepareChannelPayload(payload);
25105
- ingestInCache(data);
25106
- callback(data.channels[0], data.channelUsers[0]);
25457
+ const channelPayload = prepareChannelPayload(payload);
25458
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25459
+ const { channels, channelUsers } = preparedPayload;
25460
+ ingestInCache(preparedPayload);
25461
+ callback(channels[0], channelUsers[0]);
25107
25462
  };
25108
- return createEventSubscriber(client, 'onChannelMemberRemoved', 'v3.channel.didRemoveUsers', filter);
25463
+ return createEventSubscriber(client, 'onChannelMemberRemoved', 'channel.membersRemoved', filter);
25109
25464
  };
25110
25465
 
25111
25466
  /**
@@ -25126,11 +25481,13 @@ const onChannelMemberRemoved = (callback) => {
25126
25481
  const onChannelMemberBanned = (callback) => {
25127
25482
  const client = getActiveClient();
25128
25483
  const filter = (payload) => {
25129
- const data = prepareChannelPayload(payload);
25130
- ingestInCache(data);
25131
- callback(data.channels[0], data.channelUsers.find(cu => cu.membership === 'banned'));
25484
+ const channelPayload = prepareChannelPayload(payload);
25485
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25486
+ const { channels, channelUsers } = preparedPayload;
25487
+ ingestInCache(preparedPayload);
25488
+ callback(channels[0], channelUsers.find(cu => cu.membership === 'banned'));
25132
25489
  };
25133
- return createEventSubscriber(client, 'onChannelMemberBanned', 'v3.channel.didBan', filter);
25490
+ return createEventSubscriber(client, 'onChannelMemberBanned', 'channel.banned', filter);
25134
25491
  };
25135
25492
 
25136
25493
  /**
@@ -25151,11 +25508,13 @@ const onChannelMemberBanned = (callback) => {
25151
25508
  const onChannelMemberUnbanned = (callback) => {
25152
25509
  const client = getActiveClient();
25153
25510
  const filter = (payload) => {
25154
- const data = prepareChannelPayload(payload);
25155
- ingestInCache(data);
25156
- callback(data.channels[0], data.channelUsers.find(cu => cu.membership === 'none'));
25511
+ const channelPayload = prepareChannelPayload(payload);
25512
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25513
+ const { channels, channelUsers } = preparedPayload;
25514
+ ingestInCache(preparedPayload);
25515
+ callback(channels[0], channelUsers.find(cu => cu.membership === 'none'));
25157
25516
  };
25158
- return createEventSubscriber(client, 'onChannelMemberBanned', 'v3.channel.didUnban', filter);
25517
+ return createEventSubscriber(client, 'onChannelMemberUnbanned', 'channel.unbanned', filter);
25159
25518
  };
25160
25519
 
25161
25520
  /**
@@ -25191,7 +25550,7 @@ const observeChannel = (channelId, callback) => {
25191
25550
  (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
25192
25551
  };
25193
25552
  const disposers = [];
25194
- disposers.push(onChannelUpdated(data => router({ data, loading: false, origin: 'event' }, 'onUpdate')), onChannelDeleted(data => router({ data, loading: false, origin: 'event' }, 'onDelete')), onChannelJoined(data => router({ data, loading: false, origin: 'event' }, 'onJoin')), onChannelLeft(data => router({ data, loading: false, origin: 'event' }, 'onLeft')), onChannelMemberAdded(data => router({ data, loading: false, origin: 'event' }, 'onMemberAdded')), onChannelMemberRemoved(data => router({ data, loading: false, origin: 'event' }, 'onMemberRemoved')));
25553
+ disposers.push(onChannelUpdated(data => router({ data, loading: false, origin: 'event' }, 'onUpdate')), onChannelDeleted(data => router({ data, loading: false, origin: 'event' }, 'onDelete')), onChannelJoined(data => router({ data, loading: false, origin: 'event' }, 'onJoin')), onChannelLeft(data => router({ data, loading: false, origin: 'event' }, 'onLeft')), onChannelMuted(data => router({ data, loading: false, origin: 'event' }, 'onMute')), onChannelMemberAdded(data => router({ data, loading: false, origin: 'event' }, 'onMemberAdded')), onChannelMemberRemoved(data => router({ data, loading: false, origin: 'event' }, 'onMemberRemoved')));
25195
25554
  runQuery(createQuery(getChannel, channelId), result => result.data && router(result, 'onFetch'));
25196
25555
  return () => {
25197
25556
  log(`observeChannel(tmpid: ${timestamp}) > dispose`);
@@ -25226,324 +25585,1131 @@ const observeChannels = (callback) => {
25226
25585
  (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, channel);
25227
25586
  (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, channel);
25228
25587
  };
25229
- disposers.push(onChannelCreated(data => router(data, 'onCreate')), onChannelUpdated(data => router(data, 'onUpdate')), onChannelDeleted(data => router(data, 'onDelete')), onChannelJoined(data => router(data, 'onJoin')), onChannelLeft(data => router(data, 'onLeft')), onChannelMemberAdded(data => router(data, 'onMemberAdded')), onChannelMemberRemoved(data => router(data, 'onMemberRemoved')));
25588
+ disposers.push(onChannelCreated(data => router(data, 'onCreate')), onChannelUpdated(data => router(data, 'onUpdate')), onChannelDeleted(data => router(data, 'onDelete')), onChannelJoined(data => router(data, 'onJoin')), onChannelLeft(data => router(data, 'onLeft')), onChannelMuted(data => router(data, 'onMute')), onChannelMemberAdded(data => router(data, 'onMemberAdded')), onChannelMemberRemoved(data => router(data, 'onMemberRemoved')));
25230
25589
  return () => {
25231
25590
  log(`observeChannels(tmpid: ${timestamp}) > dispose`);
25232
25591
  disposers.forEach(fn => fn());
25233
25592
  };
25234
25593
  };
25235
25594
 
25595
+ function hasMention(model, userId) {
25596
+ var _a, _b;
25597
+ const channelMention = (_a = model === null || model === void 0 ? void 0 : model.mentionees) === null || _a === void 0 ? void 0 : _a.find(x => x.type === 'channel');
25598
+ if (channelMention) {
25599
+ return true;
25600
+ }
25601
+ const userMention = (_b = model === null || model === void 0 ? void 0 : model.mentionees) === null || _b === void 0 ? void 0 : _b.find(x => x.type === 'user');
25602
+ if (userMention) {
25603
+ return userMention.userIds.includes(userId);
25604
+ }
25605
+ return false;
25606
+ }
25607
+ function isCollectionOutdated(collection, newItem, action) {
25608
+ const key = identifyModelKey(newItem);
25609
+ // @ts-ignore
25610
+ const item = collection.find(x => x[key] === newItem[key]);
25611
+ if (item) {
25612
+ return hasUpdates(item, newItem);
25613
+ }
25614
+ return action === 'onCreate';
25615
+ }
25616
+ function merge(collection1, collection2) {
25617
+ const temp = [...collection1, ...collection2];
25618
+ if (temp.length === 0) {
25619
+ return [];
25620
+ }
25621
+ const key = identifyModelKey(temp[0]);
25622
+ const map = new Map();
25623
+ // @ts-ignore
25624
+ temp.forEach(x => map.set(x[key], x));
25625
+ return Array.from(map.values());
25626
+ }
25627
+
25236
25628
  /**
25237
25629
  * ```js
25238
- * import { liveChannels } from '@amityco/ts-sdk'
25239
- *
25240
- * let channels = []
25241
- * const unsub = liveChannels({
25242
- * displayName: Amity.Channel['displayName'],
25243
- * }, response => merge(channels, response.data))
25630
+ * import { onMessageCreated } from '@amityco/ts-sdk'
25631
+ * const dispose = onMessageCreated(message => {
25632
+ * // ...
25633
+ * })
25244
25634
  * ```
25245
25635
  *
25246
- * Observe all mutations on a list of {@link Amity.Channel}s
25636
+ * Fired when an {@link Amity.Message} has been created
25247
25637
  *
25248
- * @param params for querying channels
25249
- * @param callback the function to call when new data are available
25250
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channels
25638
+ * @param callback The function to call when the event was fired
25639
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
25251
25640
  *
25252
- * @category Channel Live Collection
25641
+ * @category Message Events
25253
25642
  */
25254
- const liveChannels = (params, callback, config) => {
25255
- const { log, cache, userId } = getActiveClient();
25256
- if (!cache) {
25257
- console.log(ENABLE_CACHE_MESSAGE);
25258
- }
25259
- const timestamp = Date.now();
25260
- log(`liveChannels(tmpid: ${timestamp}) > listen`);
25261
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
25262
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
25263
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
25264
- const disposers = [];
25265
- const cacheKey = ['channel', 'collection', {}];
25266
- const responder = (data) => {
25267
- var _a, _b;
25268
- let channels = (_a = data.data
25269
- .map(channelId => pullFromCache(['channel', 'get', channelId]))
25270
- .filter(Boolean)
25271
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
25272
- channels = filterByPropEquality(channels, 'isDeleted', params.isDeleted);
25273
- channels = filterByPropEquality(channels, 'displayName', params.displayName);
25274
- if (params.types) {
25275
- channels = channels.filter(c => { var _a; return (_a = params.types) === null || _a === void 0 ? void 0 : _a.includes(c.type); });
25276
- }
25277
- if (params.tags) {
25278
- channels = channels.filter(c => { var _a; return (_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = params.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
25279
- }
25280
- if (params.excludeTags) {
25281
- channels = channels.filter(c => { var _a; return !((_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = params.excludeTags) === null || _a === void 0 ? void 0 : _a.includes(t); })); });
25282
- }
25283
- // userId is required to be able to filter channel by current active user
25284
- if (params.membership && userId) {
25285
- channels = filterByChannelMembership(channels, params.membership, userId);
25286
- }
25287
- const sortBy = params.sortBy || 'lastCreated';
25288
- if (sortBy === 'lastCreated' || sortBy === 'firstCreated') {
25289
- channels = channels.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
25290
- }
25291
- /*
25292
- * The server returns channels with empty | null displayName's first before
25293
- * returning sorted list of channels with displayNames
25294
- *
25295
- * This section needs to be updated as displayNames can be null as well
25296
- */
25297
- if (sortBy === 'displayName') {
25298
- channels = channels
25299
- // this needs to be aligned with the backend data type
25300
- .map(c => (c.displayName ? c : Object.assign(Object.assign({}, c), { displayName: '' })))
25301
- // @ts-ignore
25302
- .sort(sortByDisplayName);
25303
- }
25304
- callback({
25305
- onNextPage: onFetch,
25306
- data: channels,
25307
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
25308
- loading: data.loading,
25309
- error: data.error,
25310
- });
25311
- };
25312
- const realtimeRouter = (channel, action) => {
25313
- var _a;
25314
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25315
- if (!collection)
25316
- return;
25317
- if (action === 'onCreate') {
25318
- collection.data = [...new Set([channel.channelId, ...collection.data])];
25319
- /*
25320
- * if the filter isDeleted is set, only collection item must be updated and not
25321
- * the collection
25322
- */
25323
- }
25324
- else if (action === 'onDelete' && !params.isDeleted) {
25325
- collection.data = collection.data.filter(c => c !== channel.channelId);
25326
- }
25327
- pushToCache(cacheKey, collection);
25328
- responder(collection);
25329
- };
25330
- const onFetch = () => {
25331
- var _a, _b, _c;
25332
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25333
- const channels = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
25334
- if (channels.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
25335
- return;
25336
- const query = createQuery(queryChannels, Object.assign(Object.assign({}, queryParams), { page: (_c = collection === null || collection === void 0 ? void 0 : collection.params.page) !== null && _c !== void 0 ? _c : { limit } }));
25337
- runQuery(query, ({ data: result, error, loading, nextPage: page }) => {
25338
- const data = {
25339
- loading,
25340
- error,
25341
- params: { page },
25342
- data: channels,
25343
- };
25344
- if (result) {
25345
- data.data = [...new Set([...channels, ...result.map(getResolver('channel'))])];
25643
+ const onMessageCreated = (callback) => {
25644
+ const client = getActiveClient();
25645
+ const filter = (rawPayload) => {
25646
+ const payload = prepareMessagePayload(rawPayload);
25647
+ const message = payload.messages[0];
25648
+ const cached = pullFromCache(['channel', 'get', message.channelId]);
25649
+ if (cached && cached.data.defaultSubChannelId === message.subChannelId) {
25650
+ let update;
25651
+ // @ts-ignore
25652
+ if (cached.data.localReading) {
25653
+ update = Object.assign(Object.assign({}, cached.data), { localReadToSegment: message.channelSegment, localLastMentionSegment: hasMention(message, client.userId)
25654
+ ? message.channelSegment
25655
+ : cached.data.localLastMentionSegment, messageCount: message.channelSegment, lastActivity: message.createdAt, updatedAt: message.createdAt });
25346
25656
  }
25347
- pushToCache(cacheKey, data);
25348
- responder(data);
25349
- }, queryOptions(policy));
25657
+ else {
25658
+ update = Object.assign(Object.assign({}, cached.data), { defaultSubChannelHasUnreadMention: hasMention(message, client.userId) || cached.data.defaultSubChannelHasUnreadMention, defaultSubChannelUnreadCount: message.channelSegment - cached.data.localReadToSegment, lastActivity: message.createdAt, messageCount: message.channelSegment, updatedAt: message.createdAt });
25659
+ }
25660
+ pushToCache(['channel', 'get', message.channelId], update);
25661
+ client.emitter.emit('local.channel.updated', { channels: [update] });
25662
+ }
25663
+ ingestInCache(payload);
25664
+ callback(message);
25350
25665
  };
25351
- disposers.push(onChannelCreated(channel => realtimeRouter(channel, 'onCreate')), onChannelDeleted(channel => realtimeRouter(channel, 'onDelete')), onChannelUpdated(channel => realtimeRouter(channel, 'onUpdate')));
25352
- onFetch();
25666
+ const disposers = [
25667
+ createEventSubscriber(client, 'message/onMessageCreated', 'message.created', filter),
25668
+ createEventSubscriber(client, 'local.message.created', 'local.message.created', payload => callback(payload.messages[0])),
25669
+ ];
25353
25670
  return () => {
25354
- log(`liveChannels(tmpid: ${timestamp}) > dispose`);
25355
25671
  disposers.forEach(fn => fn());
25356
25672
  };
25357
25673
  };
25358
25674
 
25359
25675
  /**
25360
25676
  * ```js
25361
- * import { liveChannelMembers } from '@amityco/ts-sdk'
25677
+ * import { onMessageUpdated } from '@amityco/ts-sdk'
25678
+ * const dispose = onMessageUpdated(message => {
25679
+ * // ...
25680
+ * })
25681
+ * ```
25362
25682
  *
25363
- * let channelMembers = []
25683
+ * Fired when an {@link Amity.Message} has been updated
25684
+ *
25685
+ * @param callback The function to call when the event was fired
25686
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
25687
+ *
25688
+ * @category Message Events
25689
+ */
25690
+ const onMessageUpdated = (callback) => {
25691
+ const client = getActiveClient();
25692
+ const filter = (rawPayload) => {
25693
+ const payload = prepareMessagePayload(rawPayload);
25694
+ ingestInCache(payload);
25695
+ callback(payload.messages[0]);
25696
+ };
25697
+ const disposers = [
25698
+ createEventSubscriber(client, 'message/onMessageUpdated', 'message.updated', filter),
25699
+ createEventSubscriber(client, 'local.message.updated', 'local.message.updated', payload => callback(payload.messages[0])),
25700
+ ];
25701
+ return () => {
25702
+ disposers.forEach(fn => fn());
25703
+ };
25704
+ };
25705
+
25706
+ /**
25707
+ * ```js
25708
+ * import { onMessageDeleted } from '@amityco/ts-sdk'
25709
+ * const dispose = onMessageDeleted(message => {
25710
+ * // ...
25711
+ * })
25712
+ * ```
25713
+ *
25714
+ * Fired when an {@link Amity.Message} was deleted
25715
+ *
25716
+ * @param callback The function to call when the event was fired
25717
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
25718
+ *
25719
+ * @category Message Events
25720
+ */
25721
+ const onMessageDeleted = (callback) => {
25722
+ const client = getActiveClient();
25723
+ const filter = (rawPayload) => {
25724
+ const payload = prepareMessagePayload(rawPayload);
25725
+ ingestInCache(payload);
25726
+ callback(payload.messages[0]);
25727
+ };
25728
+ const disposers = [
25729
+ createEventSubscriber(client, 'message/onMessageDeleted', 'message.deleted', filter),
25730
+ createEventSubscriber(client, 'local.message.deleted', 'local.message.deleted', payload => callback(payload.messages[0])),
25731
+ ];
25732
+ return () => {
25733
+ disposers.forEach(fn => fn());
25734
+ };
25735
+ };
25736
+
25737
+ /**
25738
+ * ```js
25739
+ * import { onMessageFlagged } from '@amityco/ts-sdk'
25740
+ * const dispose = onMessageFlagged(message => {
25741
+ * // ...
25742
+ * })
25743
+ * ```
25744
+ *
25745
+ * Fired when a {@link Amity.Message} has been flagged
25746
+ *
25747
+ * @param callback The function to call when the event was fired
25748
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
25749
+ *
25750
+ * @category Message Events
25751
+ */
25752
+ const onMessageFlagged = (callback) => {
25753
+ const client = getActiveClient();
25754
+ const filter = (rawPayload) => {
25755
+ const payload = prepareMessagePayload(rawPayload);
25756
+ ingestInCache(payload);
25757
+ callback(payload.messages[0]);
25758
+ };
25759
+ return createEventSubscriber(client, 'onMessageFlagged', 'message.flagged', filter);
25760
+ };
25761
+
25762
+ /**
25763
+ * ```js
25764
+ * import { onMessageUnflagged } from '@amityco/ts-sdk'
25765
+ * const dispose = onMessageUnflagged(message => {
25766
+ * // ...
25767
+ * })
25768
+ * ```
25769
+ *
25770
+ * Fired when a flag has been removed from a {@link Amity.Message}
25771
+ *
25772
+ * @param callback The function to call when the event was fired
25773
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
25774
+ *
25775
+ * @category Message Events
25776
+ */
25777
+ const onMessageUnflagged = (callback) => {
25778
+ const client = getActiveClient();
25779
+ const filter = (rawPayload) => {
25780
+ const payload = prepareMessagePayload(rawPayload);
25781
+ ingestInCache(payload);
25782
+ callback(payload.messages[0]);
25783
+ };
25784
+ return createEventSubscriber(client, 'onMessageUnflagged', 'message.unflagged', filter);
25785
+ };
25786
+
25787
+ /**
25788
+ * ```js
25789
+ * import { onMessageFlagCleared } from '@amityco/ts-sdk'
25790
+ * const dispose = onMessageFlagCleared(message => {
25791
+ * // ...
25792
+ * })
25793
+ * ```
25794
+ *
25795
+ * Fired when flags have been cleared for a {@link Amity.Message}
25796
+ *
25797
+ * @param callback The function to call when the event was fired
25798
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
25799
+ *
25800
+ * @category Message Events
25801
+ */
25802
+ const onMessageFlagCleared = (callback) => {
25803
+ const client = getActiveClient();
25804
+ const filter = (rawPayload) => {
25805
+ const payload = prepareMessagePayload(rawPayload);
25806
+ ingestInCache(payload);
25807
+ callback(payload.messages[0]);
25808
+ };
25809
+ return createEventSubscriber(client, 'onMessageFlagCleared', 'message.flagCleared', filter);
25810
+ };
25811
+
25812
+ /**
25813
+ * ```js
25814
+ * import { onMessageReactionAdded } from '@amityco/ts-sdk';
25815
+ *
25816
+ * const unsubscribe = onMessageReactionAdded(message => {
25817
+ * // ...
25818
+ * });
25819
+ * ```
25820
+ *
25821
+ * Fired when a {@link Amity.Message} has been reacted
25822
+ *
25823
+ * @param callback The function to call when the event was fired
25824
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
25825
+ *
25826
+ * @category Post Events
25827
+ */
25828
+ const onMessageReactionAdded = (callback) => {
25829
+ const client = getActiveClient();
25830
+ const filter = (rawPayload) => {
25831
+ const payload = prepareMessagePayload(rawPayload);
25832
+ ingestInCache(payload);
25833
+ callback(payload.messages[0]);
25834
+ };
25835
+ return createEventSubscriber(client, 'onMessageReactionAdded', 'message.reactionAdded', filter);
25836
+ };
25837
+
25838
+ /**
25839
+ * ```js
25840
+ * import { onMessageReactionRemoved } from '@amityco/ts-sdk';
25841
+ *
25842
+ * const unsubscribe = onMessageReactionRemoved(message => {
25843
+ * // ...
25844
+ * });
25845
+ * ```
25846
+ *
25847
+ * Fired when a reaction has been removed from a {@link Amity.Message}
25848
+ *
25849
+ * @param callback The function to call when the event was fired
25850
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
25851
+ *
25852
+ * @category Post Events
25853
+ */
25854
+ const onMessageReactionRemoved = (callback) => {
25855
+ const client = getActiveClient();
25856
+ const filter = (rawPayload) => {
25857
+ const payload = prepareMessagePayload(rawPayload);
25858
+ ingestInCache(payload);
25859
+ callback(payload.messages[0]);
25860
+ };
25861
+ return createEventSubscriber(client, 'onMessageReactionRemoved', 'message.reactionRemoved', filter);
25862
+ };
25863
+
25864
+ /**
25865
+ * ```js
25866
+ * import { liveChannel } from '@amityco/ts-sdk';
25867
+ *
25868
+ * let channel;
25869
+ *
25870
+ * const unsubscribe = liveChannel(channelId, response => {
25871
+ * channel = response.data;
25872
+ * });
25873
+ * ```
25874
+ *
25875
+ * Observe all mutation on a given {@link Amity.Channel}
25876
+ *
25877
+ * @param channelId the ID of the channel to observe
25878
+ * @param callback the function to call when new data are available
25879
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channel
25880
+ *
25881
+ * @category Message Live Object
25882
+ */
25883
+ const liveChannel = (channelId, callback) => {
25884
+ const { log, cache } = getActiveClient();
25885
+ const timestamp = Date.now();
25886
+ log(`liveChannel(tmpid: ${timestamp}) > listen`);
25887
+ if (!cache) {
25888
+ console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
25889
+ }
25890
+ let channel;
25891
+ let isUnsyncedObject = false;
25892
+ const disposers = [];
25893
+ const dispatcher = (data) => {
25894
+ channel = data.data;
25895
+ callback(data);
25896
+ };
25897
+ const realtimeRouter = (eventChannel) => {
25898
+ if (channelId !== eventChannel.channelId) {
25899
+ return;
25900
+ }
25901
+ if (channel && !hasUpdates(channel, eventChannel)) {
25902
+ return;
25903
+ }
25904
+ dispatcher({ loading: false, data: eventChannel, origin: 'event' });
25905
+ };
25906
+ const onFetch = () => {
25907
+ const query = createQuery(getChannel, channelId);
25908
+ runQuery(query, ({ loading, data, error, origin, cachedAt }) => {
25909
+ if (cachedAt === UNSYNCED_OBJECT_CACHED_AT_VALUE) {
25910
+ dispatcher({
25911
+ data,
25912
+ origin,
25913
+ loading: false,
25914
+ error: new ASCApiError(UNSYNCED_OBJECT_CACHED_AT_MESSAGE, 800800 /* Amity.ClientError.DISALOOW_UNSYNCED_OBJECT */, "error" /* Amity.ErrorLevel.ERROR */),
25915
+ });
25916
+ isUnsyncedObject = true;
25917
+ disposers.forEach(fn => fn());
25918
+ }
25919
+ else if (!isUnsyncedObject) {
25920
+ dispatcher({ loading, data, origin, error });
25921
+ }
25922
+ if (error) {
25923
+ disposers.forEach(fn => fn());
25924
+ }
25925
+ });
25926
+ };
25927
+ disposers.push(onChannelUpdated(realtimeRouter), onChannelDeleted(realtimeRouter), onChannelJoined(realtimeRouter), onChannelMuted(realtimeRouter), onMessageCreated(() => null));
25928
+ onFetch();
25929
+ return () => {
25930
+ log(`liveChannel(tmpid: ${timestamp}) > dispose`);
25931
+ disposers.forEach(fn => fn());
25932
+ };
25933
+ };
25934
+
25935
+ /**
25936
+ * ```js
25937
+ * import { liveChannels } from '@amityco/ts-sdk'
25938
+ *
25939
+ * let channels = []
25940
+ * const unsub = liveChannels({
25941
+ * displayName: Amity.Channel['displayName'],
25942
+ * }, response => merge(channels, response.data))
25943
+ * ```
25944
+ *
25945
+ * Observe all mutations on a list of {@link Amity.Channel}s
25946
+ *
25947
+ * @param params for querying channels
25948
+ * @param callback the function to call when new data are available
25949
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channels
25950
+ *
25951
+ * @category Channel Live Collection
25952
+ */
25953
+ const liveChannels = (params, callback, config) => {
25954
+ const { log, cache, userId } = getActiveClient();
25955
+ if (!cache) {
25956
+ console.log(ENABLE_CACHE_MESSAGE);
25957
+ }
25958
+ const timestamp = Date.now();
25959
+ log(`liveChannels(tmpid: ${timestamp}) > listen`);
25960
+ const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
25961
+ const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
25962
+ const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
25963
+ const disposers = [];
25964
+ const cacheKey = ['channel', 'collection', {}];
25965
+ const responder = (data) => {
25966
+ var _a, _b;
25967
+ let channels = (_a = data.data
25968
+ .map(channelId => pullFromCache(['channel', 'get', channelId]))
25969
+ .filter(Boolean)
25970
+ .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
25971
+ channels = filterByPropEquality(channels, 'isDeleted', params.isDeleted);
25972
+ channels = filterByPropEquality(channels, 'displayName', params.displayName);
25973
+ if (params.types) {
25974
+ channels = channels.filter(c => { var _a; return (_a = params.types) === null || _a === void 0 ? void 0 : _a.includes(c.type); });
25975
+ }
25976
+ if (params.tags) {
25977
+ channels = channels.filter(c => { var _a; return (_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = params.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
25978
+ }
25979
+ if (params.excludeTags) {
25980
+ channels = channels.filter(c => { var _a; return !((_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = params.excludeTags) === null || _a === void 0 ? void 0 : _a.includes(t); })); });
25981
+ }
25982
+ // userId is required to be able to filter channel by current active user
25983
+ if (params.membership && userId) {
25984
+ channels = filterByChannelMembership(channels, params.membership, userId);
25985
+ }
25986
+ const sortBy = params.sortBy || 'lastCreated';
25987
+ if (sortBy === 'lastCreated' || sortBy === 'firstCreated') {
25988
+ channels = channels.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
25989
+ }
25990
+ /*
25991
+ * The server returns channels with empty | null displayName's first before
25992
+ * returning sorted list of channels with displayNames
25993
+ *
25994
+ * This section needs to be updated as displayNames can be null as well
25995
+ */
25996
+ if (sortBy === 'displayName') {
25997
+ channels = channels
25998
+ // this needs to be aligned with the backend data type
25999
+ .map(c => (c.displayName ? c : Object.assign(Object.assign({}, c), { displayName: '' })))
26000
+ // @ts-ignore
26001
+ .sort(sortByDisplayName);
26002
+ }
26003
+ callback({
26004
+ onNextPage: onFetch,
26005
+ data: channels,
26006
+ hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
26007
+ loading: data.loading,
26008
+ error: data.error,
26009
+ });
26010
+ };
26011
+ const realtimeRouter = (action) => (channel) => {
26012
+ var _a;
26013
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26014
+ if (!collection)
26015
+ return;
26016
+ if (action === 'onDelete' && params.isDeleted === false) {
26017
+ collection.data = collection.data.filter(c => c !== channel.channelId);
26018
+ }
26019
+ else {
26020
+ collection.data = [...new Set([channel.channelId, ...collection.data])];
26021
+ }
26022
+ pushToCache(cacheKey, collection);
26023
+ responder(collection);
26024
+ };
26025
+ const onFetch = () => {
26026
+ var _a, _b, _c;
26027
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26028
+ const channels = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
26029
+ if (channels.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
26030
+ return;
26031
+ const query = createQuery(queryChannels, Object.assign(Object.assign({}, queryParams), { page: (_c = collection === null || collection === void 0 ? void 0 : collection.params.page) !== null && _c !== void 0 ? _c : { limit } }));
26032
+ runQuery(query, ({ data: result, error, loading, nextPage: page }) => {
26033
+ const data = {
26034
+ loading,
26035
+ error,
26036
+ params: { page },
26037
+ data: channels,
26038
+ };
26039
+ if (result) {
26040
+ data.data = [...new Set([...channels, ...result.map(getResolver('channel'))])];
26041
+ }
26042
+ pushToCache(cacheKey, data);
26043
+ responder(data);
26044
+ }, queryOptions(policy));
26045
+ };
26046
+ disposers.push(onChannelCreated(realtimeRouter('onCreate')), onChannelDeleted(realtimeRouter('onDelete')), onChannelUpdated(realtimeRouter('onUpdate')), onChannelMuted(realtimeRouter('onMute')), onChannelJoined(realtimeRouter('onJoin')), onChannelLeft(realtimeRouter('onLeft')), onChannelMemberAdded(realtimeRouter('onMemberAdded')), onChannelMemberRemoved(realtimeRouter('onMemberRemoved')), onMessageCreated(() => null));
26047
+ onFetch();
26048
+ return () => {
26049
+ log(`liveChannels(tmpid: ${timestamp}) > dispose`);
26050
+ disposers.forEach(fn => fn());
26051
+ };
26052
+ };
26053
+
26054
+ /**
26055
+ * ```js
26056
+ * import { liveChannelMembers } from '@amityco/ts-sdk'
26057
+ *
26058
+ * let channelMembers = []
25364
26059
  * const unsub = liveChannelMembers({
25365
26060
  * channelId: Amity.Channel['channelId'],
25366
26061
  * }, response => merge(channelMembers, response.data))
25367
26062
  * ```
25368
26063
  *
25369
- * Observe all mutations on a list of {@link Amity.ChannelUser}s
26064
+ * Observe all mutations on a list of {@link Amity.ChannelUser}s
26065
+ *
26066
+ * @param params for querying channel users
26067
+ * @param callback the function to call when new data are available
26068
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channel users
26069
+ *
26070
+ * @category Channel Live Collection
26071
+ */
26072
+ const liveChannelMembers = (params, callback, config) => {
26073
+ const { log, cache } = getActiveClient();
26074
+ if (!cache) {
26075
+ console.log(ENABLE_CACHE_MESSAGE);
26076
+ }
26077
+ const timestamp = Date.now();
26078
+ log(`liveChannelMembers(tmpid: ${timestamp}) > listen`);
26079
+ const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
26080
+ const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
26081
+ const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
26082
+ const disposers = [];
26083
+ const cacheKey = ['channelUsers', 'collection', { channelId: params.channelId }];
26084
+ const responder = (data) => {
26085
+ var _a, _b;
26086
+ let channelMembers = (_a = data.data
26087
+ .map(id => pullFromCache(['channelUsers', 'get', id]))
26088
+ .filter(Boolean)
26089
+ .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
26090
+ channelMembers = filterByPropEquality(channelMembers, 'roles', params.roles);
26091
+ if (params.memberships) {
26092
+ /*
26093
+ * even though membership includes muted as a possible value
26094
+ * when querying the server.
26095
+ * Muted is specified under seperarte property namely isMuted
26096
+ * Hence why I've seperately checked for it's equality
26097
+ */
26098
+ channelMembers = channelMembers.filter(member => {
26099
+ // @ts-ignore
26100
+ if (params.memberships.includes('muted') && member.isMuted) {
26101
+ return true;
26102
+ }
26103
+ // @ts-ignore
26104
+ return params.memberships.includes(member.membership);
26105
+ });
26106
+ }
26107
+ if (params.search) {
26108
+ const containsMatcher = new RegExp(params.search);
26109
+ channelMembers = channelMembers.filter(m => m.userId.match(containsMatcher));
26110
+ }
26111
+ // sort, 'lastCreated' is the default sort order
26112
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
26113
+ channelMembers = channelMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
26114
+ callback({
26115
+ onNextPage: onFetch,
26116
+ data: channelMembers,
26117
+ hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
26118
+ loading: data.loading,
26119
+ error: data.error,
26120
+ });
26121
+ };
26122
+ const realtimeRouter = (action) => (channel, channelMember) => {
26123
+ var _a;
26124
+ if (params.channelId !== channelMember.channelId) {
26125
+ return;
26126
+ }
26127
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26128
+ if (!collection)
26129
+ return;
26130
+ const channelMemberCacheId = getResolver('channelUsers')({
26131
+ channelId: params.channelId,
26132
+ userId: channelMember.userId,
26133
+ });
26134
+ if (channelMember.membership === 'none') {
26135
+ collection.data = collection.data.filter(m => m !== channelMemberCacheId);
26136
+ }
26137
+ else if (!collection.data.includes(channelMemberCacheId)) {
26138
+ collection.data = [channelMemberCacheId, ...collection.data];
26139
+ }
26140
+ pushToCache(cacheKey, collection);
26141
+ responder(collection);
26142
+ };
26143
+ const onFetch = () => {
26144
+ var _a, _b, _c;
26145
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26146
+ const channelMembers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
26147
+ if (channelMembers.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
26148
+ return;
26149
+ const query = createQuery(queryChannelMembers, Object.assign(Object.assign({}, queryParams), { page: (_c = collection === null || collection === void 0 ? void 0 : collection.params.page) !== null && _c !== void 0 ? _c : { limit } }));
26150
+ runQuery(query, ({ data: result, error, loading, nextPage: page }) => {
26151
+ const data = {
26152
+ loading,
26153
+ error,
26154
+ params: { page },
26155
+ data: channelMembers,
26156
+ };
26157
+ if (result) {
26158
+ data.data = [...new Set([...channelMembers, ...result.map(getResolver('channelUsers'))])];
26159
+ }
26160
+ pushToCache(cacheKey, data);
26161
+ responder(data);
26162
+ }, queryOptions(policy));
26163
+ };
26164
+ disposers.push(onChannelJoined(realtimeRouter()), onChannelLeft(realtimeRouter()), onChannelMemberAdded(realtimeRouter()), onChannelMemberRemoved(realtimeRouter()), onChannelMemberBanned(realtimeRouter()), onChannelMemberUnbanned(realtimeRouter()));
26165
+ onFetch();
26166
+ return () => {
26167
+ log(`liveChannelMembers(tmpid: ${timestamp}) > dispose`);
26168
+ disposers.forEach(fn => fn());
26169
+ };
26170
+ };
26171
+
26172
+ function convertFromRaw(_a) {
26173
+ 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"]);
26174
+ return Object.assign(Object.assign({}, rest), { channelId: channelPublicId, creatorId: creatorPublicId, displayName: name, lastActivity: lastMessageTimestamp, latestMessageId: lastMessageId, messageCount: childCount, subChannelId: messageFeedId });
26175
+ }
26176
+ const prepareSubChannelPayload = (payload) => {
26177
+ return Object.assign(Object.assign({}, payload), { messageFeeds: payload.messageFeeds.map(convertFromRaw) });
26178
+ };
26179
+ function convertQueryParams(_a) {
26180
+ var { excludeDefaultSubChannel } = _a, rest = __rest(_a, ["excludeDefaultSubChannel"]);
26181
+ const out = Object.assign({}, rest);
26182
+ if (excludeDefaultSubChannel !== undefined) {
26183
+ out.excludeDefaultMessageFeed = excludeDefaultSubChannel;
26184
+ }
26185
+ return out;
26186
+ }
26187
+
26188
+ /**
26189
+ * ```js
26190
+ * import { querySubChannels } from '@amityco/ts-sdk'
26191
+ * const subChannels = await querySubChannels({ channelId: 'channelId' })
26192
+ * ```
26193
+ *
26194
+ * Queries a paginable list of {@link Amity.SubChannel} objects
26195
+ *
26196
+ * @param query The query parameters
26197
+ * @returns A page of {@link Amity.SubChannel} objects
26198
+ *
26199
+ * @category Channel API
26200
+ * @async
26201
+ */
26202
+ const querySubChannels = async (query) => {
26203
+ const client = getActiveClient();
26204
+ client.log('channel/querySubChannels', query);
26205
+ const _a = convertQueryParams(query), { page = { limit: 10 }, channelId } = _a, params = __rest(_a, ["page", "channelId"]);
26206
+ const response = await client.http.get(`/api/v5/message-feeds/channel/${channelId}`, {
26207
+ params: Object.assign(Object.assign({}, params), { options: {
26208
+ token: toToken(page, 'skiplimit'),
26209
+ } }),
26210
+ });
26211
+ const _b = response.data, { paging } = _b, payload = __rest(_b, ["paging"]);
26212
+ const data = prepareSubChannelPayload(payload);
26213
+ const subChannels = data.messageFeeds;
26214
+ const cachedAt = client.cache && Date.now();
26215
+ if (client.cache) {
26216
+ ingestInCache(data, { cachedAt });
26217
+ const cacheKey = [
26218
+ 'subChannel',
26219
+ 'query',
26220
+ Object.assign(Object.assign({ channelId }, params), { options: Object.assign({}, page) }),
26221
+ ];
26222
+ pushToCache(cacheKey, { subChannels: subChannels.map(getResolver('subChannel')), paging });
26223
+ }
26224
+ fireEvent('local.message-feed.fetched', data);
26225
+ const nextPage = toPage(paging.next);
26226
+ const prevPage = toPage(paging.previous);
26227
+ return { data: subChannels, cachedAt, prevPage, nextPage };
26228
+ };
26229
+ /**
26230
+ * ```js
26231
+ * import { querySubChannels } from '@amityco/ts-sdk'
26232
+ * const subChannels = querySubChannels.locally({ channelId: 'channelId' })
26233
+ * ```
26234
+ *
26235
+ * Queries a paginable list of {@link Amity.SubChannel} objects from cache
26236
+ *
26237
+ * @param query The query parameters
26238
+ * @returns sub channels
26239
+ *
26240
+ * @category Channel API
26241
+ */
26242
+ querySubChannels.locally = (query) => {
26243
+ var _a, _b, _c;
26244
+ const client = getActiveClient();
26245
+ client.log('channel/querySubChannels.locally', query);
26246
+ // @ts-ignore
26247
+ const _d = (_a = convertQueryParams(query)) !== null && _a !== void 0 ? _a : {}, { page = { limit: 10 }, channelId } = _d, params = __rest(_d, ["page", "channelId"]);
26248
+ const cacheKey = [
26249
+ 'subChannel',
26250
+ 'query',
26251
+ Object.assign(Object.assign({ channelId }, params), { options: Object.assign({}, page) }),
26252
+ ];
26253
+ const { data, cachedAt } = (_b = pullFromCache(cacheKey)) !== null && _b !== void 0 ? _b : {};
26254
+ if (!(data === null || data === void 0 ? void 0 : data.subChannels.length))
26255
+ return;
26256
+ const subChannels = data.subChannels
26257
+ .map(ck => pullFromCache(['subChannel', 'get', ck]))
26258
+ .filter(Boolean)
26259
+ .map(({ data }) => data);
26260
+ const prevPage = toPage(data === null || data === void 0 ? void 0 : data.paging.previous);
26261
+ const nextPage = toPage(data === null || data === void 0 ? void 0 : data.paging.next);
26262
+ return subChannels.length === ((_c = data === null || data === void 0 ? void 0 : data.subChannels) === null || _c === void 0 ? void 0 : _c.length)
26263
+ ? { data: subChannels, cachedAt, prevPage, nextPage }
26264
+ : undefined;
26265
+ };
26266
+
26267
+ /**
26268
+ * ```js
26269
+ * import { getSubChannels } from '@amityco/ts-sdk'
26270
+ * const subChannels = await getSubChannels(['foo', 'bar'])
26271
+ * ```
26272
+ *
26273
+ * Fetches a collection of {@link Amity.SubChannel} objects
26274
+ *
26275
+ * @param subChannelIds the IDs of the {@link Amity.SubChannel} to fetch
26276
+ * @returns the associated collection of {@link Amity.SubChannel} objects
26277
+ *
26278
+ * @category Channel API
26279
+ * @async
26280
+ */
26281
+ const getSubChannels = async (subChannelIds) => {
26282
+ const client = getActiveClient();
26283
+ client.log('channel/getSubChannels', subChannelIds);
26284
+ const response = await client.http.get('/api/v5/message-feeds/list', {
26285
+ params: { messageFeedIds: subChannelIds.map(encodeURIComponent) },
26286
+ });
26287
+ const data = prepareSubChannelPayload(response.data);
26288
+ const cachedAt = client.cache && Date.now();
26289
+ if (client.cache)
26290
+ ingestInCache(data, { cachedAt });
26291
+ fireEvent('local.message-feed.fetched', data);
26292
+ return {
26293
+ data: data.messageFeeds,
26294
+ cachedAt,
26295
+ };
26296
+ };
26297
+ /**
26298
+ * ```js
26299
+ * import { getSubChannels } from '@amityco/ts-sdk'
26300
+ * const subChannels = getSubChannels.locally(['foo', 'bar']) ?? []
26301
+ * ```
26302
+ *
26303
+ * Fetches a collection of {@link Amity.SubChannel} objects from cache
26304
+ *
26305
+ * @param subChannelIds the IDs of the {@link Amity.SubChannel} to fetch
26306
+ * @returns the associated collection of {@link Amity.SubChannel} objects
26307
+ *
26308
+ * @category Channel API
26309
+ */
26310
+ getSubChannels.locally = (subChannelIds) => {
26311
+ var _a;
26312
+ const client = getActiveClient();
26313
+ client.log('channel/getSubChannels.locally', subChannelIds);
26314
+ if (!client.cache)
26315
+ return;
26316
+ const cached = subChannelIds
26317
+ .map(channelId => pullFromCache(['subChannel', 'get', channelId]))
26318
+ .filter(Boolean);
26319
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) < subChannelIds.length)
26320
+ return;
26321
+ const subChannels = cached.map(({ data }) => data);
26322
+ const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
26323
+ return {
26324
+ data: subChannels,
26325
+ cachedAt: oldest.cachedAt,
26326
+ };
26327
+ };
26328
+
26329
+ /**
26330
+ * ```js
26331
+ * import { getSubChannel } from '@amityco/ts-sdk'
26332
+ * const subChannel = await getSubChannel('foobar')
26333
+ * ```
26334
+ *
26335
+ * Fetches a {@link Amity.SubChannel} object
26336
+ *
26337
+ * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
26338
+ * @returns the associated {@link Amity.SubChannel} object
26339
+ *
26340
+ * @category Channel API
26341
+ * @async
26342
+ */
26343
+ const getSubChannel = async (subChannelId) => {
26344
+ const client = getActiveClient();
26345
+ client.log('channel/getSubChannel', subChannelId);
26346
+ isInTombstone('subChannel', subChannelId);
26347
+ try {
26348
+ const response = await client.http.get(`/api/v5/message-feeds/${encodeURIComponent(subChannelId)}`);
26349
+ const data = prepareSubChannelPayload(response.data);
26350
+ const cachedAt = client.cache && Date.now();
26351
+ if (client.cache)
26352
+ ingestInCache(data, { cachedAt });
26353
+ fireEvent('local.message-feed.fetched', data);
26354
+ return {
26355
+ data: data.messageFeeds[0],
26356
+ cachedAt,
26357
+ };
26358
+ }
26359
+ catch (error) {
26360
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
26361
+ pushToTombstone('subChannel', subChannelId);
26362
+ }
26363
+ throw error;
26364
+ }
26365
+ };
26366
+ /**
26367
+ * ```js
26368
+ * import { getSubChannel } from '@amityco/ts-sdk'
26369
+ * const subChannel = getSubChannel.locally('foobar')
26370
+ * ```
26371
+ *
26372
+ * Fetches a {@link Amity.SubChannel} object from cache
26373
+ *
26374
+ * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
26375
+ * @returns the associated {@link Amity.SubChannel} object
26376
+ *
26377
+ * @category Channel API
26378
+ */
26379
+ getSubChannel.locally = (subChannelId) => {
26380
+ const client = getActiveClient();
26381
+ client.log('channel/getSubChannel.locally', subChannelId);
26382
+ if (!client.cache)
26383
+ return;
26384
+ const cached = pullFromCache(['subChannel', 'get', subChannelId]);
26385
+ if (!cached)
26386
+ return;
26387
+ return {
26388
+ data: cached.data,
26389
+ cachedAt: cached.cachedAt,
26390
+ };
26391
+ };
26392
+
26393
+ /**
26394
+ * ```js
26395
+ * import { createSubChannel } from '@amityco/ts-sdk'
26396
+ * const created = await createSubChannel({ channelId: 'foobar', name: 'foobar' })
26397
+ * ```
26398
+ *
26399
+ * Creates an {@link Amity.SubChannel}
26400
+ *
26401
+ * @param bundle The data necessary to create a new {@link Amity.SubChannel}
26402
+ * @returns The newly created {@link Amity.SubChannel}
26403
+ *
26404
+ * @category Channel API
26405
+ * @async
26406
+ */
26407
+ const createSubChannel = async (bundle) => {
26408
+ const client = getActiveClient();
26409
+ client.log('user/createSubChannel', bundle);
26410
+ const response = await client.http.post('/api/v5/message-feeds', {
26411
+ channelId: bundle.channelId,
26412
+ name: bundle.displayName,
26413
+ });
26414
+ const data = prepareSubChannelPayload(response.data);
26415
+ const cachedAt = client.cache && Date.now();
26416
+ if (client.cache)
26417
+ ingestInCache(data, { cachedAt });
26418
+ fireEvent('message-feed.created', response.data);
26419
+ return {
26420
+ data: data.messageFeeds[0],
26421
+ cachedAt,
26422
+ };
26423
+ };
26424
+
26425
+ /**
26426
+ * ```js
26427
+ * import { updateSubChannel } from '@amityco/ts-sdk'
26428
+ * const updated = await updateSubChannel(subChannelId, { name: 'foobar' })
26429
+ * ```
26430
+ *
26431
+ * Updates an {@link Amity.SubChannel}
26432
+ *
26433
+ * @param subChannelId The ID of the {@link Amity.SubChannel} to edit
26434
+ * @param patch The patch data to apply
26435
+ * @returns the updated {@link Amity.SubChannel} object
26436
+ *
26437
+ * @category Channel API
26438
+ * @async
26439
+ */
26440
+ const updateSubChannel = async (subChannelId, patch) => {
26441
+ const client = getActiveClient();
26442
+ client.log('channel/updateSubChannel', subChannelId, patch);
26443
+ const response = await client.http.put(`/api/v5/message-feeds/${encodeURIComponent(subChannelId)}`, { name: patch.displayName });
26444
+ const data = prepareSubChannelPayload(response.data);
26445
+ const cachedAt = client.cache && Date.now();
26446
+ if (client.cache)
26447
+ ingestInCache(data, { cachedAt });
26448
+ fireEvent('message-feed.updated', response.data);
26449
+ return {
26450
+ data: data.messageFeeds[0],
26451
+ cachedAt,
26452
+ };
26453
+ };
26454
+
26455
+ /**
26456
+ * ```js
26457
+ * import { deleteSubChannel } from '@amityco/ts-sdk'
26458
+ * const success = await deleteSubChannel('foobar')
26459
+ * ```
26460
+ *
26461
+ * Deletes a {@link Amity.SubChannel}
25370
26462
  *
25371
- * @param params for querying channel users
25372
- * @param callback the function to call when new data are available
25373
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channel users
26463
+ * @param subChannelId The {@link Amity.SubChannel} ID to delete
26464
+ * @return A success boolean if the {@link Amity.SubChannel} was deleted
25374
26465
  *
25375
- * @category Channel Live Collection
26466
+ * @category Channel API
26467
+ * @async
25376
26468
  */
25377
- const liveChannelMembers = (params, callback, config) => {
25378
- const { log, cache } = getActiveClient();
25379
- if (!cache) {
25380
- console.log(ENABLE_CACHE_MESSAGE);
26469
+ const deleteSubChannel = async (subChannelId, permanent = false) => {
26470
+ const client = getActiveClient();
26471
+ client.log('channel/deleteSubChannel', subChannelId);
26472
+ const subChannel = await getSubChannel(subChannelId);
26473
+ await client.http.delete(`/api/v5/message-feeds/${encodeURIComponent(subChannelId)}`, { params: { permanent } });
26474
+ const deleted = Object.assign(Object.assign({}, subChannel.data), { isDeleted: true, updatedAt: getFutureDate(subChannel.data.updatedAt) });
26475
+ if (permanent) {
26476
+ setTimeout(() => {
26477
+ pushToTombstone('subChannel', subChannelId);
26478
+ }, 0);
25381
26479
  }
25382
- const timestamp = Date.now();
25383
- log(`liveChannelMembers(tmpid: ${timestamp}) > listen`);
25384
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
25385
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
25386
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
25387
- const disposers = [];
25388
- const cacheKey = ['channelUsers', 'collection', { channelId: params.channelId }];
25389
- const responder = (data) => {
25390
- var _a, _b;
25391
- let channelMembers = (_a = data.data
25392
- .map(id => pullFromCache(['channelUsers', 'get', id]))
25393
- .filter(Boolean)
25394
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
25395
- channelMembers = filterByPropEquality(channelMembers, 'roles', params.roles);
25396
- if (params.memberships) {
25397
- /*
25398
- * even though membership includes muted as a possible value
25399
- * when querying the server.
25400
- * Muted is specified under seperarte property namely isMuted
25401
- * Hence why I've seperately checked for it's equality
25402
- */
25403
- if (params.memberships.some(m => ['member', 'banned'].includes(m))) {
25404
- channelMembers = filterByPropInclusion(channelMembers, 'membership', params.memberships);
25405
- }
25406
- if (params.memberships.includes('muted')) {
25407
- channelMembers = filterByPropEquality(channelMembers, 'isMuted', true);
25408
- }
25409
- }
25410
- if (params.search) {
25411
- const containsMatcher = new RegExp(params.search);
25412
- channelMembers = channelMembers.filter(m => m.userId.match(containsMatcher));
25413
- }
25414
- // sort, 'lastCreated' is the default sort order
25415
- const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
25416
- channelMembers = channelMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
25417
- callback({
25418
- onNextPage: onFetch,
25419
- data: channelMembers,
25420
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
25421
- loading: data.loading,
25422
- error: data.error,
25423
- });
25424
- };
25425
- const realtimeRouter = (channelMember, action) => {
25426
- var _a;
25427
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25428
- if (!collection)
25429
- return;
25430
- const channelMemberCacheId = getResolver('channelUsers')({
25431
- channelId: params.channelId,
25432
- userId: channelMember.userId,
25433
- });
25434
- if (action === 'onMemberAdded') {
25435
- collection.data = [...new Set([channelMemberCacheId, ...collection.data])];
25436
- }
25437
- if (action === 'onMemberRemoved') {
25438
- collection.data = collection.data.filter(m => m !== channelMemberCacheId);
25439
- }
25440
- pushToCache(cacheKey, collection);
25441
- responder(collection);
25442
- };
25443
- const onFetch = () => {
25444
- var _a, _b, _c;
25445
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25446
- const channelMembers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
25447
- if (channelMembers.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
25448
- return;
25449
- const query = createQuery(queryChannelMembers, Object.assign(Object.assign({}, queryParams), { page: (_c = collection === null || collection === void 0 ? void 0 : collection.params.page) !== null && _c !== void 0 ? _c : { limit } }));
25450
- runQuery(query, ({ data: result, error, loading, nextPage: page }) => {
25451
- const data = {
25452
- loading,
25453
- error,
25454
- params: { page },
25455
- data: channelMembers,
25456
- };
25457
- if (result) {
25458
- data.data = [...new Set([...channelMembers, ...result.map(getResolver('channelUsers'))])];
25459
- }
25460
- pushToCache(cacheKey, data);
25461
- responder(data);
25462
- }, queryOptions(policy));
25463
- };
25464
- disposers.push(onChannelMemberAdded((_, member) => realtimeRouter(member, 'onMemberAdded')), onChannelMemberRemoved((_, member) => realtimeRouter(member, 'onMemberRemoved')), onChannelMemberBanned((_, member) => realtimeRouter(member, 'onChannelMemberBanned')), onChannelMemberUnbanned((_, member) => realtimeRouter(member, 'onChannelMemberUnbanned')));
25465
- onFetch();
25466
- return () => {
25467
- log(`liveChannelMembers(tmpid: ${timestamp}) > dispose`);
25468
- disposers.forEach(fn => fn());
25469
- };
26480
+ else {
26481
+ upsertInCache(['subChannel', 'get', subChannelId], deleted);
26482
+ }
26483
+ fireEvent('local.message-feed.deleted', { messageFeeds: [deleted] });
26484
+ return deleted;
25470
26485
  };
25471
26486
 
25472
26487
  /**
25473
26488
  * ```js
25474
- * import { onMessageCreated } from '@amityco/ts-sdk'
25475
- * const dispose = onMessageCreated(message => {
26489
+ * import { onChannelSubCreated } from '@amityco/ts-sdk'
26490
+ * const dispose = onSubChannelCreated(subChannel => {
25476
26491
  * // ...
25477
26492
  * })
25478
26493
  * ```
25479
26494
  *
25480
- * Fired when an {@link Amity.Message} has been created
26495
+ * Fired when any {@link Amity.SubChannel} have been created
25481
26496
  *
25482
26497
  * @param callback The function to call when the event was fired
25483
26498
  * @returns an {@link Amity.Unsubscriber} function to stop listening
25484
26499
  *
25485
- * @category Message Events
26500
+ * @category Channel Events
25486
26501
  */
25487
- const onMessageCreated = (callback) => {
26502
+ const onSubChannelCreated = (callback) => {
25488
26503
  const client = getActiveClient();
25489
- const filter = (payload) => {
26504
+ const filter = (rawPayload) => {
26505
+ const payload = prepareSubChannelPayload(rawPayload);
25490
26506
  ingestInCache(payload);
25491
- callback(payload.messages[0]);
26507
+ callback(payload.messageFeeds[0]);
25492
26508
  };
25493
- return createEventSubscriber(client, 'message/onMessageCreated', 'v3.message.didCreate', filter);
26509
+ return createEventSubscriber(client, 'onSubChannelCreated', 'message-feed.created', filter);
25494
26510
  };
25495
26511
 
25496
26512
  /**
25497
26513
  * ```js
25498
- * import { onMessageUpdated } from '@amityco/ts-sdk'
25499
- * const dispose = onMessageUpdated(message => {
26514
+ * import { onSubChannelUpdated } from '@amityco/ts-sdk'
26515
+ * const dispose = onSubChannelUpdated(subChannel => {
25500
26516
  * // ...
25501
26517
  * })
25502
26518
  * ```
25503
26519
  *
25504
- * Fired when an {@link Amity.Message} has been updated
26520
+ * Fired when any {@link Amity.SubChannel} have been updated
25505
26521
  *
25506
26522
  * @param callback The function to call when the event was fired
25507
26523
  * @returns an {@link Amity.Unsubscriber} function to stop listening
25508
26524
  *
25509
- * @category Message Events
26525
+ * @category Channel Events
25510
26526
  */
25511
- const onMessageUpdated = (callback) => {
26527
+ const onSubChannelUpdated = (callback) => {
25512
26528
  const client = getActiveClient();
25513
- const filter = (payload) => {
26529
+ const filter = (rawPayload) => {
26530
+ const payload = prepareSubChannelPayload(rawPayload);
25514
26531
  ingestInCache(payload);
25515
- const message = payload.messages[0];
25516
- // if payload does not have myReactions
25517
- if (!(message === null || message === void 0 ? void 0 : message.myReactions)) {
25518
- prepareMessagePayloadForCache(message);
25519
- }
25520
- callback(message);
26532
+ callback(payload.messageFeeds[0]);
25521
26533
  };
25522
- return createEventSubscriber(client, 'message/onMessageUpdated', 'v3.message.didUpdate', filter);
26534
+ return createEventSubscriber(client, 'onSubChannelUpdated', 'message-feed.updated', filter);
25523
26535
  };
25524
26536
 
25525
26537
  /**
25526
26538
  * ```js
25527
- * import { onMessageDeleted } from '@amityco/ts-sdk'
25528
- * const dispose = onMessageDeleted(message => {
26539
+ * import { onSubChannelDeleted } from '@amityco/ts-sdk'
26540
+ * const dispose = onSubChannelDeleted(subChannel => {
25529
26541
  * // ...
25530
26542
  * })
25531
26543
  * ```
25532
26544
  *
25533
- * Fired when an {@link Amity.Message} was deleted
26545
+ * Fired when any {@link Amity.SubChannel} have been deleted
25534
26546
  *
25535
26547
  * @param callback The function to call when the event was fired
25536
26548
  * @returns an {@link Amity.Unsubscriber} function to stop listening
25537
26549
  *
25538
- * @category Message Events
26550
+ * @category Channel Events
25539
26551
  */
25540
- const onMessageDeleted = (callback) => {
26552
+ const onSubChannelDeleted = (callback) => {
25541
26553
  const client = getActiveClient();
25542
- const filter = (payload) => {
26554
+ const filter = (rawPayload) => {
26555
+ const payload = prepareSubChannelPayload(rawPayload);
25543
26556
  ingestInCache(payload);
25544
- callback(payload.messages[0]);
26557
+ callback(payload.messageFeeds[0]);
26558
+ };
26559
+ const disposers = [
26560
+ createEventSubscriber(client, 'onSubChannelDeleted', 'message-feed.deleted', filter),
26561
+ createEventSubscriber(client, 'local.message-feed.deleted', 'local.message-feed.deleted', payload => callback(payload.messageFeeds[0])),
26562
+ ];
26563
+ return () => {
26564
+ disposers.forEach(fn => fn());
26565
+ };
26566
+ };
26567
+
26568
+ /** @hidden */
26569
+ const onSubChannelFetched = (callback) => {
26570
+ return createEventSubscriber(getActiveClient(), 'onSubChannelFetched', 'local.message-feed.fetched', payload => callback(payload.messageFeeds[0]));
26571
+ };
26572
+
26573
+ /**
26574
+ * ```js
26575
+ * import { liveSubChannel } from '@amityco/ts-sdk';
26576
+ *
26577
+ * let subChannel;
26578
+ *
26579
+ * const unsubscribe = liveSubChannel(subChannelId, response => {
26580
+ * subChannel = response.data;
26581
+ * });
26582
+ * ```
26583
+ *
26584
+ * Observe all mutation on a given {@link Amity.SubChannel}
26585
+ *
26586
+ * @param subChannelId the ID of the message to observe
26587
+ * @param callback the function to call when new data are available
26588
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the sub channel
26589
+ *
26590
+ * @category SubChannel Live Object
26591
+ */
26592
+ const liveSubChannel = (subChannelId, callback) => {
26593
+ const { log, cache } = getActiveClient();
26594
+ const timestamp = Date.now();
26595
+ log(`liveSubChannel(tmpid: ${timestamp}) > listen`);
26596
+ if (!cache) {
26597
+ console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
26598
+ }
26599
+ let subChannel;
26600
+ const disposers = [];
26601
+ const dispatcher = (data) => {
26602
+ subChannel = data.data;
26603
+ callback(data);
26604
+ };
26605
+ const realtimeRouter = (eventSubChannel) => {
26606
+ if (subChannelId !== eventSubChannel.subChannelId) {
26607
+ return;
26608
+ }
26609
+ if (subChannel && !hasUpdates(subChannel, eventSubChannel)) {
26610
+ return;
26611
+ }
26612
+ dispatcher({ loading: false, data: eventSubChannel, origin: 'event' });
26613
+ };
26614
+ const onFetch = () => {
26615
+ const query = createQuery(getSubChannel, subChannelId);
26616
+ runQuery(query, ({ error, data, loading, origin }) => {
26617
+ dispatcher({ error, data, loading, origin });
26618
+ if (error) {
26619
+ disposers.forEach(fn => fn());
26620
+ }
26621
+ });
26622
+ };
26623
+ disposers.push(onSubChannelFetched(realtimeRouter), onSubChannelUpdated(realtimeRouter), onSubChannelDeleted(realtimeRouter));
26624
+ onFetch();
26625
+ return () => {
26626
+ log(`liveSubChannel(tmpid: ${timestamp}) > dispose`);
26627
+ disposers.forEach(fn => fn());
26628
+ };
26629
+ };
26630
+
26631
+ /**
26632
+ * ```js
26633
+ * import { liveSubChannels } from '@amityco/ts-sdk';
26634
+ *
26635
+ * let subChannels = [];
26636
+ *
26637
+ * const unsubscribe = liveSubChannels({ channelId }, response => {
26638
+ * merge(subChannels, response.data);
26639
+ * });
26640
+ * ```
26641
+ *
26642
+ * Observe all mutations on a list of {@link Amity.SubChannel}s
26643
+ *
26644
+ * @param params for querying sub channels
26645
+ * @param callback the function to call when new data are available
26646
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the sub channels
26647
+ *
26648
+ * @category SubChannel Live Collection
26649
+ */
26650
+ const liveSubChannels = (params, callback, config) => {
26651
+ const { log, cache } = getActiveClient();
26652
+ const timestamp = Date.now();
26653
+ log(`liveSubChannels(tmpid: ${timestamp}) > listen`);
26654
+ if (!cache) {
26655
+ console.log(ENABLE_CACHE_MESSAGE);
26656
+ }
26657
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = params, queryParams = __rest(params, ["limit"]);
26658
+ const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
26659
+ let snapshot;
26660
+ const disposers = [];
26661
+ const responder = (data) => {
26662
+ var _a;
26663
+ let subChannels = data.data;
26664
+ if (params.isDeleted !== undefined) {
26665
+ subChannels = filterByPropEquality(subChannels, 'isDeleted', params.isDeleted);
26666
+ }
26667
+ subChannels.sort(sortByLastActivity);
26668
+ callback({
26669
+ onNextPage: onFetch,
26670
+ data: subChannels,
26671
+ hasNextPage: !!((_a = data.params) === null || _a === void 0 ? void 0 : _a.page),
26672
+ loading: data.loading,
26673
+ error: data.error,
26674
+ });
26675
+ };
26676
+ const realtimeRouter = (action) => (subChannel) => {
26677
+ if (params.channelId !== subChannel.channelId ||
26678
+ !snapshot ||
26679
+ !isCollectionOutdated(snapshot.data, subChannel, action)) {
26680
+ return;
26681
+ }
26682
+ if (action === 'onCreate') {
26683
+ snapshot.data = [subChannel, ...snapshot.data];
26684
+ }
26685
+ else {
26686
+ snapshot.data = snapshot.data.map(x => x.subChannelId === subChannel.subChannelId ? subChannel : x);
26687
+ }
26688
+ responder(snapshot);
26689
+ };
26690
+ const onFetch = () => {
26691
+ var _a;
26692
+ const subChannels = snapshot ? snapshot.data : [];
26693
+ if (subChannels.length > 0 && !(snapshot === null || snapshot === void 0 ? void 0 : snapshot.params.page)) {
26694
+ return;
26695
+ }
26696
+ const query = createQuery(querySubChannels, Object.assign(Object.assign({}, queryParams), { page: (_a = snapshot === null || snapshot === void 0 ? void 0 : snapshot.params.page) !== null && _a !== void 0 ? _a : { limit } }));
26697
+ runQuery(query, ({ data: result, error, loading, nextPage: page }) => {
26698
+ snapshot = {
26699
+ loading,
26700
+ error,
26701
+ params: { page },
26702
+ data: result ? merge(subChannels, result) : subChannels,
26703
+ };
26704
+ responder(snapshot);
26705
+ }, queryOptions(policy));
26706
+ };
26707
+ disposers.push(onSubChannelCreated(realtimeRouter('onCreate')), onSubChannelDeleted(realtimeRouter('onDelete')), onSubChannelFetched(realtimeRouter('onFetch')), onSubChannelUpdated(realtimeRouter('onUpdate')));
26708
+ onFetch();
26709
+ return () => {
26710
+ log(`liveSubChannels(tmpid: ${timestamp}) > dispose`);
26711
+ disposers.forEach(fn => fn());
25545
26712
  };
25546
- return createEventSubscriber(client, 'message/onMessageDeleted', 'v3.message.didDelete', filter);
25547
26713
  };
25548
26714
 
25549
26715
  /**
@@ -25567,46 +26733,50 @@ const onMessageFetched = (callback) => {
25567
26733
  ingestInCache(payload);
25568
26734
  callback(payload.messages[0]);
25569
26735
  };
25570
- return createEventSubscriber(client, 'message/onMessageFetched', 'v3.message.didFetch', filter);
26736
+ return createEventSubscriber(client, 'message/onMessageFetched', 'local.message.fetched', filter);
25571
26737
  };
25572
26738
 
25573
26739
  /**
25574
26740
  * ```js
25575
- * import { liveMessage } from '@amityco/ts-sdk'
26741
+ * import { liveMessage } from '@amityco/ts-sdk';
25576
26742
  *
25577
- * let messages = []
25578
- * const unsub = liveMessage(messageId, response => merge(messages, response.data))
26743
+ * let message;
26744
+ *
26745
+ * const unsubscribe = liveMessage(messageId, response => {
26746
+ * message = response.data;
26747
+ * });
25579
26748
  * ```
25580
26749
  *
25581
26750
  * Observe all mutation on a given {@link Amity.Message}
25582
26751
  *
25583
26752
  * @param messageId the ID of the message to observe
25584
26753
  * @param callback the function to call when new data are available
25585
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
26754
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the message
25586
26755
  *
25587
26756
  * @category Message Live Object
25588
26757
  */
25589
26758
  const liveMessage = (messageId, callback) => {
25590
26759
  const { log, cache } = getActiveClient();
25591
- let message;
25592
- let isUnsyncedObject = false;
26760
+ const timestamp = Date.now();
26761
+ log(`liveMessage(tmpid: ${timestamp}) > listen`);
25593
26762
  if (!cache) {
25594
26763
  console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
25595
26764
  }
25596
- const timestamp = Date.now();
25597
- log(`liveMessage(tmpid: ${timestamp}) > listen`);
26765
+ let message;
26766
+ let isUnsyncedObject = false;
25598
26767
  const disposers = [];
25599
26768
  const dispatcher = (data) => {
25600
- var _a;
25601
- // we check updatedAt to see if the current snapshot is new so
25602
- // we won't send old data back, only fresh new data
25603
- if (message && ((_a = data.data) === null || _a === void 0 ? void 0 : _a.updatedAt) === (message === null || message === void 0 ? void 0 : message.updatedAt) && data.origin !== 'server')
25604
- return;
25605
- callback(data);
25606
26769
  message = data.data;
26770
+ callback(data);
25607
26771
  };
25608
- const realtimeRouter = (message, action) => {
25609
- dispatcher({ loading: false, data: message, origin: 'event' });
26772
+ const realtimeRouter = (eventMessage) => {
26773
+ if (messageId !== eventMessage.messageId) {
26774
+ return;
26775
+ }
26776
+ if (message && !hasUpdates(message, eventMessage)) {
26777
+ return;
26778
+ }
26779
+ dispatcher({ loading: false, data: eventMessage, origin: 'event' });
25610
26780
  };
25611
26781
  const onFetch = () => {
25612
26782
  const query = createQuery(getMessage, messageId, true);
@@ -25625,12 +26795,11 @@ const liveMessage = (messageId, callback) => {
25625
26795
  dispatcher({ loading, data, origin, error });
25626
26796
  }
25627
26797
  if (error) {
25628
- // Terminate observe functionality on error
25629
26798
  disposers.forEach(fn => fn());
25630
26799
  }
25631
26800
  });
25632
26801
  };
25633
- disposers.push(onMessageFetched(message => realtimeRouter(message)), onMessageUpdated(message => realtimeRouter(message)), onMessageDeleted(message => realtimeRouter(message)));
26802
+ disposers.push(onMessageFetched(realtimeRouter), onMessageUpdated(realtimeRouter), onMessageDeleted(realtimeRouter), onMessageFlagged(realtimeRouter), onMessageUnflagged(realtimeRouter), onMessageFlagCleared(realtimeRouter), onMessageReactionAdded(realtimeRouter), onMessageReactionRemoved(realtimeRouter));
25634
26803
  onFetch();
25635
26804
  return () => {
25636
26805
  log(`liveMessage(tmpid: ${timestamp}) > dispose`);
@@ -25640,17 +26809,18 @@ const liveMessage = (messageId, callback) => {
25640
26809
 
25641
26810
  /**
25642
26811
  * ```js
25643
- * import { liveMessages } from '@amityco/ts-sdk'
26812
+ * import { liveMessages } from '@amityco/ts-sdk';
25644
26813
  *
25645
- * let messages = []
25646
- * const unsub = liveMessages({
25647
- * channelId: Amity.Channel['channelId'];
25648
- * }, response => merge(messages, response.data))
26814
+ * let messages = [];
26815
+ *
26816
+ * const unsubscribe = liveMessages({
26817
+ * subChannelId: Amity.SubChannel['subChannelId'];
26818
+ * }, response => merge(messages, response.data));
25649
26819
  * ```
25650
26820
  *
25651
26821
  * Observe all mutations on a list of {@link Amity.Message} for a given target object
25652
26822
  *
25653
- * @param params for querying memssages from a channel
26823
+ * @param params for querying messages from a sub channel
25654
26824
  * @param callback the function to call when new data are available
25655
26825
  * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
25656
26826
  *
@@ -25667,7 +26837,7 @@ const liveMessages = (params, callback, config) => {
25667
26837
  const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
25668
26838
  const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
25669
26839
  const disposers = [];
25670
- const cacheKey = ['message', 'collection', { channelId: params.channelId }];
26840
+ const cacheKey = ['message', 'collection', { subChannelId: params.subChannelId }];
25671
26841
  const responder = (data) => {
25672
26842
  var _a, _b;
25673
26843
  let messages = (_a = data.data
@@ -25687,10 +26857,10 @@ const liveMessages = (params, callback, config) => {
25687
26857
  error: data.error,
25688
26858
  });
25689
26859
  };
25690
- const realtimeRouter = (message, action) => {
26860
+ const realtimeRouter = (action) => (message) => {
25691
26861
  var _a;
25692
26862
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25693
- if (params.channelId !== message.channelId || !collection)
26863
+ if (params.subChannelId !== message.subChannelId || !collection)
25694
26864
  return;
25695
26865
  if (action === 'onCreate') {
25696
26866
  collection.data = [...new Set([message.messageId, ...collection.data])];
@@ -25722,7 +26892,7 @@ const liveMessages = (params, callback, config) => {
25722
26892
  responder(data);
25723
26893
  }, queryOptions(policy));
25724
26894
  };
25725
- disposers.push(onMessageFetched(message => realtimeRouter(message, 'onFetch')), onMessageCreated(message => realtimeRouter(message, 'onCreate')), onMessageDeleted(message => realtimeRouter(message, 'onDelete')), onMessageUpdated(message => realtimeRouter(message, 'onUpdate')));
26895
+ disposers.push(onMessageFetched(realtimeRouter('onFetch')), onMessageCreated(realtimeRouter('onCreate')), onMessageUpdated(realtimeRouter('onUpdate')), onMessageDeleted(realtimeRouter('onDelete')), onMessageFlagged(realtimeRouter('onFlagged')), onMessageUnflagged(realtimeRouter('onUnflagged')), onMessageFlagCleared(realtimeRouter('onFlagCleared')), onMessageReactionAdded(realtimeRouter('onReactionAdded')), onMessageReactionRemoved(realtimeRouter('onReactionRemoved')));
25726
26896
  onFetch();
25727
26897
  return () => {
25728
26898
  log(`liveMessages(tmpid: ${timestamp}) > dispose`);
@@ -25735,6 +26905,7 @@ const liveMessages = (params, callback, config) => {
25735
26905
  * import { observeMessage } from '@amityco/ts-sdk'
25736
26906
  *
25737
26907
  * let message = {}
26908
+ *
25738
26909
  * const unsub = observeMessage(messageId, updated => message = updated)
25739
26910
  * ```
25740
26911
  *
@@ -25781,25 +26952,26 @@ const observeMessage = (messageId, callback, policy = 'cache_then_server') => {
25781
26952
  * import { observeMessages } from '@amityco/ts-sdk'
25782
26953
  *
25783
26954
  * let messages = []
25784
- * const unsub = observeMessages(channelId, message => merge(messages, message))
26955
+ *
26956
+ * const unsubscribe = observeMessages(channelId, message => merge(messages, message))
25785
26957
  * ```
25786
26958
  *
25787
- * Observe all mutations on a list of {@link Amity.Message} for a given {@link Amity.Channel} object
26959
+ * Observe all mutations on a list of {@link Amity.Message} for a given {@link Amity.SubChannel} object
25788
26960
  *
25789
- * @param channelId the ID of the channel where to observe the messages
26961
+ * @param subChannelId the ID of the channel where to observe the messages
25790
26962
  * @param callback the function to call when new data are available
25791
26963
  * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
25792
26964
  *
25793
26965
  * @category Message Observer
25794
26966
  */
25795
- const observeMessages = (channelId, callback) => {
26967
+ const observeMessages = (subChannelId, callback) => {
25796
26968
  const { log } = getActiveClient();
25797
26969
  const timestamp = Date.now();
25798
26970
  log(`observeMessages(tmpid: ${timestamp}) > listen`);
25799
26971
  const disposers = [];
25800
26972
  const router = (message, action) => {
25801
26973
  var _a, _b, _c;
25802
- if (((_a = message.data) === null || _a === void 0 ? void 0 : _a.channelId) !== channelId)
26974
+ if (((_a = message.data) === null || _a === void 0 ? void 0 : _a.subChannelId) !== subChannelId)
25803
26975
  return;
25804
26976
  if (callback instanceof Function)
25805
26977
  return callback(message);
@@ -25862,22 +27034,23 @@ function getEventRelatedMember(event, payload) {
25862
27034
  const createCommunityMemberEventSubscriber = (event, callback) => {
25863
27035
  const client = getActiveClient();
25864
27036
  const filter = (payload) => {
25865
- const unpackedPayload = unpackCommunityPayload(payload);
27037
+ const communityPayload = unpackCommunityPayload(payload);
27038
+ const preparedPayload = prepareMembershipPayload(communityPayload, 'communityUsers');
25866
27039
  if (!client.cache) {
25867
27040
  // TODO: here we are missing specific properties here!
25868
- callback(unpackedPayload.communities[0], getEventRelatedMember(event, unpackedPayload));
27041
+ callback(preparedPayload.communities[0], getEventRelatedMember(event, preparedPayload));
25869
27042
  }
25870
27043
  else {
25871
- ingestInCache(unpackedPayload);
27044
+ ingestInCache(preparedPayload);
25872
27045
  const community = pullFromCache([
25873
27046
  'community',
25874
27047
  'get',
25875
- unpackedPayload.communities[0].communityId,
27048
+ preparedPayload.communities[0].communityId,
25876
27049
  ]);
25877
27050
  const member = pullFromCache([
25878
27051
  'communityUsers',
25879
27052
  'get',
25880
- getResolver('communityUsers')(getEventRelatedMember(event, unpackedPayload)),
27053
+ getResolver('communityUsers')(getEventRelatedMember(event, preparedPayload)),
25881
27054
  ]);
25882
27055
  callback(community.data, member.data);
25883
27056
  }
@@ -26916,7 +28089,7 @@ const liveFollowers = (params, callback, config) => {
26916
28089
  error: data.error,
26917
28090
  });
26918
28091
  };
26919
- const realtimeRouter = (followStatus, action) => {
28092
+ const realtimeRouter = (action) => (followStatus) => {
26920
28093
  var _a;
26921
28094
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26922
28095
  if (params.userId !== followStatus.to || !collection)
@@ -26951,7 +28124,7 @@ const liveFollowers = (params, callback, config) => {
26951
28124
  responder(data);
26952
28125
  }, queryOptions(policy));
26953
28126
  };
26954
- disposers.push(onFollowerRequested(followStatus => realtimeRouter(followStatus, 'onRequested')), onFollowRequestAccepted(followStatus => realtimeRouter(followStatus, 'onAccepted')), onFollowRequestDeclined(followStatus => realtimeRouter(followStatus, 'onDeclined')), onFollowRequestCanceled(followStatus => realtimeRouter(followStatus, 'onCanceled')), onUserFollowed(followStatus => realtimeRouter(followStatus, 'onFollowed')), onUserUnfollowed(followStatus => realtimeRouter(followStatus, 'onUnfollowed')), onFollowerDeleted(followStatus => realtimeRouter(followStatus, 'onDeleted')));
28127
+ disposers.push(onFollowerRequested(realtimeRouter('onRequested')), onFollowRequestAccepted(realtimeRouter('onAccepted')), onFollowRequestDeclined(realtimeRouter('onDeclined')), onFollowRequestCanceled(realtimeRouter('onCanceled')), onUserFollowed(realtimeRouter('onFollowed')), onUserUnfollowed(realtimeRouter('onUnfollowed')), onFollowerDeleted(realtimeRouter('onDeleted')));
26955
28128
  onFetch();
26956
28129
  return () => {
26957
28130
  log(`liveFollowers(tmpid: ${timestamp}) > dispose`);
@@ -27006,7 +28179,7 @@ const liveFollowings = (params, callback, config) => {
27006
28179
  error: data.error,
27007
28180
  });
27008
28181
  };
27009
- const realtimeRouter = (followStatus, action) => {
28182
+ const realtimeRouter = (action) => (followStatus) => {
27010
28183
  var _a;
27011
28184
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27012
28185
  if (params.userId !== followStatus.from || !collection)
@@ -27041,7 +28214,7 @@ const liveFollowings = (params, callback, config) => {
27041
28214
  responder(data);
27042
28215
  }, queryOptions(policy));
27043
28216
  };
27044
- disposers.push(onFollowerRequested(followStatus => realtimeRouter(followStatus, 'onRequested')), onFollowRequestAccepted(followStatus => realtimeRouter(followStatus, 'onAccepted')), onFollowRequestDeclined(followStatus => realtimeRouter(followStatus, 'onDeclined')), onFollowRequestCanceled(followStatus => realtimeRouter(followStatus, 'onCanceled')), onUserFollowed(followStatus => realtimeRouter(followStatus, 'onFollowed')), onUserUnfollowed(followStatus => realtimeRouter(followStatus, 'onUnfollowed')), onFollowerDeleted(followStatus => realtimeRouter(followStatus, 'onDeleted')));
28217
+ disposers.push(onFollowerRequested(realtimeRouter('onRequested')), onFollowRequestAccepted(realtimeRouter('onAccepted')), onFollowRequestDeclined(realtimeRouter('onDeclined')), onFollowRequestCanceled(realtimeRouter('onCanceled')), onUserFollowed(realtimeRouter('onFollowed')), onUserUnfollowed(realtimeRouter('onUnfollowed')), onFollowerDeleted(realtimeRouter('onDeleted')));
27045
28218
  onFetch();
27046
28219
  return () => {
27047
28220
  log(`liveFollowings(tmpid: ${timestamp}) > dispose`);
@@ -27179,6 +28352,9 @@ const livePosts = (params, callback, config) => {
27179
28352
  posts = filterByPropEquality(posts, 'isDeleted', params.isDeleted);
27180
28353
  const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
27181
28354
  posts = posts.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
28355
+ if (params.tags) {
28356
+ posts = posts.filter(p => { var _a; return (_a = p.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = params.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
28357
+ }
27182
28358
  callback({
27183
28359
  onNextPage: onFetch,
27184
28360
  data: posts,
@@ -27187,17 +28363,32 @@ const livePosts = (params, callback, config) => {
27187
28363
  error: data.error,
27188
28364
  });
27189
28365
  };
27190
- const realtimeRouter = (post, action) => {
28366
+ const realtimeRouter = (action) => (post) => {
27191
28367
  var _a;
27192
28368
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27193
28369
  if (params.targetId !== post.targetId || params.targetType !== post.targetType || !collection)
27194
28370
  return;
27195
- if (action === 'onCreate') {
28371
+ if (['onCreate', 'onApproved'].includes(action)) {
27196
28372
  collection.data = [...new Set([post.postId, ...collection.data])];
27197
28373
  }
27198
28374
  else if (['onDelete', 'onDeclined'].includes(action)) {
27199
28375
  collection.data = collection.data.filter(p => p !== post.postId);
28376
+ /*
28377
+ * if isDeleted is true, collection should add deleted items to the
28378
+ * begining of the collection
28379
+ */
28380
+ if (params.isDeleted)
28381
+ collection.data.unshift(post.postId);
27200
28382
  }
28383
+ /*
28384
+ * FIX-ME
28385
+ * This is a shortcoming as the feed object is not saved to the cache.
28386
+ * The responder should pull the feed from cache once available and should
28387
+ * match the collection to feedType param
28388
+ * https://ekoapp.atlassian.net/browse/ASC-9382
28389
+ */
28390
+ if (params.feedType === 'reviewing' && action === 'onApproved')
28391
+ collection.data = collection.data.filter(p => p !== post.postId);
27201
28392
  pushToCache(cacheKey, collection);
27202
28393
  responder(collection);
27203
28394
  };
@@ -27222,7 +28413,7 @@ const livePosts = (params, callback, config) => {
27222
28413
  responder(data);
27223
28414
  }, queryOptions(policy));
27224
28415
  };
27225
- disposers.push(onPostCreated(post => realtimeRouter(post, 'onCreate')), onPostApproved(post => realtimeRouter(post, 'onApproved')), onPostDeclined(post => realtimeRouter(post, 'onDeclined')), onPostDeleted(post => realtimeRouter(post, 'onDelete')), onPostUpdated(post => realtimeRouter(post, 'onUpdate')), onPostFlagged(post => realtimeRouter(post, 'onFlagged')), onPostUnflagged(post => realtimeRouter(post, 'onUnflagged')), onPostReactionAdded(post => realtimeRouter(post, 'onReactionAdded')), onPostReactionRemoved(post => realtimeRouter(post, 'onReactionRemoved')));
28416
+ disposers.push(onPostCreated(realtimeRouter('onCreate')), onPostApproved(realtimeRouter('onApproved')), onPostDeclined(realtimeRouter('onDeclined')), onPostDeleted(realtimeRouter('onDelete')), onPostUpdated(realtimeRouter('onUpdate')), onPostFlagged(realtimeRouter('onFlagged')), onPostUnflagged(realtimeRouter('onUnflagged')), onPostReactionAdded(realtimeRouter('onReactionAdded')), onPostReactionRemoved(realtimeRouter('onReactionRemoved')));
27226
28417
  onFetch();
27227
28418
  return () => {
27228
28419
  log(`livePosts(tmpid: ${timestamp}) > dispose`);
@@ -27364,7 +28555,7 @@ const liveComments = (params, callback, config) => {
27364
28555
  error: data.error,
27365
28556
  });
27366
28557
  };
27367
- const realtimeRouter = (comment, action) => {
28558
+ const realtimeRouter = (action) => (comment) => {
27368
28559
  var _a;
27369
28560
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27370
28561
  if (params.referenceId !== comment.referenceId ||
@@ -27403,7 +28594,7 @@ const liveComments = (params, callback, config) => {
27403
28594
  responder(data);
27404
28595
  }, queryOptions(policy));
27405
28596
  };
27406
- disposers.push(onCommentCreated(comment => realtimeRouter(comment, 'onCreate')), onCommentUpdated(comment => realtimeRouter(comment, 'onUpdate')), onCommentDeleted(comment => realtimeRouter(comment, 'onDelete')), onCommentFlagged(comment => realtimeRouter(comment, 'onFlagged')), onCommentUnflagged(comment => realtimeRouter(comment, 'onUnflagged')), onCommentReactionAdded(comment => realtimeRouter(comment, 'onReactionAdded')), onCommentReactionRemoved(comment => realtimeRouter(comment, 'onReactionRemoved')));
28597
+ disposers.push(onCommentCreated(realtimeRouter('onCreate')), onCommentUpdated(realtimeRouter('onUpdate')), onCommentDeleted(realtimeRouter('onDelete')), onCommentFlagged(realtimeRouter('onFlagged')), onCommentUnflagged(realtimeRouter('onUnflagged')), onCommentReactionAdded(realtimeRouter('onReactionAdded')), onCommentReactionRemoved(realtimeRouter('onReactionRemoved')));
27407
28598
  onFetch();
27408
28599
  return () => {
27409
28600
  log(`liveComments(tmpid: ${timestamp}) > dispose`);
@@ -27995,4 +29186,4 @@ const createUserToken = async (apiKey, apiRegion, params) => {
27995
29186
  return { accessToken: data.accessToken };
27996
29187
  };
27997
29188
 
27998
- export { API_REGIONS, CommunityPostSettingMaps, CommunityPostSettings, ContentFeedType, DefaultCommunityPostSetting, FileType, MessageContentType, PostContentType, SubscriptionLevels, VERSION$1 as VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, acceptFollower, addChannelMembers, addChannelMembersRole, addCommunityMembers, addCommunityMembersRoles, addReaction, approvePost, backupCache, banChannelMembers, closePoll, connectClient, createChannel, createClient, createComment, createCommunity, createFile, createImage, createMessage, createPoll, createPost, createQuery, createReport, createStream, createUserToken, createVideo, declineFollower, declinePost, deleteChannel, deleteComment, deleteCommunity, deleteFile, deleteMessage, deletePoll, deletePost, deleteReport, deleteStream, disableCache, disconnectClient, disposeStream, dropFromCache, enableCache, fileUrlWithSize, filterByChannelMembership, filterByPropEquality, filterByPropInclusion, follow, getActiveClient, getCategory, getChannel, getChannels, getComment, getCommentTopic, getComments, getCommunities, getCommunity, getCommunityTopic, getFeedSettings, getFile, getFollowInfo, getMessage, getMessages, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPoll, getPost, getPostTopic, getPosts, getRecommendedCommunities, getRole, getStream, getTopTrendingCommunities, getUser, getUserTopic, getUsers, isAfterBefore, isAfterBeforeRaw, isCachable, isConnected, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkipLimit, joinChannel, joinCommunity, leaveChannel, leaveCommunity, liveChannelMembers, liveChannels, liveComments, liveFollowers, liveFollowings, liveMessage, liveMessages, livePosts, liveReactions, liveUser, mergeInCache, observeChannel, observeChannels, observeComment, observeComments, observeCommunity, observeFile, observeFollowInfo, observeFollowers, observeFollowings, observeMessage, observeMessages, observePoll, observePost, observePosts, observeUser, onChannelCreated, onChannelDeleted, onChannelJoined, onChannelLeft, onChannelMemberAdded, onChannelMemberBanned, onChannelMemberRemoved, onChannelMemberUnbanned, onChannelUpdated, onClientBanned, onClientDisconnected, onCommentCreated, onCommentDeleted, onCommentFlagged, onCommentReactionAdded, onCommentReactionRemoved, onCommentUnflagged, onCommentUpdated, onCommunityCreated, onCommunityDeleted, onCommunityJoined, onCommunityLeft, onCommunityUpdated, onCommunityUserAdded, onCommunityUserBanned, onCommunityUserRemoved, onCommunityUserUnbanned, onConnectionError, onFollowInfoUpdated, onFollowRequestAccepted, onFollowRequestCanceled, onFollowRequestDeclined, onFollowerDeleted, onFollowerRequested, onMessageCreated, onMessageDeleted, onMessageFetched, onMessageUpdated, onPollDeleted, onPollUpdated, onPostApproved, onPostCreated, onPostDeclined, onPostDeleted, onPostFlagged, onPostReactionAdded, onPostReactionRemoved, onPostUnflagged, onPostUpdated, onReactionAdded, onReactionRemoved, onReactorAdded, onReactorRemoved, onStreamRecorded, onStreamStarted, onStreamStopped, onUserDeleted, onUserFetched, onUserFlagCleared, onUserFlagged, onUserFollowed, onUserUnflagged, onUserUnfollowed, onUserUpdated, pullFromCache, pushToCache, queryCache, queryCategories, queryChannelMembers, queryChannels, queryComments, queryCommunities, queryCommunityMembers, queryFollowers, queryFollowings, queryGlobalFeed, queryMessages, queryOptions, queryPosts, queryReactions, queryRoles, queryStreams, queryUsers, removeChannelMembers, removeChannelMembersRole, removeCommunityMembers, removeCommunityMembersRoles, removeReaction, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByLastActivity, sortByLastCreated, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, unbanChannelMembers, unfollow, updateChannel, updateComment, updateCommunity, updateMessage, updatePost, updateStream, updateUser, upsertInCache, votePoll, wipeCache };
29189
+ export { API_REGIONS, CommunityPostSettingMaps, CommunityPostSettings, ContentFeedType, DefaultCommunityPostSetting, FileType, MessageContentType, PostContentType, SubscriptionLevels, VERSION$1 as VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, acceptFollower, addChannelMembers, addChannelMembersRole, addCommunityMembers, addCommunityMembersRoles, addReaction, approvePost, backupCache, banChannelMembers, closePoll, connectClient, createChannel, createClient, createComment, createCommunity, createFile, createImage, createMessage, createPoll, createPost, createQuery, createReport, createStream, createSubChannel, createUserToken, createVideo, declineFollower, declinePost, deleteChannel, deleteComment, deleteCommunity, deleteFile, deleteMessage, deletePoll, deletePost, deleteReport, deleteStream, deleteSubChannel, disableCache, disconnectClient, disposeStream, dropFromCache, enableCache, fileUrlWithSize, filterByChannelMembership, filterByPropEquality, filterByPropInclusion, follow, getActiveClient, getCategory, getChannel, getChannelTopic, getChannels, getComment, getCommentTopic, getComments, getCommunities, getCommunity, getCommunityTopic, getFeedSettings, getFile, getFollowInfo, getMessage, getMessageTopic, getMessages, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPoll, getPost, getPostTopic, getPosts, getRecommendedCommunities, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStream, getSubChannel, getSubChannelTopic, getSubChannels, getTopTrendingCommunities, getUser, getUserTopic, getUsers, isAfterBefore, isAfterBeforeRaw, isCachable, isConnected, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkipLimit, joinChannel, joinCommunity, leaveChannel, leaveCommunity, liveChannel, liveChannelMembers, liveChannels, liveComments, liveFollowers, liveFollowings, liveMessage, liveMessages, livePosts, liveReactions, liveSubChannel, liveSubChannels, liveUser, mergeInCache, observeChannel, observeChannels, observeComment, observeComments, observeCommunity, observeFile, observeFollowInfo, observeFollowers, observeFollowings, observeMessage, observeMessages, observePoll, observePost, observePosts, observeUser, onChannelCreated, onChannelDeleted, onChannelJoined, onChannelLeft, onChannelMemberAdded, onChannelMemberBanned, onChannelMemberRemoved, onChannelMemberUnbanned, onChannelMuted, onChannelUpdated, onClientBanned, onClientDisconnected, onCommentCreated, onCommentDeleted, onCommentFlagged, onCommentReactionAdded, onCommentReactionRemoved, onCommentUnflagged, onCommentUpdated, onCommunityCreated, onCommunityDeleted, onCommunityJoined, onCommunityLeft, onCommunityUpdated, onCommunityUserAdded, onCommunityUserBanned, onCommunityUserRemoved, onCommunityUserUnbanned, onConnectionError, onFollowInfoUpdated, onFollowRequestAccepted, onFollowRequestCanceled, onFollowRequestDeclined, onFollowerDeleted, onFollowerRequested, onMessageCreated, onMessageDeleted, onMessageFlagCleared, onMessageFlagged, onMessageReactionAdded, onMessageReactionRemoved, onMessageUnflagged, onMessageUpdated, onPollDeleted, onPollUpdated, onPostApproved, onPostCreated, onPostDeclined, onPostDeleted, onPostFlagged, onPostReactionAdded, onPostReactionRemoved, onPostUnflagged, onPostUpdated, onReactionAdded, onReactionRemoved, onReactorAdded, onReactorRemoved, onStreamRecorded, onStreamStarted, onStreamStopped, onSubChannelCreated, onSubChannelDeleted, onSubChannelUpdated, onUserDeleted, onUserFlagCleared, onUserFlagged, onUserFollowed, onUserUnflagged, onUserUnfollowed, onUserUpdated, pullFromCache, pushToCache, queryCache, queryCategories, queryChannelMembers, queryChannels, queryComments, queryCommunities, queryCommunityMembers, queryFollowers, queryFollowings, queryGlobalFeed, queryMessages, queryOptions, queryPosts, queryReactions, queryRoles, queryStreams, querySubChannels, queryUsers, removeChannelMembers, removeChannelMembersRole, removeCommunityMembers, removeCommunityMembersRoles, removeReaction, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByLastActivity, sortByLastCreated, sortBySegmentNumber, startReading, stopReading, subscribeTopic, toPage, toPageRaw, toToken, unbanChannelMembers, unfollow, updateChannel, updateComment, updateCommunity, updateMessage, updatePost, updateStream, updateSubChannel, updateUser, upsertInCache, votePoll, wipeCache };