@amityco/ts-sdk 0.0.1-beta.32 → 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 (567) 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/ingestInCache.d.ts +1 -1
  24. package/dist/cache/api/tests/dropFromCache.test.d.ts +2 -0
  25. package/dist/cache/api/tests/dropFromCache.test.d.ts.map +1 -0
  26. package/dist/cache/api/tests/enableCache.test.d.ts +2 -0
  27. package/dist/cache/api/tests/enableCache.test.d.ts.map +1 -0
  28. package/dist/cache/api/tests/ingestInCache.test.d.ts +2 -0
  29. package/dist/cache/api/tests/ingestInCache.test.d.ts.map +1 -0
  30. package/dist/cache/api/tests/pullFromCache.test.d.ts +2 -0
  31. package/dist/cache/api/tests/pullFromCache.test.d.ts.map +1 -0
  32. package/dist/cache/api/tests/upsertInCache.test.d.ts +2 -0
  33. package/dist/cache/api/tests/upsertInCache.test.d.ts.map +1 -0
  34. package/dist/cache/utils/tests/encodeKey.test.d.ts +2 -0
  35. package/dist/cache/utils/tests/encodeKey.test.d.ts.map +1 -0
  36. package/dist/cache/utils/tests/partialMatch.test.d.ts +2 -0
  37. package/dist/cache/utils/tests/partialMatch.test.d.ts.map +1 -0
  38. package/dist/channel/api/banChannelMembers.d.ts.map +1 -1
  39. package/dist/channel/api/createChannel.d.ts +1 -1
  40. package/dist/channel/api/index.d.ts +2 -0
  41. package/dist/channel/api/index.d.ts.map +1 -1
  42. package/dist/channel/api/queryChannelMembers.d.ts.map +1 -1
  43. package/dist/channel/api/removeChannelMembers.d.ts.map +1 -1
  44. package/dist/channel/api/startReading.d.ts +17 -0
  45. package/dist/channel/api/startReading.d.ts.map +1 -0
  46. package/dist/channel/api/stopReading.d.ts +16 -0
  47. package/dist/channel/api/stopReading.d.ts.map +1 -0
  48. package/dist/channel/api/tests/createChannel.test.d.ts +2 -0
  49. package/dist/channel/api/tests/createChannel.test.d.ts.map +1 -0
  50. package/dist/channel/api/tests/joinChannel.test.d.ts +2 -0
  51. package/dist/channel/api/tests/joinChannel.test.d.ts.map +1 -0
  52. package/dist/channel/api/tests/removeChannelMembers.test.d.ts +2 -0
  53. package/dist/channel/api/tests/removeChannelMembers.test.d.ts.map +1 -0
  54. package/dist/channel/api/tests/startReading.test.d.ts +2 -0
  55. package/dist/channel/api/tests/startReading.test.d.ts.map +1 -0
  56. package/dist/channel/api/tests/stopReading.test.d.ts +2 -0
  57. package/dist/channel/api/tests/stopReading.test.d.ts.map +1 -0
  58. package/dist/channel/api/unbanChannelMembers.d.ts.map +1 -1
  59. package/dist/channel/events/index.d.ts +1 -0
  60. package/dist/channel/events/index.d.ts.map +1 -1
  61. package/dist/channel/events/onChannelJoined.d.ts +2 -2
  62. package/dist/channel/events/onChannelJoined.d.ts.map +1 -1
  63. package/dist/channel/events/onChannelLeft.d.ts +2 -2
  64. package/dist/channel/events/onChannelLeft.d.ts.map +1 -1
  65. package/dist/channel/events/onChannelMemberAdded.d.ts.map +1 -1
  66. package/dist/channel/events/onChannelMemberBanned.d.ts.map +1 -1
  67. package/dist/channel/events/onChannelMemberRemoved.d.ts.map +1 -1
  68. package/dist/channel/events/onChannelMemberUnbanned.d.ts.map +1 -1
  69. package/dist/channel/events/onChannelMuted.d.ts +17 -0
  70. package/dist/channel/events/onChannelMuted.d.ts.map +1 -0
  71. package/dist/channel/events/onChannelUpdated.d.ts +1 -1
  72. package/dist/channel/events/onChannelUpdated.d.ts.map +1 -1
  73. package/dist/channel/events/tests/onChannelCreated.test.d.ts +2 -0
  74. package/dist/channel/events/tests/onChannelCreated.test.d.ts.map +1 -0
  75. package/dist/channel/events/tests/onChannelJoined.test.d.ts +2 -0
  76. package/dist/channel/events/tests/onChannelJoined.test.d.ts.map +1 -0
  77. package/dist/channel/events/tests/onChannelMemberAdded.test.d.ts +2 -0
  78. package/dist/channel/events/tests/onChannelMemberAdded.test.d.ts.map +1 -0
  79. package/dist/channel/events/tests/onChannelMemberRemoved.test.d.ts +2 -0
  80. package/dist/channel/events/tests/onChannelMemberRemoved.test.d.ts.map +1 -0
  81. package/dist/channel/events/tests/onChannelUpdated.test.d.ts +2 -0
  82. package/dist/channel/events/tests/onChannelUpdated.test.d.ts.map +1 -0
  83. package/dist/channel/observers/index.d.ts +1 -0
  84. package/dist/channel/observers/index.d.ts.map +1 -1
  85. package/dist/channel/observers/liveChannel.d.ts +21 -0
  86. package/dist/channel/observers/liveChannel.d.ts.map +1 -0
  87. package/dist/channel/observers/liveChannelMembers.d.ts.map +1 -1
  88. package/dist/channel/observers/liveChannels.d.ts.map +1 -1
  89. package/dist/channel/observers/observeChannel.d.ts +1 -1
  90. package/dist/channel/observers/observeChannel.d.ts.map +1 -1
  91. package/dist/channel/observers/observeChannels.d.ts.map +1 -1
  92. package/dist/channel/utils/index.d.ts +2 -1
  93. package/dist/channel/utils/index.d.ts.map +1 -1
  94. package/dist/client/api/connectClient.d.ts.map +1 -1
  95. package/dist/client/api/getChatSettings.d.ts +15 -0
  96. package/dist/client/api/getChatSettings.d.ts.map +1 -0
  97. package/dist/client/api/getSocialSettings.d.ts +15 -0
  98. package/dist/client/api/getSocialSettings.d.ts.map +1 -0
  99. package/dist/client/api/tests/activeClient.test.d.ts +2 -0
  100. package/dist/client/api/tests/activeClient.test.d.ts.map +1 -0
  101. package/dist/client/api/tests/activeUser.test.d.ts +2 -0
  102. package/dist/client/api/tests/activeUser.test.d.ts.map +1 -0
  103. package/dist/client/api/tests/createClient.test.d.ts +2 -0
  104. package/dist/client/api/tests/createClient.test.d.ts.map +1 -0
  105. package/dist/client/tests/connectClient.test.d.ts +2 -0
  106. package/dist/client/tests/connectClient.test.d.ts.map +1 -0
  107. package/dist/comment/api/createComment.d.ts +1 -1
  108. package/dist/comment/api/createComment.d.ts.map +1 -1
  109. package/dist/comment/api/tests/createComment.test.d.ts +2 -0
  110. package/dist/comment/api/tests/createComment.test.d.ts.map +1 -0
  111. package/dist/comment/api/tests/getComments.test.d.ts +2 -0
  112. package/dist/comment/api/tests/getComments.test.d.ts.map +1 -0
  113. package/dist/comment/events/tests/onCommentCreated.test.d.ts +2 -0
  114. package/dist/comment/events/tests/onCommentCreated.test.d.ts.map +1 -0
  115. package/dist/comment/events/utils.d.ts +1 -1
  116. package/dist/comment/events/utils.d.ts.map +1 -1
  117. package/dist/community/api/queryCommunities.d.ts.map +1 -1
  118. package/dist/community/api/queryCommunityMembers.d.ts +6 -1
  119. package/dist/community/api/queryCommunityMembers.d.ts.map +1 -1
  120. package/dist/community/api/test/addCommunityMember.test.d.ts +2 -0
  121. package/dist/community/api/test/addCommunityMember.test.d.ts.map +1 -0
  122. package/dist/community/api/test/addCommunityMemberRole.test.d.ts +2 -0
  123. package/dist/community/api/test/addCommunityMemberRole.test.d.ts.map +1 -0
  124. package/dist/community/api/test/createCommunity.test.d.ts +2 -0
  125. package/dist/community/api/test/createCommunity.test.d.ts.map +1 -0
  126. package/dist/community/api/test/deleteCommunity.test.d.ts +2 -0
  127. package/dist/community/api/test/deleteCommunity.test.d.ts.map +1 -0
  128. package/dist/community/api/test/getCommunities.test.d.ts +2 -0
  129. package/dist/community/api/test/getCommunities.test.d.ts.map +1 -0
  130. package/dist/community/api/test/getCommunity.test.d.ts +2 -0
  131. package/dist/community/api/test/getCommunity.test.d.ts.map +1 -0
  132. package/dist/community/api/test/getRecommendedCommunities.test.d.ts +2 -0
  133. package/dist/community/api/test/getRecommendedCommunities.test.d.ts.map +1 -0
  134. package/dist/community/api/test/getTopTrendingCommunities.test.d.ts +2 -0
  135. package/dist/community/api/test/getTopTrendingCommunities.test.d.ts.map +1 -0
  136. package/dist/community/api/test/joinCommunity.test.d.ts +2 -0
  137. package/dist/community/api/test/joinCommunity.test.d.ts.map +1 -0
  138. package/dist/community/api/test/leaveCommunity.test.d.ts +2 -0
  139. package/dist/community/api/test/leaveCommunity.test.d.ts.map +1 -0
  140. package/dist/community/api/test/queryCommunity.test.d.ts +2 -0
  141. package/dist/community/api/test/queryCommunity.test.d.ts.map +1 -0
  142. package/dist/community/api/test/queryCommunityMembers.test.d.ts +2 -0
  143. package/dist/community/api/test/queryCommunityMembers.test.d.ts.map +1 -0
  144. package/dist/community/api/test/removeCommunityMemberRole.test.d.ts +2 -0
  145. package/dist/community/api/test/removeCommunityMemberRole.test.d.ts.map +1 -0
  146. package/dist/community/api/test/removeCommunityMembers.test.d.ts +2 -0
  147. package/dist/community/api/test/removeCommunityMembers.test.d.ts.map +1 -0
  148. package/dist/community/api/test/updateCommunity.test.d.ts +2 -0
  149. package/dist/community/api/test/updateCommunity.test.d.ts.map +1 -0
  150. package/dist/community/events/test/onCommunityCreated.test.d.ts +2 -0
  151. package/dist/community/events/test/onCommunityCreated.test.d.ts.map +1 -0
  152. package/dist/community/events/test/onCommunityDeleted.test.d.ts +2 -0
  153. package/dist/community/events/test/onCommunityDeleted.test.d.ts.map +1 -0
  154. package/dist/community/events/test/onCommunityJoined.test.d.ts +2 -0
  155. package/dist/community/events/test/onCommunityJoined.test.d.ts.map +1 -0
  156. package/dist/community/events/test/onCommunityLeft.test.d.ts +2 -0
  157. package/dist/community/events/test/onCommunityLeft.test.d.ts.map +1 -0
  158. package/dist/community/events/test/onCommunityUpdated.test.d.ts +2 -0
  159. package/dist/community/events/test/onCommunityUpdated.test.d.ts.map +1 -0
  160. package/dist/community/events/test/onCommunityUserAdded.test.d.ts +2 -0
  161. package/dist/community/events/test/onCommunityUserAdded.test.d.ts.map +1 -0
  162. package/dist/community/events/test/onCommunityUserBanned.test.d.ts +2 -0
  163. package/dist/community/events/test/onCommunityUserBanned.test.d.ts.map +1 -0
  164. package/dist/community/events/test/onCommunityUserRemoved.test.d.ts +2 -0
  165. package/dist/community/events/test/onCommunityUserRemoved.test.d.ts.map +1 -0
  166. package/dist/community/events/test/onCommunityUserUnbaned.test.d.ts +2 -0
  167. package/dist/community/events/test/onCommunityUserUnbaned.test.d.ts.map +1 -0
  168. package/dist/community/events/test/utils.test.d.ts +2 -0
  169. package/dist/community/events/test/utils.test.d.ts.map +1 -0
  170. package/dist/community/events/utils.d.ts +2 -2
  171. package/dist/community/events/utils.d.ts.map +1 -1
  172. package/dist/core/events.d.ts +3 -3
  173. package/dist/core/events.d.ts.map +1 -1
  174. package/dist/core/model/idResolvers.d.ts.map +1 -1
  175. package/dist/core/model/identifyModel.d.ts.map +1 -1
  176. package/dist/core/model/index.d.ts +5 -0
  177. package/dist/core/model/index.d.ts.map +1 -1
  178. package/dist/core/query/filtering.d.ts.map +1 -1
  179. package/dist/core/query/query.d.ts.map +1 -1
  180. package/dist/core/subscription.d.ts +26 -1
  181. package/dist/core/subscription.d.ts.map +1 -1
  182. package/dist/core/tests/subscription.test.d.ts +2 -0
  183. package/dist/core/tests/subscription.test.d.ts.map +1 -0
  184. package/dist/feed/api/queryGlobalFeed.d.ts +1 -1
  185. package/dist/feed/api/queryGlobalFeed.d.ts.map +1 -1
  186. package/dist/feed/api/test/queryGlobalFeed.test.d.ts +2 -0
  187. package/dist/feed/api/test/queryGlobalFeed.test.d.ts.map +1 -0
  188. package/dist/follow/events/utils.d.ts +1 -1
  189. package/dist/follow/events/utils.d.ts.map +1 -1
  190. package/dist/group/utils/index.d.ts +2 -0
  191. package/dist/group/utils/index.d.ts.map +1 -0
  192. package/dist/group/utils/test/withUsers.test.d.ts +2 -0
  193. package/dist/group/utils/test/withUsers.test.d.ts.map +1 -0
  194. package/dist/group/utils/withUser.d.ts +38 -0
  195. package/dist/group/utils/withUser.d.ts.map +1 -0
  196. package/dist/index.cjs.js +2053 -818
  197. package/dist/index.d.ts +3 -0
  198. package/dist/index.d.ts.map +1 -1
  199. package/dist/index.esm.js +2028 -817
  200. package/dist/index.umd.js +4 -4
  201. package/dist/message/api/createMessage.d.ts +15 -9
  202. package/dist/message/api/createMessage.d.ts.map +1 -1
  203. package/dist/message/api/deleteMessage.d.ts +2 -2
  204. package/dist/message/api/getMessage.d.ts.map +1 -1
  205. package/dist/message/api/getMessages.d.ts.map +1 -1
  206. package/dist/message/api/queryMessages.d.ts.map +1 -1
  207. package/dist/message/api/updateMessage.d.ts +1 -1
  208. package/dist/message/api/updateMessage.d.ts.map +1 -1
  209. package/dist/message/events/index.d.ts +5 -1
  210. package/dist/message/events/index.d.ts.map +1 -1
  211. package/dist/message/events/onMessageCreated.d.ts.map +1 -1
  212. package/dist/message/events/onMessageDeleted.d.ts.map +1 -1
  213. package/dist/message/events/onMessageFlagCleared.d.ts +17 -0
  214. package/dist/message/events/onMessageFlagCleared.d.ts.map +1 -0
  215. package/dist/message/events/onMessageFlagged.d.ts +17 -0
  216. package/dist/message/events/onMessageFlagged.d.ts.map +1 -0
  217. package/dist/message/events/onMessageReactionAdded.d.ts +18 -0
  218. package/dist/message/events/onMessageReactionAdded.d.ts.map +1 -0
  219. package/dist/message/events/onMessageReactionRemoved.d.ts +18 -0
  220. package/dist/message/events/onMessageReactionRemoved.d.ts.map +1 -0
  221. package/dist/message/events/onMessageUnflagged.d.ts +17 -0
  222. package/dist/message/events/onMessageUnflagged.d.ts.map +1 -0
  223. package/dist/message/events/onMessageUpdated.d.ts.map +1 -1
  224. package/dist/message/observers/liveMessage.d.ts +7 -4
  225. package/dist/message/observers/liveMessage.d.ts.map +1 -1
  226. package/dist/message/observers/liveMessages.d.ts +7 -6
  227. package/dist/message/observers/liveMessages.d.ts.map +1 -1
  228. package/dist/message/observers/observeMessage.d.ts +1 -0
  229. package/dist/message/observers/observeMessage.d.ts.map +1 -1
  230. package/dist/message/observers/observeMessages.d.ts +5 -4
  231. package/dist/message/observers/observeMessages.d.ts.map +1 -1
  232. package/dist/message/tests/events.test.d.ts +2 -0
  233. package/dist/message/tests/events.test.d.ts.map +1 -0
  234. package/dist/message/utils/index.d.ts +18 -0
  235. package/dist/message/utils/index.d.ts.map +1 -0
  236. package/dist/post/api/queryPosts.d.ts.map +1 -1
  237. package/dist/post/api/tests/queryPosts.test.d.ts +2 -0
  238. package/dist/post/api/tests/queryPosts.test.d.ts.map +1 -0
  239. package/dist/post/events/tests/onPostApproved.test.d.ts +2 -0
  240. package/dist/post/events/tests/onPostApproved.test.d.ts.map +1 -0
  241. package/dist/post/events/tests/onPostCreated.test.d.ts +2 -0
  242. package/dist/post/events/tests/onPostCreated.test.d.ts.map +1 -0
  243. package/dist/post/events/tests/onPostDeclined.test.d.ts +2 -0
  244. package/dist/post/events/tests/onPostDeclined.test.d.ts.map +1 -0
  245. package/dist/post/events/tests/onPostDeleted.test.d.ts +2 -0
  246. package/dist/post/events/tests/onPostDeleted.test.d.ts.map +1 -0
  247. package/dist/post/events/tests/onPostFlagged.test.d.ts +2 -0
  248. package/dist/post/events/tests/onPostFlagged.test.d.ts.map +1 -0
  249. package/dist/post/events/tests/onPostReactionAdded.test.d.ts +2 -0
  250. package/dist/post/events/tests/onPostReactionAdded.test.d.ts.map +1 -0
  251. package/dist/post/events/tests/onPostReactionRemoved.test.d.ts +2 -0
  252. package/dist/post/events/tests/onPostReactionRemoved.test.d.ts.map +1 -0
  253. package/dist/post/events/tests/onPostUnflagged.test.d.ts +2 -0
  254. package/dist/post/events/tests/onPostUnflagged.test.d.ts.map +1 -0
  255. package/dist/post/events/tests/onPostUpdated.test.d.ts +2 -0
  256. package/dist/post/events/tests/onPostUpdated.test.d.ts.map +1 -0
  257. package/dist/post/events/utils.d.ts +1 -1
  258. package/dist/post/events/utils.d.ts.map +1 -1
  259. package/dist/post/observers/livePosts.d.ts.map +1 -1
  260. package/dist/post/observers/tests/livePosts.test.d.ts +2 -0
  261. package/dist/post/observers/tests/livePosts.test.d.ts.map +1 -0
  262. package/dist/reaction/api/addReaction.d.ts.map +1 -1
  263. package/dist/reaction/api/removeReaction.d.ts.map +1 -1
  264. package/dist/reaction/events/onReactionAdded.d.ts.map +1 -1
  265. package/dist/reaction/events/onReactionRemoved.d.ts.map +1 -1
  266. package/dist/reaction/events/onReactorAdded.d.ts.map +1 -1
  267. package/dist/reaction/events/onReactorRemoved.d.ts.map +1 -1
  268. package/dist/report/api/createReport.d.ts.map +1 -1
  269. package/dist/report/api/deleteReport.d.ts.map +1 -1
  270. package/dist/report/api/isReportedByMe.d.ts.map +1 -1
  271. package/dist/subChannel/api/createSubChannel.d.ts +16 -0
  272. package/dist/subChannel/api/createSubChannel.d.ts.map +1 -0
  273. package/dist/subChannel/api/deleteSubChannel.d.ts +16 -0
  274. package/dist/subChannel/api/deleteSubChannel.d.ts.map +1 -0
  275. package/dist/subChannel/api/getSubChannel.d.ts +32 -0
  276. package/dist/subChannel/api/getSubChannel.d.ts.map +1 -0
  277. package/dist/subChannel/api/getSubChannels.d.ts +32 -0
  278. package/dist/subChannel/api/getSubChannels.d.ts.map +1 -0
  279. package/dist/subChannel/api/index.d.ts +7 -0
  280. package/dist/subChannel/api/index.d.ts.map +1 -0
  281. package/dist/subChannel/api/querySubChannels.d.ts +32 -0
  282. package/dist/subChannel/api/querySubChannels.d.ts.map +1 -0
  283. package/dist/subChannel/api/updateSubChannel.d.ts +17 -0
  284. package/dist/subChannel/api/updateSubChannel.d.ts.map +1 -0
  285. package/dist/subChannel/events/index.d.ts +4 -0
  286. package/dist/subChannel/events/index.d.ts.map +1 -0
  287. package/dist/subChannel/events/onSubChannelCreated.d.ts +17 -0
  288. package/dist/subChannel/events/onSubChannelCreated.d.ts.map +1 -0
  289. package/dist/subChannel/events/onSubChannelDeleted.d.ts +17 -0
  290. package/dist/subChannel/events/onSubChannelDeleted.d.ts.map +1 -0
  291. package/dist/subChannel/events/onSubChannelFetched.d.ts +3 -0
  292. package/dist/subChannel/events/onSubChannelFetched.d.ts.map +1 -0
  293. package/dist/subChannel/events/onSubChannelUpdated.d.ts +17 -0
  294. package/dist/subChannel/events/onSubChannelUpdated.d.ts.map +1 -0
  295. package/dist/subChannel/observers/index.d.ts +3 -0
  296. package/dist/subChannel/observers/index.d.ts.map +1 -0
  297. package/dist/subChannel/observers/liveSubChannel.d.ts +21 -0
  298. package/dist/subChannel/observers/liveSubChannel.d.ts.map +1 -0
  299. package/dist/subChannel/observers/liveSubChannels.d.ts +21 -0
  300. package/dist/subChannel/observers/liveSubChannels.d.ts.map +1 -0
  301. package/dist/subChannel/observers/tests/liveSubChannel.test.d.ts +2 -0
  302. package/dist/subChannel/observers/tests/liveSubChannel.test.d.ts.map +1 -0
  303. package/dist/subChannel/observers/tests/liveSubChannels.test.d.ts +2 -0
  304. package/dist/subChannel/observers/tests/liveSubChannels.test.d.ts.map +1 -0
  305. package/dist/subChannel/utils/index.d.ts +8 -0
  306. package/dist/subChannel/utils/index.d.ts.map +1 -0
  307. package/dist/user/events/index.d.ts +0 -1
  308. package/dist/user/events/index.d.ts.map +1 -1
  309. package/dist/user/events/utils.d.ts +1 -1
  310. package/dist/user/events/utils.d.ts.map +1 -1
  311. package/dist/user/observers/liveUser.d.ts +7 -4
  312. package/dist/user/observers/liveUser.d.ts.map +1 -1
  313. package/dist/utils/index.d.ts +4 -0
  314. package/dist/utils/index.d.ts.map +1 -0
  315. package/dist/utils/tests/dummy/channel.d.ts +51 -20
  316. package/dist/utils/tests/dummy/channel.d.ts.map +1 -1
  317. package/dist/utils/tests/dummy/community.d.ts +36 -0
  318. package/dist/utils/tests/dummy/community.d.ts.map +1 -0
  319. package/dist/utils/tests/dummy/file.d.ts +2 -0
  320. package/dist/utils/tests/dummy/file.d.ts.map +1 -0
  321. package/dist/utils/tests/dummy/follow.d.ts +1 -0
  322. package/dist/utils/tests/dummy/follow.d.ts.map +1 -1
  323. package/dist/utils/tests/dummy/index.d.ts +7 -0
  324. package/dist/utils/tests/dummy/index.d.ts.map +1 -1
  325. package/dist/utils/tests/dummy/member.d.ts +2 -0
  326. package/dist/utils/tests/dummy/member.d.ts.map +1 -0
  327. package/dist/utils/tests/dummy/message.d.ts +7 -1
  328. package/dist/utils/tests/dummy/message.d.ts.map +1 -1
  329. package/dist/utils/tests/dummy/poll.d.ts +3 -0
  330. package/dist/utils/tests/dummy/poll.d.ts.map +1 -0
  331. package/dist/utils/tests/dummy/post.d.ts +18 -0
  332. package/dist/utils/tests/dummy/post.d.ts.map +1 -1
  333. package/dist/utils/tests/dummy/reaction.d.ts +4 -0
  334. package/dist/utils/tests/dummy/reaction.d.ts.map +1 -0
  335. package/dist/utils/tests/dummy/role.d.ts +4 -0
  336. package/dist/utils/tests/dummy/role.d.ts.map +1 -0
  337. package/dist/utils/tests/dummy/subChannel.d.ts +3 -0
  338. package/dist/utils/tests/dummy/subChannel.d.ts.map +1 -0
  339. package/dist/utils/tests/dummy/user.d.ts +2 -0
  340. package/dist/utils/tests/dummy/user.d.ts.map +1 -1
  341. package/dist/utils/tests/utils.d.ts +1 -0
  342. package/dist/utils/tests/utils.d.ts.map +1 -1
  343. package/package.json +1 -1
  344. package/src/@types/core/events.ts +56 -28
  345. package/src/@types/core/model.ts +2 -0
  346. package/src/@types/core/payload.ts +21 -5
  347. package/src/@types/domains/channel.ts +23 -6
  348. package/src/@types/domains/client.ts +21 -0
  349. package/src/@types/domains/content.ts +4 -3
  350. package/src/@types/domains/group.ts +6 -2
  351. package/src/@types/domains/message.ts +59 -26
  352. package/src/@types/domains/post.ts +2 -2
  353. package/src/@types/domains/subChannel.ts +48 -0
  354. package/src/@types/index.ts +1 -0
  355. package/src/cache/api/ingestInCache.ts +2 -2
  356. package/src/cache/api/tests/dropFromCache.test.ts +59 -0
  357. package/src/cache/api/tests/enableCache.test.ts +15 -0
  358. package/src/cache/api/tests/ingestInCache.test.ts +87 -0
  359. package/src/cache/api/tests/pullFromCache.test.ts +42 -0
  360. package/src/cache/api/tests/upsertInCache.test.ts +60 -0
  361. package/src/cache/utils/tests/encodeKey.test.ts +19 -0
  362. package/src/cache/utils/tests/partialMatch.test.ts +13 -0
  363. package/src/channel/api/addChannelMembers.ts +2 -2
  364. package/src/channel/api/banChannelMembers.ts +5 -3
  365. package/src/channel/api/createChannel.ts +1 -1
  366. package/src/channel/api/getChannels.ts +2 -2
  367. package/src/channel/api/index.ts +3 -0
  368. package/src/channel/api/queryChannelMembers.ts +15 -10
  369. package/src/channel/api/queryChannels.ts +1 -1
  370. package/src/channel/api/removeChannelMembers.ts +9 -1
  371. package/src/channel/api/startReading.ts +53 -0
  372. package/src/channel/api/stopReading.ts +49 -0
  373. package/src/channel/api/tests/addChannelMembers.test.ts +36 -8
  374. package/src/channel/api/tests/createChannel.test.ts +53 -0
  375. package/src/channel/api/tests/getChannel.test.ts +3 -2
  376. package/src/channel/api/tests/joinChannel.test.ts +52 -0
  377. package/src/channel/api/tests/queryChannelMembers.test.ts +27 -11
  378. package/src/channel/api/tests/queryChannels.test.ts +2 -2
  379. package/src/channel/api/tests/removeChannelMembers.test.ts +95 -0
  380. package/src/channel/api/tests/startReading.test.ts +25 -0
  381. package/src/channel/api/tests/stopReading.test.ts +25 -0
  382. package/src/channel/api/unbanChannelMembers.ts +6 -3
  383. package/src/channel/events/index.ts +1 -0
  384. package/src/channel/events/onChannelCreated.ts +1 -1
  385. package/src/channel/events/onChannelDeleted.ts +1 -1
  386. package/src/channel/events/onChannelJoined.ts +12 -7
  387. package/src/channel/events/onChannelLeft.ts +12 -7
  388. package/src/channel/events/onChannelMemberAdded.ts +8 -6
  389. package/src/channel/events/onChannelMemberBanned.ts +7 -4
  390. package/src/channel/events/onChannelMemberRemoved.ts +7 -9
  391. package/src/channel/events/onChannelMemberUnbanned.ts +7 -4
  392. package/src/channel/events/onChannelMuted.ts +34 -0
  393. package/src/channel/events/onChannelUpdated.ts +10 -1
  394. package/src/channel/events/tests/onChannelCreated.test.ts +55 -0
  395. package/src/channel/events/tests/onChannelJoined.test.ts +56 -0
  396. package/src/channel/events/tests/onChannelMemberAdded.test.ts +56 -0
  397. package/src/channel/events/tests/onChannelMemberBanned.test.ts +13 -12
  398. package/src/channel/events/tests/onChannelMemberRemoved.test.ts +56 -0
  399. package/src/channel/events/tests/onChannelMemberUnbanned.test.ts +13 -12
  400. package/src/channel/events/tests/onChannelUpdated.test.ts +55 -0
  401. package/src/channel/observers/index.ts +1 -0
  402. package/src/channel/observers/liveChannel.ts +108 -0
  403. package/src/channel/observers/liveChannelMembers.ts +40 -34
  404. package/src/channel/observers/liveChannels.ts +25 -14
  405. package/src/channel/observers/observeChannel.ts +2 -0
  406. package/src/channel/observers/observeChannels.ts +2 -0
  407. package/src/channel/observers/tests/liveChannelMembers.test.ts +107 -95
  408. package/src/channel/observers/tests/liveChannels.test.ts +385 -126
  409. package/src/channel/utils/index.ts +54 -1
  410. package/src/channel/utils/tests/prepareChannelPayload.test.ts +22 -22
  411. package/src/client/api/connectClient.ts +11 -4
  412. package/src/client/api/createClient.ts +1 -1
  413. package/src/client/api/getChatSettings.ts +22 -0
  414. package/src/client/api/getSocialSettings.ts +24 -0
  415. package/src/client/api/tests/activeClient.test.ts +20 -0
  416. package/src/client/api/tests/activeUser.test.ts +20 -0
  417. package/src/client/api/tests/createClient.test.ts +40 -0
  418. package/src/client/tests/connectClient.test.ts +35 -0
  419. package/src/comment/api/createComment.ts +3 -3
  420. package/src/comment/api/tests/createComment.test.ts +49 -0
  421. package/src/comment/api/tests/getComments.test.ts +36 -0
  422. package/src/comment/events/tests/onCommentCreated.test.ts +27 -0
  423. package/src/comment/events/utils.ts +1 -1
  424. package/src/comment/observers/liveComments.ts +8 -8
  425. package/src/community/api/queryCommunities.ts +3 -2
  426. package/src/community/api/queryCommunityMembers.ts +59 -14
  427. package/src/community/api/test/addCommunityMember.test.ts +71 -0
  428. package/src/community/api/test/addCommunityMemberRole.test.ts +67 -0
  429. package/src/community/api/test/createCommunity.test.ts +61 -0
  430. package/src/community/api/test/deleteCommunity.test.ts +74 -0
  431. package/src/community/api/test/getCommunities.test.ts +73 -0
  432. package/src/community/api/test/getCommunity.test.ts +69 -0
  433. package/src/community/api/test/getRecommendedCommunities.test.ts +102 -0
  434. package/src/community/api/test/getTopTrendingCommunities.test.ts +102 -0
  435. package/src/community/api/test/joinCommunity.test.ts +70 -0
  436. package/src/community/api/test/leaveCommunity.test.ts +78 -0
  437. package/src/community/api/test/queryCommunity.test.ts +108 -0
  438. package/src/community/api/test/queryCommunityMembers.test.ts +122 -0
  439. package/src/community/api/test/removeCommunityMemberRole.test.ts +67 -0
  440. package/src/community/api/test/removeCommunityMembers.test.ts +75 -0
  441. package/src/community/api/test/updateCommunity.test.ts +65 -0
  442. package/src/community/events/test/onCommunityCreated.test.ts +46 -0
  443. package/src/community/events/test/onCommunityDeleted.test.ts +35 -0
  444. package/src/community/events/test/onCommunityJoined.test.ts +50 -0
  445. package/src/community/events/test/onCommunityLeft.test.ts +50 -0
  446. package/src/community/events/test/onCommunityUpdated.test.ts +49 -0
  447. package/src/community/events/test/onCommunityUserAdded.test.ts +50 -0
  448. package/src/community/events/test/onCommunityUserBanned.test.ts +50 -0
  449. package/src/community/events/test/onCommunityUserRemoved.test.ts +50 -0
  450. package/src/community/events/test/onCommunityUserUnbaned.test.ts +50 -0
  451. package/src/community/events/test/utils.test.ts +158 -0
  452. package/src/community/events/utils.ts +18 -10
  453. package/src/core/events.ts +9 -20
  454. package/src/core/model/idResolvers.ts +2 -1
  455. package/src/core/model/identifyModel.ts +1 -0
  456. package/src/core/model/index.ts +15 -0
  457. package/src/core/query/filtering.ts +2 -9
  458. package/src/core/query/query.ts +2 -34
  459. package/src/core/subscription.ts +47 -9
  460. package/src/core/tests/query/query/runQuery.test.ts +15 -38
  461. package/src/core/tests/subscription.test.ts +15 -0
  462. package/src/feed/api/queryGlobalFeed.ts +1 -1
  463. package/src/feed/api/test/queryGlobalFeed.test.ts +138 -0
  464. package/src/follow/events/utils.ts +1 -1
  465. package/src/follow/observers/liveFollowers.ts +8 -8
  466. package/src/follow/observers/liveFollowings.ts +8 -8
  467. package/src/group/utils/index.ts +1 -0
  468. package/src/group/utils/test/withUsers.test.ts +103 -0
  469. package/src/group/utils/withUser.ts +92 -0
  470. package/src/index.ts +4 -0
  471. package/src/message/api/createMessage.ts +60 -29
  472. package/src/message/api/deleteMessage.ts +6 -6
  473. package/src/message/api/getMessage.ts +5 -4
  474. package/src/message/api/getMessages.ts +7 -5
  475. package/src/message/api/queryMessages.ts +13 -25
  476. package/src/message/api/tests/createMessage.test.ts +129 -37
  477. package/src/message/api/tests/deleteMessage.test.ts +18 -12
  478. package/src/message/api/tests/getMessage.test.ts +6 -4
  479. package/src/message/api/tests/getMessages.test.ts +7 -8
  480. package/src/message/api/tests/queryMessages.test.ts +20 -23
  481. package/src/message/api/tests/updateMessage.test.ts +13 -12
  482. package/src/message/api/updateMessage.ts +12 -9
  483. package/src/message/events/index.ts +7 -1
  484. package/src/message/events/onMessageCreated.ts +50 -3
  485. package/src/message/events/onMessageDeleted.ts +14 -2
  486. package/src/message/events/onMessageFetched.ts +1 -1
  487. package/src/message/events/onMessageFlagCleared.ts +34 -0
  488. package/src/message/events/onMessageFlagged.ts +33 -0
  489. package/src/message/events/onMessageReactionAdded.ts +35 -0
  490. package/src/message/events/onMessageReactionRemoved.ts +40 -0
  491. package/src/message/events/onMessageUnflagged.ts +32 -0
  492. package/src/message/events/onMessageUpdated.ts +14 -10
  493. package/src/message/observers/liveMessage.ts +42 -23
  494. package/src/message/observers/liveMessages.ts +30 -16
  495. package/src/message/observers/observeMessage.ts +1 -0
  496. package/src/message/observers/observeMessages.ts +6 -5
  497. package/src/message/tests/events.test.ts +53 -0
  498. package/src/message/tests/observers/liveMessage.test.ts +46 -49
  499. package/src/message/tests/observers/liveMessages.test.ts +45 -37
  500. package/src/message/utils/index.ts +129 -0
  501. package/src/post/api/queryPosts.ts +9 -0
  502. package/src/post/api/tests/queryPosts.test.ts +149 -0
  503. package/src/post/events/tests/onPostApproved.test.ts +33 -0
  504. package/src/post/events/tests/onPostCreated.test.ts +33 -0
  505. package/src/post/events/tests/onPostDeclined.test.ts +33 -0
  506. package/src/post/events/tests/onPostDeleted.test.ts +33 -0
  507. package/src/post/events/tests/onPostFlagged.test.ts +33 -0
  508. package/src/post/events/tests/onPostReactionAdded.test.ts +40 -0
  509. package/src/post/events/tests/onPostReactionRemoved.test.ts +40 -0
  510. package/src/post/events/tests/onPostUnflagged.test.ts +33 -0
  511. package/src/post/events/tests/onPostUpdated.test.ts +33 -0
  512. package/src/post/events/utils.ts +1 -1
  513. package/src/post/observers/livePosts.ts +32 -12
  514. package/src/post/observers/tests/livePosts.test.ts +302 -0
  515. package/src/reaction/api/addReaction.ts +18 -3
  516. package/src/reaction/api/removeReaction.ts +23 -4
  517. package/src/reaction/api/tests/addReaction.test.ts +42 -6
  518. package/src/reaction/api/tests/removeReaction.test.ts +49 -13
  519. package/src/reaction/events/onReactionAdded.ts +4 -7
  520. package/src/reaction/events/onReactionRemoved.ts +4 -7
  521. package/src/reaction/events/onReactorAdded.ts +4 -2
  522. package/src/reaction/events/onReactorRemoved.ts +4 -7
  523. package/src/reaction/observers/liveReactions.ts +6 -6
  524. package/src/reaction/utils/dispatchReactable.ts +1 -1
  525. package/src/report/api/createReport.ts +28 -18
  526. package/src/report/api/deleteReport.ts +28 -18
  527. package/src/report/api/isReportedByMe.ts +9 -2
  528. package/src/subChannel/api/createSubChannel.ts +41 -0
  529. package/src/subChannel/api/deleteSubChannel.ts +53 -0
  530. package/src/subChannel/api/getSubChannel.ts +85 -0
  531. package/src/subChannel/api/getSubChannels.ts +77 -0
  532. package/src/subChannel/api/index.ts +8 -0
  533. package/src/subChannel/api/querySubChannels.ts +115 -0
  534. package/src/subChannel/api/updateSubChannel.ts +43 -0
  535. package/src/subChannel/events/index.ts +3 -0
  536. package/src/subChannel/events/onSubChannelCreated.ts +32 -0
  537. package/src/subChannel/events/onSubChannelDeleted.ts +44 -0
  538. package/src/subChannel/events/onSubChannelFetched.ts +12 -0
  539. package/src/subChannel/events/onSubChannelUpdated.ts +32 -0
  540. package/src/subChannel/observers/index.ts +2 -0
  541. package/src/subChannel/observers/liveSubChannel.ts +84 -0
  542. package/src/subChannel/observers/liveSubChannels.ts +137 -0
  543. package/src/subChannel/observers/tests/liveSubChannel.test.ts +212 -0
  544. package/src/subChannel/observers/tests/liveSubChannels.test.ts +206 -0
  545. package/src/subChannel/utils/index.ts +50 -0
  546. package/src/user/events/index.ts +0 -1
  547. package/src/user/events/utils.ts +1 -1
  548. package/src/user/observers/liveUser.ts +29 -23
  549. package/src/user/tests/observers/liveUser.test.ts +5 -9
  550. package/src/utils/index.ts +52 -0
  551. package/src/utils/tests/dummy/channel.ts +128 -114
  552. package/src/utils/tests/dummy/community.ts +108 -0
  553. package/src/utils/tests/dummy/file.ts +20 -0
  554. package/src/utils/tests/dummy/follow.ts +6 -0
  555. package/src/utils/tests/dummy/index.ts +11 -0
  556. package/src/utils/tests/dummy/member.ts +18 -0
  557. package/src/utils/tests/dummy/message.ts +44 -16
  558. package/src/utils/tests/dummy/poll.ts +43 -0
  559. package/src/utils/tests/dummy/post.ts +73 -1
  560. package/src/utils/tests/dummy/reaction.ts +22 -0
  561. package/src/utils/tests/dummy/role.ts +21 -0
  562. package/src/utils/tests/dummy/subChannel.ts +29 -0
  563. package/src/utils/tests/dummy/user.ts +8 -0
  564. package/src/utils/tests/utils.ts +2 -0
  565. package/dist/channel/utils/prepareChannelPayload.d.ts +0 -3
  566. package/dist/channel/utils/prepareChannelPayload.d.ts.map +0 -1
  567. 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);
@@ -20395,7 +20396,7 @@ const getDeviceInfo = () => {
20395
20396
  * Ingest a payload (v3) into the cache
20396
20397
  *
20397
20398
  * @param payload a "backend v3" payload object
20398
- * @param order the order of the keys to process (in case of need)
20399
+ * @param options caching options like cachedAt or offline
20399
20400
  *
20400
20401
  * @category Cache
20401
20402
  * @hidden
@@ -20407,9 +20408,7 @@ const ingestInCache = (payload = {}, options) => {
20407
20408
  return;
20408
20409
  const resolver = getResolver(type);
20409
20410
  models.forEach(model => {
20410
- upsertInCache(
20411
- // eslint-disable @typescript-eslint no-explicit-any
20412
- [type, 'get', resolver(model)], // this 'any' cannot be avoided, sorry.
20411
+ upsertInCache([type, 'get', resolver(model)], // this 'any' cannot be avoided, sorry.
20413
20412
  model, options);
20414
20413
  });
20415
20414
  });
@@ -20573,9 +20572,8 @@ const connectClient = async (params, config) => {
20573
20572
  // @ts-ignore: in that particular case, typing can be
20574
20573
  // ignored since we enforce default values just before.
20575
20574
  const { accessToken, users } = await getToken(params);
20576
- // manually setup the token for http transport
20575
+ // manually setup the token for http, ws transport
20577
20576
  client.http.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
20578
- // manually setup the token for ws transport
20579
20577
  client.ws.io.opts.query = { token: accessToken };
20580
20578
  // FIXME: events are duplicated if connectClient is called few times without disconnectClient
20581
20579
  // wire websocket events to our event emitter
@@ -20591,6 +20589,9 @@ const connectClient = async (params, config) => {
20591
20589
  setActiveUser(users[0]);
20592
20590
  if ((config === null || config === void 0 ? void 0 : config.disableRTE) !== true) {
20593
20591
  subscribeTopic(getNetworkTopic());
20592
+ subscribeTopic(getSmartFeedChannelTopic());
20593
+ subscribeTopic(getSmartFeedSubChannelTopic());
20594
+ subscribeTopic(getSmartFeedMessageTopic());
20594
20595
  }
20595
20596
  const subscriptions = [
20596
20597
  onClientBanned(() => {
@@ -20943,23 +20944,6 @@ const updateUser = async (userId, patch) => {
20943
20944
  };
20944
20945
  };
20945
20946
 
20946
- /**
20947
- * ```js
20948
- * import { onUserFetched } from '@amityco/ts-sdk'
20949
- * const dispose = onUserFetched(user => {
20950
- * // ...
20951
- * })
20952
- * ```
20953
- *
20954
- * Fired when a {@link Amity.User} has been fetched
20955
- *
20956
- * @param callback The function to call when the event was fired
20957
- * @returns an {@link Amity.Unsubscriber} function to stop listening
20958
- *
20959
- * @category User Events
20960
- */
20961
- const onUserFetched = (callback) => createUserEventSubscriber('user.fetched', callback);
20962
-
20963
20947
  /**
20964
20948
  * ```js
20965
20949
  * import { onUserUpdated } from '@amityco/ts-sdk'
@@ -21037,52 +21021,72 @@ const UNSYNCED_OBJECT_CACHED_AT_VALUE = -5;
21037
21021
 
21038
21022
  /**
21039
21023
  * ```js
21040
- * 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';
21041
21042
  *
21042
- * let users = []
21043
- * const unsub = liveUser(userId, response => merge(users, response.data))
21043
+ * let user;
21044
+ *
21045
+ * const unsubscribe = liveUser(userId, response => {
21046
+ * user = response.data;
21047
+ * });
21044
21048
  * ```
21045
21049
  *
21046
21050
  * Observe all mutation on a given {@link Amity.User}
21047
21051
  *
21048
21052
  * @param userId the ID of the user to observe
21049
21053
  * @param callback the function to call when new data are available
21050
- * @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
21051
21055
  *
21052
21056
  * @category Message Live Object
21053
21057
  */
21054
21058
  const liveUser = (userId, callback) => {
21055
21059
  const { log, cache } = getActiveClient();
21056
- let user;
21060
+ const timestamp = Date.now();
21061
+ log(`liveUser(tmpid: ${timestamp}) > listen`);
21057
21062
  if (!cache) {
21058
21063
  console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
21059
21064
  }
21060
- const timestamp = Date.now();
21061
- log(`liveUser(tmpid: ${timestamp}) > listen`);
21065
+ let user;
21062
21066
  const disposers = [];
21063
21067
  const dispatcher = (data) => {
21064
- var _a;
21065
- // we check updatedAt to see if the current snapshot is new so
21066
- // we won't send old data back, only fresh new data
21067
- 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')
21068
- return;
21069
- callback(data);
21070
21068
  user = data.data;
21069
+ callback(data);
21071
21070
  };
21072
- const realtimeRouter = (user, action) => {
21073
- 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' });
21074
21079
  };
21075
21080
  const onFetch = () => {
21076
21081
  const query = createQuery(getUser, userId, true);
21077
21082
  runQuery(query, ({ loading, data, error, origin }) => {
21078
21083
  dispatcher({ loading, data, origin, error });
21079
21084
  if (error) {
21080
- // Terminate observe functionality on error
21081
21085
  disposers.forEach(fn => fn());
21082
21086
  }
21083
21087
  });
21084
21088
  };
21085
- 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));
21086
21090
  onFetch();
21087
21091
  return () => {
21088
21092
  log(`liveUser(tmpid: ${timestamp}) > dispose`);
@@ -21496,7 +21500,7 @@ getRole.locally = (roleId) => {
21496
21500
  const dispatchReactable = (referenceType, model) => {
21497
21501
  if (referenceType === 'message')
21498
21502
  // @ts-ignore: refactor later
21499
- fireEvent('v3.message.didUpdate', { messages: [model] });
21503
+ fireEvent('local.message.updated', { messages: [model] });
21500
21504
  else if (referenceType === 'post')
21501
21505
  // @ts-ignore: refactor later
21502
21506
  fireEvent('post.updated', { posts: [model] });
@@ -21505,6 +21509,100 @@ const dispatchReactable = (referenceType, model) => {
21505
21509
  fireEvent('comment.updated', { comments: [model] });
21506
21510
  };
21507
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
+
21508
21606
  /**
21509
21607
  * ```js
21510
21608
  * import { getMessage } from '@amityco/ts-sdk'
@@ -21529,7 +21627,9 @@ const getMessage = async (messageId, isLive = false) => {
21529
21627
  let data;
21530
21628
  try {
21531
21629
  // API-FIX: endpoint should not be /list, parameters should be querystring.
21532
- 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);
21533
21633
  data = response.data;
21534
21634
  }
21535
21635
  catch (error) {
@@ -21542,7 +21642,7 @@ const getMessage = async (messageId, isLive = false) => {
21542
21642
  if (client.cache)
21543
21643
  ingestInCache(data, { cachedAt });
21544
21644
  const { messages } = data;
21545
- fireEvent('v3.message.didFetch', { messages });
21645
+ fireEvent('local.message.fetched', { messages });
21546
21646
  return {
21547
21647
  data: messages.find(message => message.messageId === messageId),
21548
21648
  cachedAt,
@@ -21592,15 +21692,16 @@ getMessage.locally = (messageId) => {
21592
21692
  const getMessages = async (messageIds) => {
21593
21693
  const client = getActiveClient();
21594
21694
  client.log('message/getMessages', messageIds);
21595
- // API-FIX: endpoint should not be /list, parameters should be querystring.
21596
- const { data } = await client.http.get(`/api/v3/messages/list`, {
21597
- params: { messageIds },
21598
- });
21695
+ const { data } = await client.http
21696
+ .get(`/api/v5/messages/list`, {
21697
+ params: { messageIds: messageIds.map(encodeURIComponent) },
21698
+ })
21699
+ .then(convertResponseFromRaw);
21599
21700
  const cachedAt = client.cache && Date.now();
21600
21701
  if (client.cache)
21601
21702
  ingestInCache(data, { cachedAt });
21602
21703
  const { messages } = data;
21603
- fireEvent('v3.message.didFetch', { messages });
21704
+ fireEvent('local.message.fetched', { messages });
21604
21705
  return {
21605
21706
  data: messages,
21606
21707
  cachedAt,
@@ -21655,31 +21756,25 @@ getMessages.locally = (messageIds) => {
21655
21756
  const queryMessages = async (query) => {
21656
21757
  const client = getActiveClient();
21657
21758
  client.log('message/queryMessages', query);
21658
- const { page = { limit: 10 } } = query, params = __rest(query, ["page"]);
21759
+ const params = convertQueryParams$1(query);
21659
21760
  // API-FIX: parameters should be querystring. (1)
21660
21761
  // API-FIX: backend should answer Amity.Response (2)
21661
21762
  // API-FIX: pagination should not be indexed on channelSegment (3)
21662
21763
  // const { data } = await client.http.get<Amity.Response<Amity.Paged<Amity.MessagePayload>>>(
21663
- const { data } = await client.http.get(`/api/v3/messages`, {
21664
- params: Object.assign(Object.assign({}, params), { options: {
21665
- token: toToken(page, 'afterbefore'),
21666
- } }),
21667
- });
21764
+ const response = await client.http
21765
+ .get(`/api/v5/messages`, { params })
21766
+ .then(convertResponseFromRaw);
21668
21767
  // API-FIX: backend should answer Amity.Response (2)
21669
21768
  // const { paging, messages } = unwrapPayload(data)
21670
- const { paging } = data, payload = __rest(data, ["paging"]);
21671
- const { messages } = payload;
21769
+ const _a = response.data, { paging } = _a, data = __rest(_a, ["paging"]);
21770
+ const { messages } = data;
21672
21771
  const cachedAt = client.cache && Date.now();
21673
21772
  if (client.cache) {
21674
- ingestInCache(payload, { cachedAt });
21675
- const cacheKey = [
21676
- 'message',
21677
- 'query',
21678
- Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
21679
- ];
21773
+ ingestInCache(data, { cachedAt });
21774
+ const cacheKey = ['message', 'query', params];
21680
21775
  pushToCache(cacheKey, { messages: messages.map(getResolver('message')), paging });
21681
21776
  }
21682
- fireEvent('v3.message.didFetch', { messages });
21777
+ fireEvent('local.message.fetched', { messages });
21683
21778
  const nextPage = toPage(paging.next);
21684
21779
  const prevPage = toPage(paging.previous);
21685
21780
  return { data: messages, cachedAt, prevPage, nextPage };
@@ -21703,8 +21798,8 @@ queryMessages.locally = (query) => {
21703
21798
  client.log('message/queryMessages.locally', query);
21704
21799
  if (!client.cache)
21705
21800
  return;
21706
- const { page = { limit: 10 } } = query, params = __rest(query, ["page"]);
21707
- 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];
21708
21803
  const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
21709
21804
  if (!(data === null || data === void 0 ? void 0 : data.messages.length))
21710
21805
  return;
@@ -21721,13 +21816,20 @@ queryMessages.locally = (query) => {
21721
21816
 
21722
21817
  const uuid = () => nativeIdGenerator.v4().toString();
21723
21818
 
21819
+ // FIXME: temp solution
21820
+ let uniqueId;
21724
21821
  /**
21725
21822
  * ```js
21726
- * import { createMessage } from '@amityco/ts-sdk'
21727
- * const created = await createMessage({
21728
- * channelId: 'foobar',
21729
- * data: { text: 'hello world' }
21730
- * })
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
+ * });
21731
21833
  * ```
21732
21834
  *
21733
21835
  * Creates an {@link Amity.Message}
@@ -21740,13 +21842,19 @@ const uuid = () => nativeIdGenerator.v4().toString();
21740
21842
  */
21741
21843
  const createMessage = async (bundle) => {
21742
21844
  const client = getActiveClient();
21743
- client.log('user/createMessage', bundle);
21744
- 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);
21745
21851
  const cachedAt = client.cache && Date.now();
21746
- if (client.cache)
21852
+ if (client.cache) {
21853
+ dropFromCache(['message', 'get', referenceId]);
21747
21854
  ingestInCache(data, { cachedAt });
21855
+ }
21748
21856
  const { messages } = data;
21749
- fireEvent('v3.message.didCreate', { messages });
21857
+ fireEvent('local.message.created', { messages });
21750
21858
  return {
21751
21859
  data: messages[0],
21752
21860
  cachedAt,
@@ -21755,7 +21863,8 @@ const createMessage = async (bundle) => {
21755
21863
  /**
21756
21864
  * ```js
21757
21865
  * import { createMessage } from '@amityco/ts-sdk'
21758
- * const created = createMessage.locally({
21866
+ *
21867
+ * const created = createMessage.optimistically({
21759
21868
  * channelId: 'foobar',
21760
21869
  * data: { text: 'hello world' }
21761
21870
  * })
@@ -21780,17 +21889,26 @@ createMessage.optimistically = (bundle) => {
21780
21889
  * Updated to handle client requirement to add messageId while uploading
21781
21890
  * message with image. Temporary!
21782
21891
  */
21783
- const bundleWithMessageId = Object.assign({ messageId: uuid() }, bundle);
21784
- // only log if cache is enabled
21785
- client.log('user/createMessage.locally', bundleWithMessageId);
21786
- const channel = pullFromCache(['channel', 'get', bundleWithMessageId.channelId]);
21787
- 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
+ }
21788
21906
  // as reused to update created and updated time, which should be the same
21789
21907
  const createdTime = new Date().toISOString();
21790
- 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);
21791
21909
  const cachedAt = UNSYNCED_OBJECT_CACHED_AT_VALUE;
21792
21910
  pushToCache(['message', 'get', message.messageId], message, { cachedAt });
21793
- fireEvent('v3.message.didCreate', { messages: [message] });
21911
+ fireEvent('local.message.created', { messages: [message] });
21794
21912
  return {
21795
21913
  cachedAt,
21796
21914
  data: message,
@@ -21816,13 +21934,15 @@ createMessage.optimistically = (bundle) => {
21816
21934
  */
21817
21935
  const updateMessage = async (messageId, patch) => {
21818
21936
  const client = getActiveClient();
21819
- client.log('user/updateMessage', patch);
21820
- 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);
21821
21941
  const cachedAt = client.cache && Date.now();
21822
21942
  if (client.cache)
21823
21943
  ingestInCache(data, { cachedAt });
21824
21944
  const { messages } = data;
21825
- fireEvent('v3.message.didUpdate', { messages });
21945
+ fireEvent('local.message.updated', { messages });
21826
21946
  return {
21827
21947
  data: messages.find(message => message.messageId === messageId),
21828
21948
  cachedAt,
@@ -21831,7 +21951,7 @@ const updateMessage = async (messageId, patch) => {
21831
21951
  /**
21832
21952
  * ```js
21833
21953
  * import { updateMessage } from '@amityco/ts-sdk'
21834
- * const updated = updateMessage.locally('foobar', {
21954
+ * const updated = updateMessage.optimistically('foobar', {
21835
21955
  * data: { text: 'hello world' }
21836
21956
  * })
21837
21957
  * ```
@@ -21846,7 +21966,7 @@ const updateMessage = async (messageId, patch) => {
21846
21966
  */
21847
21967
  updateMessage.optimistically = (messageId, patch) => {
21848
21968
  const client = getActiveClient();
21849
- client.log('user/updateMessage', patch);
21969
+ client.log('message/updateMessage.optimistically', patch);
21850
21970
  if (!client.cache)
21851
21971
  return;
21852
21972
  const message = pullFromCache(['message', 'get', messageId]);
@@ -21855,7 +21975,7 @@ updateMessage.optimistically = (messageId, patch) => {
21855
21975
  const cachedAt = -1;
21856
21976
  const updated = Object.assign(Object.assign(Object.assign({}, message.data), patch), { updatedAt: new Date().toISOString() });
21857
21977
  upsertInCache(['message', 'get', messageId], updated, { cachedAt });
21858
- fireEvent('v3.message.didUpdate', { messages: [updated] });
21978
+ fireEvent('local.message.updated', { messages: [updated] });
21859
21979
  return {
21860
21980
  data: updated,
21861
21981
  cachedAt,
@@ -21870,7 +21990,7 @@ updateMessage.optimistically = (messageId, patch) => {
21870
21990
  *
21871
21991
  * Delete a {@link Amity.Message}
21872
21992
  *
21873
- * @param The ID of the {@link Amity.Message} to delete
21993
+ * @param messageId the ID of the {@link Amity.Message} to delete
21874
21994
  * @return A success boolean if the {@link Amity.Message} was deleted
21875
21995
  *
21876
21996
  * @category Message API
@@ -21880,15 +22000,15 @@ const deleteMessage = async (messageId) => {
21880
22000
  const client = getActiveClient();
21881
22001
  client.log('message/deleteMessage', messageId);
21882
22002
  // API-FIX: This endpoint has not been implemented yet.
21883
- await client.http.delete(`/api/v3/messages/${encodeURIComponent(messageId)}`);
22003
+ await client.http.delete(`/api/v5/messages/${encodeURIComponent(messageId)}`);
21884
22004
  const deleted = await getMessage(messageId);
21885
- fireEvent('v3.message.didDelete', { messages: [deleted.data] });
22005
+ fireEvent('local.message.deleted', { messages: [deleted.data] });
21886
22006
  return deleted.data;
21887
22007
  };
21888
22008
  /**
21889
22009
  * ```js
21890
22010
  * import { deleteMessage } from '@amityco/ts-sdk'
21891
- * const success = deleteMessage.locally('foobar')
22011
+ * const success = deleteMessage.optimistically('foobar')
21892
22012
  * ```
21893
22013
  *
21894
22014
  * Deletes a {@link Amity.Message}
@@ -21900,14 +22020,14 @@ const deleteMessage = async (messageId) => {
21900
22020
  */
21901
22021
  deleteMessage.optimistically = (messageId) => {
21902
22022
  const client = getActiveClient();
21903
- client.log('message/deleteMessage', messageId);
22023
+ client.log('message/deleteMessage.optimistically', messageId);
21904
22024
  const message = pullFromCache(['message', 'get', messageId]);
21905
22025
  if (!message)
21906
22026
  return;
21907
22027
  const cachedAt = -1;
21908
22028
  const deleted = Object.assign(Object.assign({}, message.data), { isDeleted: true, updatedAt: new Date().toISOString() });
21909
22029
  upsertInCache(['message', 'get', messageId], deleted, { cachedAt });
21910
- fireEvent('v3.message.didDelete', { messages: [deleted] });
22030
+ fireEvent('local.message.deleted', { messages: [deleted] });
21911
22031
  return {
21912
22032
  data: deleted,
21913
22033
  cachedAt,
@@ -21932,11 +22052,20 @@ const queryPosts = async (query) => {
21932
22052
  const client = getActiveClient();
21933
22053
  client.log('post/queryPosts', query);
21934
22054
  const { page = { limit: 10 } } = query, params = __rest(query, ["page"]);
22055
+ const { dataTypes, matchingOnlyParentPost } = params;
21935
22056
  // API-FIX: parameters should be querystring. (1)
21936
22057
  // API-FIX: backend should answer Amity.Response (2)
21937
22058
  // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.PostPayload>>>(
21938
22059
  const { data } = await client.http.get(`/api/v4/posts`, {
21939
- 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: {
21940
22069
  token: toToken(page, 'afterbeforeraw'),
21941
22070
  } }),
21942
22071
  });
@@ -22234,12 +22363,13 @@ const queryCommunities = async (query) => {
22234
22363
  const client = getActiveClient();
22235
22364
  client.log('channel/queryCommunities', query);
22236
22365
  // safe decapsulation
22237
- 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"]);
22238
22368
  // API-FIX: parameters should be querystring.
22239
22369
  // API-FIX: backend doesnt answer Amity.Response
22240
22370
  // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<CommunityPayload>>>(
22241
22371
  const { data } = await client.http.get(`/api/v3/communities`, {
22242
- params: Object.assign(Object.assign({}, params), { keyword: displayName, filter: membership, options: {
22372
+ params: Object.assign(Object.assign({}, restParams), { keyword: displayName, filter: membership, options: {
22243
22373
  token: toToken(page, 'skiplimit'),
22244
22374
  } }),
22245
22375
  });
@@ -22534,6 +22664,58 @@ const leaveCommunity = async (communityId) => {
22534
22664
  return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership !== 'member');
22535
22665
  };
22536
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
+
22537
22719
  /**
22538
22720
  * ```js
22539
22721
  * import { queryCommunityMembers } from '@amityco/ts-sdk'
@@ -22551,17 +22733,27 @@ const leaveCommunity = async (communityId) => {
22551
22733
  const queryCommunityMembers = async (query) => {
22552
22734
  const client = getActiveClient();
22553
22735
  client.log('community/queryCommunityMembers', query);
22554
- const _a = query !== null && query !== void 0 ? query : {}, { page, communityId } = _a, params = __rest(_a, ["page", "communityId"]);
22555
- 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`, {
22556
22738
  params: Object.assign(Object.assign({}, params), { options: {
22557
22739
  token: toToken(page, 'skiplimit'),
22558
22740
  } }),
22559
22741
  });
22560
- const { paging } = data, payload = __rest(data, ["paging"]);
22561
- const { communityUsers } = payload;
22742
+ const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
22743
+ const preparedPayload = prepareMembershipPayload(payload, 'communityUsers');
22744
+ const { communityUsers } = preparedPayload;
22562
22745
  const cachedAt = client.cache && Date.now();
22563
22746
  if (client.cache) {
22564
- 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
+ });
22565
22757
  }
22566
22758
  const nextPage = toPage(paging.next);
22567
22759
  const prevPage = toPage(paging.previous);
@@ -22581,9 +22773,29 @@ const queryCommunityMembers = async (query) => {
22581
22773
  * @category Post API
22582
22774
  */
22583
22775
  queryCommunityMembers.locally = (query) => {
22776
+ var _a, _b;
22584
22777
  const client = getActiveClient();
22585
22778
  client.log('community/queryCommunityMembers', query);
22586
- // 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;
22587
22799
  };
22588
22800
 
22589
22801
  /**
@@ -23292,38 +23504,6 @@ const preparePayloadForCache = (event, payload) => {
23292
23504
  }
23293
23505
  };
23294
23506
 
23295
- /** @hidden */
23296
- /*
23297
- * @param message payload from http request without myReactions
23298
- * add myReactions to http response if the event was a reaction event
23299
- */
23300
- const prepareMessagePayloadForCache = (payload) => {
23301
- const client = getActiveClient();
23302
- const cached = pullFromCache(['message', 'get', payload.messageId]);
23303
- // '[]' in cases where the new reaction is the first one
23304
- const myReactions = (cached === null || cached === void 0 ? void 0 : cached.data.myReactions) || [];
23305
- // add myReactions to the payload
23306
- Object.assign(payload, { myReactions });
23307
- // check if there are any updates to the reactions
23308
- const latestReaction = payload === null || payload === void 0 ? void 0 : payload.latestReaction;
23309
- const isLatestReactionMine = latestReaction && latestReaction.userId === client.userId;
23310
- if (!isLatestReactionMine) {
23311
- return;
23312
- }
23313
- // new reaction added
23314
- if (latestReaction.eventName === 'add' && !myReactions.includes(latestReaction.reactionName)) {
23315
- Object.assign(payload, {
23316
- myReactions: [...myReactions, latestReaction.reactionName],
23317
- });
23318
- }
23319
- // existing reaction removed
23320
- if (latestReaction.eventName === 'remove' && myReactions.includes(latestReaction.reactionName)) {
23321
- Object.assign(payload, {
23322
- myReactions: myReactions.filter(x => x !== latestReaction.reactionName),
23323
- });
23324
- }
23325
- };
23326
-
23327
23507
  /**
23328
23508
  * ```js
23329
23509
  * import { addReaction } from '@amityco/ts-sdk'
@@ -23351,7 +23531,17 @@ const addReaction = async (referenceType, referenceId, reactionName) => {
23351
23531
  referenceId,
23352
23532
  referenceType,
23353
23533
  reactionName,
23534
+ referenceVersion: referenceType === 'message' ? 5 : undefined,
23354
23535
  });
23536
+ if (client.cache) {
23537
+ const model = pullFromCache([
23538
+ referenceType,
23539
+ 'get',
23540
+ referenceId,
23541
+ ]);
23542
+ (model === null || model === void 0 ? void 0 : model.data) &&
23543
+ pushToCache([referenceType, 'get', referenceId], model.data, { cachedAt: Date.now() });
23544
+ }
23355
23545
  return true;
23356
23546
  };
23357
23547
  /**
@@ -23387,7 +23577,9 @@ addReaction.optimistically = (referenceType, referenceId, reactionName) => {
23387
23577
  if (!(model === null || model === void 0 ? void 0 : model.data) || ((_a = model.data.myReactions) === null || _a === void 0 ? void 0 : _a.includes(reactionName)))
23388
23578
  return;
23389
23579
  const reaction = Object.assign(Object.assign({}, model.data), { reactionsCount: model.data.reactionsCount + 1, myReactions: [...((_b = model.data.myReactions) !== null && _b !== void 0 ? _b : []), reactionName], reactions: Object.assign(Object.assign({}, model.data.reactions), { [reactionName]: ((_c = model.data.reactions[reactionName]) !== null && _c !== void 0 ? _c : 0) + 1 }) });
23390
- upsertInCache([referenceType, 'get', referenceId], reaction, { cachedAt: -1 });
23580
+ upsertInCache([referenceType, 'get', referenceId], reaction, {
23581
+ cachedAt: UNSYNCED_OBJECT_CACHED_AT_VALUE,
23582
+ });
23391
23583
  dispatchReactable(referenceType, reaction);
23392
23584
  return (_e = (_d = reaction === null || reaction === void 0 ? void 0 : reaction.myReactions) === null || _d === void 0 ? void 0 : _d.includes(reactionName)) !== null && _e !== void 0 ? _e : false;
23393
23585
  };
@@ -23416,8 +23608,22 @@ const removeReaction = async (referenceType, referenceId, reactionName) => {
23416
23608
  reactionName,
23417
23609
  });
23418
23610
  await client.http.delete(`/api/v2/reactions`, {
23419
- data: { referenceId, referenceType, reactionName },
23611
+ data: {
23612
+ referenceId,
23613
+ referenceType,
23614
+ reactionName,
23615
+ referenceVersion: referenceType === 'message' ? 5 : undefined,
23616
+ },
23420
23617
  });
23618
+ if (client.cache) {
23619
+ const model = pullFromCache([
23620
+ referenceType,
23621
+ 'get',
23622
+ referenceId,
23623
+ ]);
23624
+ (model === null || model === void 0 ? void 0 : model.data) &&
23625
+ pushToCache([referenceType, 'get', referenceId], model.data, { cachedAt: Date.now() });
23626
+ }
23421
23627
  return true;
23422
23628
  };
23423
23629
  /**
@@ -23453,7 +23659,9 @@ removeReaction.optimistically = (referenceType, referenceId, reactionName) => {
23453
23659
  if (!(model === null || model === void 0 ? void 0 : model.data) || !((_a = model.data.myReactions) === null || _a === void 0 ? void 0 : _a.includes(reactionName)))
23454
23660
  return;
23455
23661
  const reaction = Object.assign(Object.assign({}, model.data), { reactionsCount: Math.max(0, model.data.reactionsCount - 1), myReactions: ((_b = model.data.myReactions) !== null && _b !== void 0 ? _b : []).filter(item => item !== reactionName), reactions: Object.assign(Object.assign({}, model.data.reactions), { [reactionName]: Math.max(0, ((_c = model.data.reactions[reactionName]) !== null && _c !== void 0 ? _c : 0) - 1) }) });
23456
- upsertInCache([referenceType, 'get', referenceId], reaction, { cachedAt: -1 });
23662
+ upsertInCache([referenceType, 'get', referenceId], reaction, {
23663
+ cachedAt: UNSYNCED_OBJECT_CACHED_AT_VALUE,
23664
+ });
23457
23665
  dispatchReactable(referenceType, reaction);
23458
23666
  return (_e = !((_d = reaction === null || reaction === void 0 ? void 0 : reaction.myReactions) === null || _d === void 0 ? void 0 : _d.includes(reactionName))) !== null && _e !== void 0 ? _e : false;
23459
23667
  };
@@ -23918,8 +24126,9 @@ const onReactionAdded = (referenceType, referenceId, callback) => {
23918
24126
  */
23919
24127
  if (referenceType === 'message') {
23920
24128
  const client = getActiveClient();
23921
- const filter = (payload) => {
24129
+ const filter = (rawPayload) => {
23922
24130
  var _a;
24131
+ const payload = prepareMessagePayload(rawPayload);
23923
24132
  const cached = pullFromCache([
23924
24133
  'message',
23925
24134
  'get',
@@ -23931,7 +24140,7 @@ const onReactionAdded = (referenceType, referenceId, callback) => {
23931
24140
  callbackWrapper(payload.messages[0]);
23932
24141
  }
23933
24142
  };
23934
- return createEventSubscriber(client, 'reaction/onReactionAdded', 'v3.message.didUpdate', filter);
24143
+ return createEventSubscriber(client, 'reaction/onReactionAdded', 'message.updated', filter);
23935
24144
  }
23936
24145
  if (referenceType === 'post') {
23937
24146
  return onPostReactionAdded(callbackWrapper);
@@ -23964,8 +24173,9 @@ const onReactionRemoved = (referenceType, referenceId, callback) => {
23964
24173
  };
23965
24174
  if (referenceType === 'message') {
23966
24175
  const client = getActiveClient();
23967
- const filter = (payload) => {
24176
+ const filter = (rawPayload) => {
23968
24177
  var _a;
24178
+ const payload = prepareMessagePayload(rawPayload);
23969
24179
  const cached = pullFromCache([
23970
24180
  'message',
23971
24181
  'get',
@@ -23977,7 +24187,7 @@ const onReactionRemoved = (referenceType, referenceId, callback) => {
23977
24187
  callbackWrapper(payload.messages[0]);
23978
24188
  }
23979
24189
  };
23980
- return createEventSubscriber(client, 'reaction/onReactionRemoved', 'v3.message.didUpdate', filter);
24190
+ return createEventSubscriber(client, 'reaction/onReactionRemoved', 'message.updated', filter);
23981
24191
  }
23982
24192
  if (referenceType === 'post') {
23983
24193
  return onPostReactionRemoved(callbackWrapper);
@@ -24010,7 +24220,8 @@ const onReactorAdded = (referenceType, referenceId, callback) => {
24010
24220
  }
24011
24221
  };
24012
24222
  if (referenceType === 'message') {
24013
- const filter = (payload) => {
24223
+ const filter = (rawPayload) => {
24224
+ const payload = prepareMessagePayload(rawPayload);
24014
24225
  if (!payload.messages[0].latestReaction)
24015
24226
  return;
24016
24227
  const _a = payload.messages[0].latestReaction, { eventName, referenceId, referenceType, userDisplayName } = _a, reactor = __rest(_a, ["eventName", "referenceId", "referenceType", "userDisplayName"]);
@@ -24020,7 +24231,7 @@ const onReactorAdded = (referenceType, referenceId, callback) => {
24020
24231
  ingestInCache({ reactions: [reactor] });
24021
24232
  callbackWrapper('message', payload.messages[0].messageId, reactor);
24022
24233
  };
24023
- return createEventSubscriber(client, 'reaction/onReactorAdded', 'v3.message.didUpdate', filter);
24234
+ return createEventSubscriber(client, 'reaction/onReactorAdded', 'message.updated', filter);
24024
24235
  }
24025
24236
  if (referenceType === 'post') {
24026
24237
  const filter = (payload) => {
@@ -24065,7 +24276,8 @@ const onReactorRemoved = (referenceType, referenceId, callback) => {
24065
24276
  }
24066
24277
  };
24067
24278
  if (referenceType === 'message') {
24068
- const filter = (payload) => {
24279
+ const filter = (rawPayload) => {
24280
+ const payload = prepareMessagePayload(rawPayload);
24069
24281
  if (!payload.messages[0].latestReaction)
24070
24282
  return;
24071
24283
  const _a = payload.messages[0].latestReaction, { eventName, referenceId, referenceType } = _a, reactor = __rest(_a, ["eventName", "referenceId", "referenceType"]);
@@ -24075,7 +24287,7 @@ const onReactorRemoved = (referenceType, referenceId, callback) => {
24075
24287
  ingestInCache({ reactions: [reactor] });
24076
24288
  callbackWrapper('message', payload.messages[0].messageId, reactor);
24077
24289
  };
24078
- return createEventSubscriber(client, 'reaction/onReactorRemoved', 'v3.message.didUpdate', filter);
24290
+ return createEventSubscriber(client, 'reaction/onReactorRemoved', 'message.updated', filter);
24079
24291
  }
24080
24292
  if (referenceType === 'post') {
24081
24293
  const filter = (payload) => {
@@ -24145,7 +24357,7 @@ const liveReactions = (params, callback, config) => {
24145
24357
  error: data.error,
24146
24358
  });
24147
24359
  };
24148
- const realtimeRouter = (reaction, action) => {
24360
+ const realtimeRouter = (action) => (reaction) => {
24149
24361
  var _a;
24150
24362
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24151
24363
  if (!collection)
@@ -24182,7 +24394,7 @@ const liveReactions = (params, callback, config) => {
24182
24394
  responder(data);
24183
24395
  }, queryOptions(policy));
24184
24396
  };
24185
- 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')));
24186
24398
  onFetch();
24187
24399
  return () => {
24188
24400
  log(`liveReactions(tmpid: ${timestamp}) > dispose`);
@@ -24229,18 +24441,28 @@ var REFERENCE_TYPES = {
24229
24441
  const createReport = async (referenceType, referenceId) => {
24230
24442
  const client = getActiveClient();
24231
24443
  client.log('report/createReport', { referenceType, referenceId });
24232
- const { domainName } = REFERENCE_TYPES[referenceType];
24233
- const { data } = await client.http.post(`/api/${referenceType === 'user'
24234
- ? `v4/me/flags/${encodeURIComponent(referenceId)}`
24235
- : `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());
24236
24455
  if (client.cache)
24237
- ingestInCache(data);
24238
- const event = referenceType === 'message'
24239
- ? 'v3.message.didUpdate'
24240
- : `${referenceType}.flagged`;
24241
- fireEvent(event, data);
24242
- return !!data;
24243
- };
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
+ }
24464
+ return !!data;
24465
+ };
24244
24466
 
24245
24467
  /**
24246
24468
  * ```js
@@ -24258,16 +24480,26 @@ const createReport = async (referenceType, referenceId) => {
24258
24480
  const deleteReport = async (referenceType, referenceId) => {
24259
24481
  const client = getActiveClient();
24260
24482
  client.log('report/deleteReport', { referenceType, referenceId });
24261
- const { domainName } = REFERENCE_TYPES[referenceType];
24262
- const { data } = await client.http.delete(`/api/${referenceType === 'user'
24263
- ? `v4/me/flags/${encodeURIComponent(referenceId)}`
24264
- : `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());
24265
24494
  if (client.cache)
24266
- ingestInCache(data);
24267
- const event = referenceType === 'message'
24268
- ? 'v3.message.didUpdate'
24269
- : `${referenceType}.unflagged`;
24270
- fireEvent(event, 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
+ }
24271
24503
  return !!data;
24272
24504
  };
24273
24505
 
@@ -24289,26 +24521,45 @@ const isReportedByMe = async (referenceType, referenceId) => {
24289
24521
  const client = getActiveClient();
24290
24522
  client.log('report/isReportedByMe', { referenceType, referenceId });
24291
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
+ }
24292
24528
  const { result, isFlagByMe } = (_a = (await synchronousWSCall(client, eventName, {
24293
24529
  [primaryKey]: referenceId,
24294
24530
  }))) !== null && _a !== void 0 ? _a : {};
24295
24531
  return (_b = result !== null && result !== void 0 ? result : isFlagByMe) !== null && _b !== void 0 ? _b : false;
24296
24532
  };
24297
24533
 
24298
- /** @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
+ }
24299
24561
  const prepareChannelPayload = (payload) => {
24300
- const client = getActiveClient();
24301
- const channels = payload.channels.map(channel => {
24302
- const channelUser = payload.channelUsers.find(channelUser => channelUser.userId === client.userId && channel.channelId === channelUser.channelId);
24303
- const hasMention = channelUser
24304
- ? channelUser.readToSegment < channelUser.lastMentionedSegment
24305
- : false;
24306
- const unreadCount = channelUser && channelUser.membership === 'member' && channel.messageCount
24307
- ? Math.max(0, channel.messageCount - channelUser.readToSegment)
24308
- : 0;
24309
- return Object.assign(Object.assign({}, channel), { hasMention,
24310
- unreadCount });
24311
- });
24562
+ const channels = payload.channels.map(channel => convertFromRaw$1(channel, getSegmentParams(channel)));
24312
24563
  return Object.assign(Object.assign({}, payload), { channels });
24313
24564
  };
24314
24565
 
@@ -24444,10 +24695,10 @@ getChannels.locally = (channelIds) => {
24444
24695
  const cached = channelIds
24445
24696
  .map(channelId => pullFromCache(['channel', 'get', channelId]))
24446
24697
  .filter(Boolean);
24447
- const channels = cached.map(({ data }) => data);
24448
- const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
24449
24698
  if ((cached === null || cached === void 0 ? void 0 : cached.length) < channelIds.length)
24450
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];
24451
24702
  return {
24452
24703
  data: channels,
24453
24704
  cachedAt: oldest.cachedAt,
@@ -24522,7 +24773,7 @@ getChannel.locally = (channelId) => {
24522
24773
  /**
24523
24774
  * ```js
24524
24775
  * import { createChannel } from '@amityco/ts-sdk'
24525
- * const created = await createChannel({ channelId: 'foobar', displayName: 'foobar' })
24776
+ * const created = await createChannel({ displayName: 'foobar' })
24526
24777
  * ```
24527
24778
  *
24528
24779
  * Creates an {@link Amity.Channel}
@@ -24674,18 +24925,19 @@ const leaveChannel = async (channelId) => {
24674
24925
  const queryChannelMembers = async (query) => {
24675
24926
  const client = getActiveClient();
24676
24927
  client.log('channel/queryChannelMembers', query);
24677
- 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"]);
24678
24929
  const { data: queryPayload } = await client.http.get(`/api/v4/channels/${encodeURIComponent(params.channelId)}/users`, {
24679
24930
  params: Object.assign(Object.assign({}, params), { options: {
24680
24931
  token: toToken(page, 'skiplimit'),
24681
24932
  } }),
24682
24933
  });
24683
24934
  const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
24684
- const data = prepareChannelPayload(payload);
24685
- const { channelUsers } = data;
24935
+ const channelPayload = prepareChannelPayload(payload);
24936
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
24937
+ const { channelUsers } = preparedPayload;
24686
24938
  const cachedAt = client.cache && Date.now();
24687
24939
  if (client.cache) {
24688
- ingestInCache(data);
24940
+ ingestInCache(preparedPayload);
24689
24941
  const cacheKey = [
24690
24942
  'channelUsers',
24691
24943
  'query',
@@ -24698,7 +24950,12 @@ const queryChannelMembers = async (query) => {
24698
24950
  }
24699
24951
  const nextPage = toPage(paging.next);
24700
24952
  const prevPage = toPage(paging.previous);
24701
- return { data: channelUsers, cachedAt, nextPage, prevPage };
24953
+ return {
24954
+ data: channelUsers,
24955
+ cachedAt,
24956
+ nextPage,
24957
+ prevPage,
24958
+ };
24702
24959
  };
24703
24960
  /**
24704
24961
  * ```js
@@ -24719,7 +24976,7 @@ queryChannelMembers.locally = (query) => {
24719
24976
  client.log('channel/queryChannelMembers.locally', query);
24720
24977
  if (!client.cache)
24721
24978
  return;
24722
- const { page = { limit: 10 } } = query, params = __rest(query, ["page"]);
24979
+ const { page } = query, params = __rest(query, ["page"]);
24723
24980
  const cacheKey = [
24724
24981
  'channelUsers',
24725
24982
  'query',
@@ -24765,7 +25022,7 @@ const addChannelMembers = async (channelId, userIds) => {
24765
25022
  /*
24766
25023
  * should fire event for each user that was added
24767
25024
  */
24768
- 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) })));
24769
25026
  const { channelUsers } = data;
24770
25027
  return !!channelUsers.find(channelUser => channelUser.channelId === channelId && channelUser.membership === 'member');
24771
25028
  };
@@ -24792,7 +25049,10 @@ const removeChannelMembers = async (channelId, userIds) => {
24792
25049
  const data = prepareChannelPayload(payload);
24793
25050
  if (client.cache)
24794
25051
  ingestInCache(data);
24795
- 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) })));
24796
25056
  const { channelUsers } = data;
24797
25057
  return !!channelUsers.find(channelUser => channelUser.channelId === channelId && channelUser.membership !== 'member');
24798
25058
  };
@@ -24871,11 +25131,12 @@ const banChannelMembers = async (channelId, userIds) => {
24871
25131
  const { data: payload } = await client.http.put(`/api/v3/channels/${channelId}/users/ban`, {
24872
25132
  userIds,
24873
25133
  });
24874
- const data = prepareChannelPayload(payload);
25134
+ const channelPayload = prepareChannelPayload(payload);
25135
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25136
+ const { channelUsers } = preparedPayload;
24875
25137
  const cachedAt = client.cache && Date.now();
24876
25138
  if (client.cache)
24877
- ingestInCache(data, { cachedAt });
24878
- const { channelUsers } = data;
25139
+ ingestInCache(preparedPayload, { cachedAt });
24879
25140
  return {
24880
25141
  data: channelUsers === null || channelUsers === void 0 ? void 0 : channelUsers.filter(user => user.membership === 'banned'),
24881
25142
  cachedAt,
@@ -24902,17 +25163,92 @@ const unbanChannelMembers = async (channelId, userIds) => {
24902
25163
  const { data: payload } = await client.http.put(`/api/v3/channels/${encodeURIComponent(channelId)}/users/unban`, {
24903
25164
  userIds,
24904
25165
  });
24905
- const data = prepareChannelPayload(payload);
25166
+ const channelPayload = prepareChannelPayload(payload);
25167
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
24906
25168
  const cachedAt = client.cache && Date.now();
24907
25169
  if (client.cache)
24908
- ingestInCache(data, { cachedAt });
24909
- const { channelUsers } = data;
25170
+ ingestInCache(preparedPayload, { cachedAt });
25171
+ const { channelUsers } = preparedPayload;
24910
25172
  return {
24911
25173
  data: channelUsers === null || channelUsers === void 0 ? void 0 : channelUsers.filter(user => user.membership === 'member'),
24912
25174
  cachedAt,
24913
25175
  };
24914
25176
  };
24915
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
+
24916
25252
  /**
24917
25253
  * ```js
24918
25254
  * import { onChannelCreated } from '@amityco/ts-sdk'
@@ -24935,7 +25271,7 @@ const onChannelCreated = (callback) => {
24935
25271
  ingestInCache(data);
24936
25272
  callback(data.channels[0]);
24937
25273
  };
24938
- return createEventSubscriber(client, 'onChannelCreated', 'v3.channel.didCreate', filter);
25274
+ return createEventSubscriber(client, 'onChannelCreated', 'channel.created', filter);
24939
25275
  };
24940
25276
 
24941
25277
  /**
@@ -24960,7 +25296,13 @@ const onChannelUpdated = (callback) => {
24960
25296
  ingestInCache(data);
24961
25297
  callback(data.channels[0]);
24962
25298
  };
24963
- 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
+ };
24964
25306
  };
24965
25307
 
24966
25308
  /**
@@ -24985,13 +25327,13 @@ const onChannelDeleted = (callback) => {
24985
25327
  ingestInCache(data);
24986
25328
  callback(data.channels[0]);
24987
25329
  };
24988
- return createEventSubscriber(client, 'onChannelDeleted', 'v3.channel.didDelete', filter);
25330
+ return createEventSubscriber(client, 'onChannelDeleted', 'channel.deleted', filter);
24989
25331
  };
24990
25332
 
24991
25333
  /**
24992
25334
  * ```js
24993
25335
  * import { onChannelJoined } from '@amityco/ts-sdk'
24994
- * const dispose = onChannelJoined(channel => {
25336
+ * const dispose = onChannelJoined((channel, member) => {
24995
25337
  * // ...
24996
25338
  * })
24997
25339
  * ```
@@ -25006,17 +25348,19 @@ const onChannelDeleted = (callback) => {
25006
25348
  const onChannelJoined = (callback) => {
25007
25349
  const client = getActiveClient();
25008
25350
  const filter = (payload) => {
25009
- const data = prepareChannelPayload(payload);
25010
- ingestInCache(data);
25011
- 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]);
25012
25356
  };
25013
- return createEventSubscriber(client, 'onChannelJoined', 'v3.channel.didJoin', filter);
25357
+ return createEventSubscriber(client, 'onChannelJoined', 'channel.joined', filter);
25014
25358
  };
25015
25359
 
25016
25360
  /**
25017
25361
  * ```js
25018
25362
  * import { onChannelLeft } from '@amityco/ts-sdk'
25019
- * const dispose = onChannelLeft(channel => {
25363
+ * const dispose = onChannelLeft((channel, member) => {
25020
25364
  * // ...
25021
25365
  * })
25022
25366
  * ```
@@ -25029,13 +25373,40 @@ const onChannelJoined = (callback) => {
25029
25373
  * @category Channel Events
25030
25374
  */
25031
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) => {
25032
25403
  const client = getActiveClient();
25033
25404
  const filter = (payload) => {
25034
25405
  const data = prepareChannelPayload(payload);
25035
25406
  ingestInCache(data);
25036
25407
  callback(data.channels[0]);
25037
25408
  };
25038
- return createEventSubscriber(client, 'onChannelLeft', 'v3.channel.didLeave', filter);
25409
+ return createEventSubscriber(client, 'onChannelMuted', 'channel.setMuted', filter);
25039
25410
  };
25040
25411
 
25041
25412
  /**
@@ -25056,11 +25427,13 @@ const onChannelLeft = (callback) => {
25056
25427
  const onChannelMemberAdded = (callback) => {
25057
25428
  const client = getActiveClient();
25058
25429
  const filter = (payload) => {
25059
- const data = prepareChannelPayload(payload);
25060
- ingestInCache(data);
25061
- 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'));
25062
25435
  };
25063
- return createEventSubscriber(client, 'onChannelMemberAdded', 'v3.channel.didAddUsers', filter);
25436
+ return createEventSubscriber(client, 'onChannelMemberAdded', 'channel.membersAdded', filter);
25064
25437
  };
25065
25438
 
25066
25439
  /**
@@ -25081,11 +25454,13 @@ const onChannelMemberAdded = (callback) => {
25081
25454
  const onChannelMemberRemoved = (callback) => {
25082
25455
  const client = getActiveClient();
25083
25456
  const filter = (payload) => {
25084
- const data = prepareChannelPayload(payload);
25085
- ingestInCache(data);
25086
- 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]);
25087
25462
  };
25088
- return createEventSubscriber(client, 'onChannelMemberRemoved', 'v3.channel.didRemoveUsers', filter);
25463
+ return createEventSubscriber(client, 'onChannelMemberRemoved', 'channel.membersRemoved', filter);
25089
25464
  };
25090
25465
 
25091
25466
  /**
@@ -25106,11 +25481,13 @@ const onChannelMemberRemoved = (callback) => {
25106
25481
  const onChannelMemberBanned = (callback) => {
25107
25482
  const client = getActiveClient();
25108
25483
  const filter = (payload) => {
25109
- const data = prepareChannelPayload(payload);
25110
- ingestInCache(data);
25111
- 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'));
25112
25489
  };
25113
- return createEventSubscriber(client, 'onChannelMemberBanned', 'v3.channel.didBan', filter);
25490
+ return createEventSubscriber(client, 'onChannelMemberBanned', 'channel.banned', filter);
25114
25491
  };
25115
25492
 
25116
25493
  /**
@@ -25131,11 +25508,13 @@ const onChannelMemberBanned = (callback) => {
25131
25508
  const onChannelMemberUnbanned = (callback) => {
25132
25509
  const client = getActiveClient();
25133
25510
  const filter = (payload) => {
25134
- const data = prepareChannelPayload(payload);
25135
- ingestInCache(data);
25136
- 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'));
25137
25516
  };
25138
- return createEventSubscriber(client, 'onChannelMemberBanned', 'v3.channel.didUnban', filter);
25517
+ return createEventSubscriber(client, 'onChannelMemberUnbanned', 'channel.unbanned', filter);
25139
25518
  };
25140
25519
 
25141
25520
  /**
@@ -25171,7 +25550,7 @@ const observeChannel = (channelId, callback) => {
25171
25550
  (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
25172
25551
  };
25173
25552
  const disposers = [];
25174
- 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')));
25175
25554
  runQuery(createQuery(getChannel, channelId), result => result.data && router(result, 'onFetch'));
25176
25555
  return () => {
25177
25556
  log(`observeChannel(tmpid: ${timestamp}) > dispose`);
@@ -25206,324 +25585,1131 @@ const observeChannels = (callback) => {
25206
25585
  (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, channel);
25207
25586
  (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, channel);
25208
25587
  };
25209
- 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')));
25210
25589
  return () => {
25211
25590
  log(`observeChannels(tmpid: ${timestamp}) > dispose`);
25212
25591
  disposers.forEach(fn => fn());
25213
25592
  };
25214
25593
  };
25215
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
+
25216
25628
  /**
25217
25629
  * ```js
25218
- * import { liveChannels } from '@amityco/ts-sdk'
25219
- *
25220
- * let channels = []
25221
- * const unsub = liveChannels({
25222
- * displayName: Amity.Channel['displayName'],
25223
- * }, response => merge(channels, response.data))
25630
+ * import { onMessageCreated } from '@amityco/ts-sdk'
25631
+ * const dispose = onMessageCreated(message => {
25632
+ * // ...
25633
+ * })
25224
25634
  * ```
25225
25635
  *
25226
- * Observe all mutations on a list of {@link Amity.Channel}s
25636
+ * Fired when an {@link Amity.Message} has been created
25227
25637
  *
25228
- * @param params for querying channels
25229
- * @param callback the function to call when new data are available
25230
- * @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
25231
25640
  *
25232
- * @category Channel Live Collection
25641
+ * @category Message Events
25233
25642
  */
25234
- const liveChannels = (params, callback, config) => {
25235
- const { log, cache, userId } = getActiveClient();
25236
- if (!cache) {
25237
- console.log(ENABLE_CACHE_MESSAGE);
25238
- }
25239
- const timestamp = Date.now();
25240
- log(`liveChannels(tmpid: ${timestamp}) > listen`);
25241
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
25242
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
25243
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
25244
- const disposers = [];
25245
- const cacheKey = ['channel', 'collection', {}];
25246
- const responder = (data) => {
25247
- var _a, _b;
25248
- let channels = (_a = data.data
25249
- .map(channelId => pullFromCache(['channel', 'get', channelId]))
25250
- .filter(Boolean)
25251
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
25252
- channels = filterByPropEquality(channels, 'isDeleted', params.isDeleted);
25253
- channels = filterByPropEquality(channels, 'displayName', params.displayName);
25254
- if (params.types) {
25255
- channels = channels.filter(c => { var _a; return (_a = params.types) === null || _a === void 0 ? void 0 : _a.includes(c.type); });
25256
- }
25257
- if (params.tags) {
25258
- 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); }); });
25259
- }
25260
- if (params.excludeTags) {
25261
- 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); })); });
25262
- }
25263
- // userId is required to be able to filter channel by current active user
25264
- if (params.membership && userId) {
25265
- channels = filterByChannelMembership(channels, params.membership, userId);
25266
- }
25267
- const sortBy = params.sortBy || 'lastCreated';
25268
- if (sortBy === 'lastCreated' || sortBy === 'firstCreated') {
25269
- channels = channels.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
25270
- }
25271
- /*
25272
- * The server returns channels with empty | null displayName's first before
25273
- * returning sorted list of channels with displayNames
25274
- *
25275
- * This section needs to be updated as displayNames can be null as well
25276
- */
25277
- if (sortBy === 'displayName') {
25278
- channels = channels
25279
- // this needs to be aligned with the backend data type
25280
- .map(c => (c.displayName ? c : Object.assign(Object.assign({}, c), { displayName: '' })))
25281
- // @ts-ignore
25282
- .sort(sortByDisplayName);
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 });
25656
+ }
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] });
25283
25662
  }
25284
- callback({
25285
- onNextPage: onFetch,
25286
- data: channels,
25287
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
25288
- loading: data.loading,
25289
- error: data.error,
25290
- });
25663
+ ingestInCache(payload);
25664
+ callback(message);
25291
25665
  };
25292
- const realtimeRouter = (channel, action) => {
25293
- var _a;
25294
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25295
- if (!collection)
25296
- return;
25297
- if (action === 'onCreate') {
25298
- collection.data = [...new Set([channel.channelId, ...collection.data])];
25299
- /*
25300
- * if the filter isDeleted is set, only collection item must be updated and not
25301
- * the collection
25302
- */
25303
- }
25304
- else if (action === 'onDelete' && !params.isDeleted) {
25305
- collection.data = collection.data.filter(c => c !== channel.channelId);
25306
- }
25307
- pushToCache(cacheKey, collection);
25308
- responder(collection);
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
+ ];
25670
+ return () => {
25671
+ disposers.forEach(fn => fn());
25309
25672
  };
25310
- const onFetch = () => {
25311
- var _a, _b, _c;
25312
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25313
- const channels = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
25314
- if (channels.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
25315
- return;
25316
- 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 } }));
25317
- runQuery(query, ({ data: result, error, loading, nextPage: page }) => {
25318
- const data = {
25319
- loading,
25320
- error,
25321
- params: { page },
25322
- data: channels,
25323
- };
25324
- if (result) {
25325
- data.data = [...new Set([...channels, ...result.map(getResolver('channel'))])];
25326
- }
25327
- pushToCache(cacheKey, data);
25328
- responder(data);
25673
+ };
25674
+
25675
+ /**
25676
+ * ```js
25677
+ * import { onMessageUpdated } from '@amityco/ts-sdk'
25678
+ * const dispose = onMessageUpdated(message => {
25679
+ * // ...
25680
+ * })
25681
+ * ```
25682
+ *
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 = []
26059
+ * const unsub = liveChannelMembers({
26060
+ * channelId: Amity.Channel['channelId'],
26061
+ * }, response => merge(channelMembers, response.data))
26062
+ * ```
26063
+ *
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);
25329
26162
  }, queryOptions(policy));
25330
26163
  };
25331
- disposers.push(onChannelCreated(channel => realtimeRouter(channel, 'onCreate')), onChannelDeleted(channel => realtimeRouter(channel, 'onDelete')), onChannelUpdated(channel => realtimeRouter(channel, 'onUpdate')));
26164
+ disposers.push(onChannelJoined(realtimeRouter()), onChannelLeft(realtimeRouter()), onChannelMemberAdded(realtimeRouter()), onChannelMemberRemoved(realtimeRouter()), onChannelMemberBanned(realtimeRouter()), onChannelMemberUnbanned(realtimeRouter()));
25332
26165
  onFetch();
25333
26166
  return () => {
25334
- log(`liveChannels(tmpid: ${timestamp}) > dispose`);
26167
+ log(`liveChannelMembers(tmpid: ${timestamp}) > dispose`);
25335
26168
  disposers.forEach(fn => fn());
25336
26169
  };
25337
26170
  };
25338
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
+
25339
26188
  /**
25340
26189
  * ```js
25341
- * import { liveChannelMembers } from '@amityco/ts-sdk'
26190
+ * import { querySubChannels } from '@amityco/ts-sdk'
26191
+ * const subChannels = await querySubChannels({ channelId: 'channelId' })
26192
+ * ```
25342
26193
  *
25343
- * let channelMembers = []
25344
- * const unsub = liveChannelMembers({
25345
- * channelId: Amity.Channel['channelId'],
25346
- * }, response => merge(channelMembers, response.data))
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')
25347
26459
  * ```
25348
26460
  *
25349
- * Observe all mutations on a list of {@link Amity.ChannelUser}s
26461
+ * Deletes a {@link Amity.SubChannel}
25350
26462
  *
25351
- * @param params for querying channel users
25352
- * @param callback the function to call when new data are available
25353
- * @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
25354
26465
  *
25355
- * @category Channel Live Collection
26466
+ * @category Channel API
26467
+ * @async
25356
26468
  */
25357
- const liveChannelMembers = (params, callback, config) => {
25358
- const { log, cache } = getActiveClient();
25359
- if (!cache) {
25360
- 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);
25361
26479
  }
25362
- const timestamp = Date.now();
25363
- log(`liveChannelMembers(tmpid: ${timestamp}) > listen`);
25364
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
25365
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
25366
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
25367
- const disposers = [];
25368
- const cacheKey = ['channelUsers', 'collection', { channelId: params.channelId }];
25369
- const responder = (data) => {
25370
- var _a, _b;
25371
- let channelMembers = (_a = data.data
25372
- .map(id => pullFromCache(['channelUsers', 'get', id]))
25373
- .filter(Boolean)
25374
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
25375
- channelMembers = filterByPropEquality(channelMembers, 'roles', params.roles);
25376
- if (params.memberships) {
25377
- /*
25378
- * even though membership includes muted as a possible value
25379
- * when querying the server.
25380
- * Muted is specified under seperarte property namely isMuted
25381
- * Hence why I've seperately checked for it's equality
25382
- */
25383
- if (params.memberships.some(m => ['member', 'banned'].includes(m))) {
25384
- channelMembers = filterByPropInclusion(channelMembers, 'membership', params.memberships);
25385
- }
25386
- if (params.memberships.includes('muted')) {
25387
- channelMembers = filterByPropEquality(channelMembers, 'isMuted', true);
25388
- }
25389
- }
25390
- if (params.search) {
25391
- const containsMatcher = new RegExp(params.search);
25392
- channelMembers = channelMembers.filter(m => m.userId.match(containsMatcher));
25393
- }
25394
- // sort, 'lastCreated' is the default sort order
25395
- const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
25396
- channelMembers = channelMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
25397
- callback({
25398
- onNextPage: onFetch,
25399
- data: channelMembers,
25400
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
25401
- loading: data.loading,
25402
- error: data.error,
25403
- });
25404
- };
25405
- const realtimeRouter = (channelMember, action) => {
25406
- var _a;
25407
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25408
- if (!collection)
25409
- return;
25410
- const channelMemberCacheId = getResolver('channelUsers')({
25411
- channelId: params.channelId,
25412
- userId: channelMember.userId,
25413
- });
25414
- if (action === 'onMemberAdded') {
25415
- collection.data = [...new Set([channelMemberCacheId, ...collection.data])];
25416
- }
25417
- if (action === 'onMemberRemoved') {
25418
- collection.data = collection.data.filter(m => m !== channelMemberCacheId);
25419
- }
25420
- pushToCache(cacheKey, collection);
25421
- responder(collection);
25422
- };
25423
- const onFetch = () => {
25424
- var _a, _b, _c;
25425
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25426
- const channelMembers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
25427
- if (channelMembers.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
25428
- return;
25429
- 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 } }));
25430
- runQuery(query, ({ data: result, error, loading, nextPage: page }) => {
25431
- const data = {
25432
- loading,
25433
- error,
25434
- params: { page },
25435
- data: channelMembers,
25436
- };
25437
- if (result) {
25438
- data.data = [...new Set([...channelMembers, ...result.map(getResolver('channelUsers'))])];
25439
- }
25440
- pushToCache(cacheKey, data);
25441
- responder(data);
25442
- }, queryOptions(policy));
25443
- };
25444
- disposers.push(onChannelMemberAdded((_, member) => realtimeRouter(member, 'onMemberAdded')), onChannelMemberRemoved((_, member) => realtimeRouter(member, 'onMemberRemoved')), onChannelMemberBanned((_, member) => realtimeRouter(member, 'onChannelMemberBanned')), onChannelMemberUnbanned((_, member) => realtimeRouter(member, 'onChannelMemberUnbanned')));
25445
- onFetch();
25446
- return () => {
25447
- log(`liveChannelMembers(tmpid: ${timestamp}) > dispose`);
25448
- disposers.forEach(fn => fn());
25449
- };
26480
+ else {
26481
+ upsertInCache(['subChannel', 'get', subChannelId], deleted);
26482
+ }
26483
+ fireEvent('local.message-feed.deleted', { messageFeeds: [deleted] });
26484
+ return deleted;
25450
26485
  };
25451
26486
 
25452
26487
  /**
25453
26488
  * ```js
25454
- * import { onMessageCreated } from '@amityco/ts-sdk'
25455
- * const dispose = onMessageCreated(message => {
26489
+ * import { onChannelSubCreated } from '@amityco/ts-sdk'
26490
+ * const dispose = onSubChannelCreated(subChannel => {
25456
26491
  * // ...
25457
26492
  * })
25458
26493
  * ```
25459
26494
  *
25460
- * Fired when an {@link Amity.Message} has been created
26495
+ * Fired when any {@link Amity.SubChannel} have been created
25461
26496
  *
25462
26497
  * @param callback The function to call when the event was fired
25463
26498
  * @returns an {@link Amity.Unsubscriber} function to stop listening
25464
26499
  *
25465
- * @category Message Events
26500
+ * @category Channel Events
25466
26501
  */
25467
- const onMessageCreated = (callback) => {
26502
+ const onSubChannelCreated = (callback) => {
25468
26503
  const client = getActiveClient();
25469
- const filter = (payload) => {
26504
+ const filter = (rawPayload) => {
26505
+ const payload = prepareSubChannelPayload(rawPayload);
25470
26506
  ingestInCache(payload);
25471
- callback(payload.messages[0]);
26507
+ callback(payload.messageFeeds[0]);
25472
26508
  };
25473
- return createEventSubscriber(client, 'message/onMessageCreated', 'v3.message.didCreate', filter);
26509
+ return createEventSubscriber(client, 'onSubChannelCreated', 'message-feed.created', filter);
25474
26510
  };
25475
26511
 
25476
26512
  /**
25477
26513
  * ```js
25478
- * import { onMessageUpdated } from '@amityco/ts-sdk'
25479
- * const dispose = onMessageUpdated(message => {
26514
+ * import { onSubChannelUpdated } from '@amityco/ts-sdk'
26515
+ * const dispose = onSubChannelUpdated(subChannel => {
25480
26516
  * // ...
25481
26517
  * })
25482
26518
  * ```
25483
26519
  *
25484
- * Fired when an {@link Amity.Message} has been updated
26520
+ * Fired when any {@link Amity.SubChannel} have been updated
25485
26521
  *
25486
26522
  * @param callback The function to call when the event was fired
25487
26523
  * @returns an {@link Amity.Unsubscriber} function to stop listening
25488
26524
  *
25489
- * @category Message Events
26525
+ * @category Channel Events
25490
26526
  */
25491
- const onMessageUpdated = (callback) => {
26527
+ const onSubChannelUpdated = (callback) => {
25492
26528
  const client = getActiveClient();
25493
- const filter = (payload) => {
26529
+ const filter = (rawPayload) => {
26530
+ const payload = prepareSubChannelPayload(rawPayload);
25494
26531
  ingestInCache(payload);
25495
- const message = payload.messages[0];
25496
- // if payload does not have myReactions
25497
- if (!(message === null || message === void 0 ? void 0 : message.myReactions)) {
25498
- prepareMessagePayloadForCache(message);
25499
- }
25500
- callback(message);
26532
+ callback(payload.messageFeeds[0]);
25501
26533
  };
25502
- return createEventSubscriber(client, 'message/onMessageUpdated', 'v3.message.didUpdate', filter);
26534
+ return createEventSubscriber(client, 'onSubChannelUpdated', 'message-feed.updated', filter);
25503
26535
  };
25504
26536
 
25505
26537
  /**
25506
26538
  * ```js
25507
- * import { onMessageDeleted } from '@amityco/ts-sdk'
25508
- * const dispose = onMessageDeleted(message => {
26539
+ * import { onSubChannelDeleted } from '@amityco/ts-sdk'
26540
+ * const dispose = onSubChannelDeleted(subChannel => {
25509
26541
  * // ...
25510
26542
  * })
25511
26543
  * ```
25512
26544
  *
25513
- * Fired when an {@link Amity.Message} was deleted
26545
+ * Fired when any {@link Amity.SubChannel} have been deleted
25514
26546
  *
25515
26547
  * @param callback The function to call when the event was fired
25516
26548
  * @returns an {@link Amity.Unsubscriber} function to stop listening
25517
26549
  *
25518
- * @category Message Events
26550
+ * @category Channel Events
25519
26551
  */
25520
- const onMessageDeleted = (callback) => {
26552
+ const onSubChannelDeleted = (callback) => {
25521
26553
  const client = getActiveClient();
25522
- const filter = (payload) => {
26554
+ const filter = (rawPayload) => {
26555
+ const payload = prepareSubChannelPayload(rawPayload);
25523
26556
  ingestInCache(payload);
25524
- 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());
25525
26712
  };
25526
- return createEventSubscriber(client, 'message/onMessageDeleted', 'v3.message.didDelete', filter);
25527
26713
  };
25528
26714
 
25529
26715
  /**
@@ -25547,46 +26733,50 @@ const onMessageFetched = (callback) => {
25547
26733
  ingestInCache(payload);
25548
26734
  callback(payload.messages[0]);
25549
26735
  };
25550
- return createEventSubscriber(client, 'message/onMessageFetched', 'v3.message.didFetch', filter);
26736
+ return createEventSubscriber(client, 'message/onMessageFetched', 'local.message.fetched', filter);
25551
26737
  };
25552
26738
 
25553
26739
  /**
25554
26740
  * ```js
25555
- * import { liveMessage } from '@amityco/ts-sdk'
26741
+ * import { liveMessage } from '@amityco/ts-sdk';
25556
26742
  *
25557
- * let messages = []
25558
- * const unsub = liveMessage(messageId, response => merge(messages, response.data))
26743
+ * let message;
26744
+ *
26745
+ * const unsubscribe = liveMessage(messageId, response => {
26746
+ * message = response.data;
26747
+ * });
25559
26748
  * ```
25560
26749
  *
25561
26750
  * Observe all mutation on a given {@link Amity.Message}
25562
26751
  *
25563
26752
  * @param messageId the ID of the message to observe
25564
26753
  * @param callback the function to call when new data are available
25565
- * @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
25566
26755
  *
25567
26756
  * @category Message Live Object
25568
26757
  */
25569
26758
  const liveMessage = (messageId, callback) => {
25570
26759
  const { log, cache } = getActiveClient();
25571
- let message;
25572
- let isUnsyncedObject = false;
26760
+ const timestamp = Date.now();
26761
+ log(`liveMessage(tmpid: ${timestamp}) > listen`);
25573
26762
  if (!cache) {
25574
26763
  console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
25575
26764
  }
25576
- const timestamp = Date.now();
25577
- log(`liveMessage(tmpid: ${timestamp}) > listen`);
26765
+ let message;
26766
+ let isUnsyncedObject = false;
25578
26767
  const disposers = [];
25579
26768
  const dispatcher = (data) => {
25580
- var _a;
25581
- // we check updatedAt to see if the current snapshot is new so
25582
- // we won't send old data back, only fresh new data
25583
- 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')
25584
- return;
25585
- callback(data);
25586
26769
  message = data.data;
26770
+ callback(data);
25587
26771
  };
25588
- const realtimeRouter = (message, action) => {
25589
- 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' });
25590
26780
  };
25591
26781
  const onFetch = () => {
25592
26782
  const query = createQuery(getMessage, messageId, true);
@@ -25605,12 +26795,11 @@ const liveMessage = (messageId, callback) => {
25605
26795
  dispatcher({ loading, data, origin, error });
25606
26796
  }
25607
26797
  if (error) {
25608
- // Terminate observe functionality on error
25609
26798
  disposers.forEach(fn => fn());
25610
26799
  }
25611
26800
  });
25612
26801
  };
25613
- 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));
25614
26803
  onFetch();
25615
26804
  return () => {
25616
26805
  log(`liveMessage(tmpid: ${timestamp}) > dispose`);
@@ -25620,17 +26809,18 @@ const liveMessage = (messageId, callback) => {
25620
26809
 
25621
26810
  /**
25622
26811
  * ```js
25623
- * import { liveMessages } from '@amityco/ts-sdk'
26812
+ * import { liveMessages } from '@amityco/ts-sdk';
25624
26813
  *
25625
- * let messages = []
25626
- * const unsub = liveMessages({
25627
- * channelId: Amity.Channel['channelId'];
25628
- * }, response => merge(messages, response.data))
26814
+ * let messages = [];
26815
+ *
26816
+ * const unsubscribe = liveMessages({
26817
+ * subChannelId: Amity.SubChannel['subChannelId'];
26818
+ * }, response => merge(messages, response.data));
25629
26819
  * ```
25630
26820
  *
25631
26821
  * Observe all mutations on a list of {@link Amity.Message} for a given target object
25632
26822
  *
25633
- * @param params for querying memssages from a channel
26823
+ * @param params for querying messages from a sub channel
25634
26824
  * @param callback the function to call when new data are available
25635
26825
  * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
25636
26826
  *
@@ -25647,7 +26837,7 @@ const liveMessages = (params, callback, config) => {
25647
26837
  const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
25648
26838
  const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
25649
26839
  const disposers = [];
25650
- const cacheKey = ['message', 'collection', { channelId: params.channelId }];
26840
+ const cacheKey = ['message', 'collection', { subChannelId: params.subChannelId }];
25651
26841
  const responder = (data) => {
25652
26842
  var _a, _b;
25653
26843
  let messages = (_a = data.data
@@ -25667,10 +26857,10 @@ const liveMessages = (params, callback, config) => {
25667
26857
  error: data.error,
25668
26858
  });
25669
26859
  };
25670
- const realtimeRouter = (message, action) => {
26860
+ const realtimeRouter = (action) => (message) => {
25671
26861
  var _a;
25672
26862
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25673
- if (params.channelId !== message.channelId || !collection)
26863
+ if (params.subChannelId !== message.subChannelId || !collection)
25674
26864
  return;
25675
26865
  if (action === 'onCreate') {
25676
26866
  collection.data = [...new Set([message.messageId, ...collection.data])];
@@ -25702,7 +26892,7 @@ const liveMessages = (params, callback, config) => {
25702
26892
  responder(data);
25703
26893
  }, queryOptions(policy));
25704
26894
  };
25705
- 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')));
25706
26896
  onFetch();
25707
26897
  return () => {
25708
26898
  log(`liveMessages(tmpid: ${timestamp}) > dispose`);
@@ -25715,6 +26905,7 @@ const liveMessages = (params, callback, config) => {
25715
26905
  * import { observeMessage } from '@amityco/ts-sdk'
25716
26906
  *
25717
26907
  * let message = {}
26908
+ *
25718
26909
  * const unsub = observeMessage(messageId, updated => message = updated)
25719
26910
  * ```
25720
26911
  *
@@ -25761,25 +26952,26 @@ const observeMessage = (messageId, callback, policy = 'cache_then_server') => {
25761
26952
  * import { observeMessages } from '@amityco/ts-sdk'
25762
26953
  *
25763
26954
  * let messages = []
25764
- * const unsub = observeMessages(channelId, message => merge(messages, message))
26955
+ *
26956
+ * const unsubscribe = observeMessages(channelId, message => merge(messages, message))
25765
26957
  * ```
25766
26958
  *
25767
- * 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
25768
26960
  *
25769
- * @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
25770
26962
  * @param callback the function to call when new data are available
25771
26963
  * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
25772
26964
  *
25773
26965
  * @category Message Observer
25774
26966
  */
25775
- const observeMessages = (channelId, callback) => {
26967
+ const observeMessages = (subChannelId, callback) => {
25776
26968
  const { log } = getActiveClient();
25777
26969
  const timestamp = Date.now();
25778
26970
  log(`observeMessages(tmpid: ${timestamp}) > listen`);
25779
26971
  const disposers = [];
25780
26972
  const router = (message, action) => {
25781
26973
  var _a, _b, _c;
25782
- 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)
25783
26975
  return;
25784
26976
  if (callback instanceof Function)
25785
26977
  return callback(message);
@@ -25842,22 +27034,23 @@ function getEventRelatedMember(event, payload) {
25842
27034
  const createCommunityMemberEventSubscriber = (event, callback) => {
25843
27035
  const client = getActiveClient();
25844
27036
  const filter = (payload) => {
25845
- const unpackedPayload = unpackCommunityPayload(payload);
27037
+ const communityPayload = unpackCommunityPayload(payload);
27038
+ const preparedPayload = prepareMembershipPayload(communityPayload, 'communityUsers');
25846
27039
  if (!client.cache) {
25847
27040
  // TODO: here we are missing specific properties here!
25848
- callback(unpackedPayload.communities[0], getEventRelatedMember(event, unpackedPayload));
27041
+ callback(preparedPayload.communities[0], getEventRelatedMember(event, preparedPayload));
25849
27042
  }
25850
27043
  else {
25851
- ingestInCache(unpackedPayload);
27044
+ ingestInCache(preparedPayload);
25852
27045
  const community = pullFromCache([
25853
27046
  'community',
25854
27047
  'get',
25855
- unpackedPayload.communities[0].communityId,
27048
+ preparedPayload.communities[0].communityId,
25856
27049
  ]);
25857
27050
  const member = pullFromCache([
25858
27051
  'communityUsers',
25859
27052
  'get',
25860
- getResolver('communityUsers')(getEventRelatedMember(event, unpackedPayload)),
27053
+ getResolver('communityUsers')(getEventRelatedMember(event, preparedPayload)),
25861
27054
  ]);
25862
27055
  callback(community.data, member.data);
25863
27056
  }
@@ -26896,7 +28089,7 @@ const liveFollowers = (params, callback, config) => {
26896
28089
  error: data.error,
26897
28090
  });
26898
28091
  };
26899
- const realtimeRouter = (followStatus, action) => {
28092
+ const realtimeRouter = (action) => (followStatus) => {
26900
28093
  var _a;
26901
28094
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26902
28095
  if (params.userId !== followStatus.to || !collection)
@@ -26931,7 +28124,7 @@ const liveFollowers = (params, callback, config) => {
26931
28124
  responder(data);
26932
28125
  }, queryOptions(policy));
26933
28126
  };
26934
- 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')));
26935
28128
  onFetch();
26936
28129
  return () => {
26937
28130
  log(`liveFollowers(tmpid: ${timestamp}) > dispose`);
@@ -26986,7 +28179,7 @@ const liveFollowings = (params, callback, config) => {
26986
28179
  error: data.error,
26987
28180
  });
26988
28181
  };
26989
- const realtimeRouter = (followStatus, action) => {
28182
+ const realtimeRouter = (action) => (followStatus) => {
26990
28183
  var _a;
26991
28184
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26992
28185
  if (params.userId !== followStatus.from || !collection)
@@ -27021,7 +28214,7 @@ const liveFollowings = (params, callback, config) => {
27021
28214
  responder(data);
27022
28215
  }, queryOptions(policy));
27023
28216
  };
27024
- 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')));
27025
28218
  onFetch();
27026
28219
  return () => {
27027
28220
  log(`liveFollowings(tmpid: ${timestamp}) > dispose`);
@@ -27159,6 +28352,9 @@ const livePosts = (params, callback, config) => {
27159
28352
  posts = filterByPropEquality(posts, 'isDeleted', params.isDeleted);
27160
28353
  const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
27161
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
+ }
27162
28358
  callback({
27163
28359
  onNextPage: onFetch,
27164
28360
  data: posts,
@@ -27167,17 +28363,32 @@ const livePosts = (params, callback, config) => {
27167
28363
  error: data.error,
27168
28364
  });
27169
28365
  };
27170
- const realtimeRouter = (post, action) => {
28366
+ const realtimeRouter = (action) => (post) => {
27171
28367
  var _a;
27172
28368
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27173
28369
  if (params.targetId !== post.targetId || params.targetType !== post.targetType || !collection)
27174
28370
  return;
27175
- if (action === 'onCreate') {
28371
+ if (['onCreate', 'onApproved'].includes(action)) {
27176
28372
  collection.data = [...new Set([post.postId, ...collection.data])];
27177
28373
  }
27178
28374
  else if (['onDelete', 'onDeclined'].includes(action)) {
27179
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);
27180
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);
27181
28392
  pushToCache(cacheKey, collection);
27182
28393
  responder(collection);
27183
28394
  };
@@ -27202,7 +28413,7 @@ const livePosts = (params, callback, config) => {
27202
28413
  responder(data);
27203
28414
  }, queryOptions(policy));
27204
28415
  };
27205
- 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')));
27206
28417
  onFetch();
27207
28418
  return () => {
27208
28419
  log(`livePosts(tmpid: ${timestamp}) > dispose`);
@@ -27344,7 +28555,7 @@ const liveComments = (params, callback, config) => {
27344
28555
  error: data.error,
27345
28556
  });
27346
28557
  };
27347
- const realtimeRouter = (comment, action) => {
28558
+ const realtimeRouter = (action) => (comment) => {
27348
28559
  var _a;
27349
28560
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27350
28561
  if (params.referenceId !== comment.referenceId ||
@@ -27383,7 +28594,7 @@ const liveComments = (params, callback, config) => {
27383
28594
  responder(data);
27384
28595
  }, queryOptions(policy));
27385
28596
  };
27386
- 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')));
27387
28598
  onFetch();
27388
28599
  return () => {
27389
28600
  log(`liveComments(tmpid: ${timestamp}) > dispose`);
@@ -27975,4 +29186,4 @@ const createUserToken = async (apiKey, apiRegion, params) => {
27975
29186
  return { accessToken: data.accessToken };
27976
29187
  };
27977
29188
 
27978
- 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 };