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

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 (652) hide show
  1. package/dist/@types/core/errors.d.ts +1 -0
  2. package/dist/@types/core/errors.d.ts.map +1 -1
  3. package/dist/@types/core/events.d.ts +51 -22
  4. package/dist/@types/core/events.d.ts.map +1 -1
  5. package/dist/@types/core/model.d.ts +2 -0
  6. package/dist/@types/core/model.d.ts.map +1 -1
  7. package/dist/@types/core/payload.d.ts +15 -5
  8. package/dist/@types/core/payload.d.ts.map +1 -1
  9. package/dist/@types/domains/channel.d.ts +12 -7
  10. package/dist/@types/domains/channel.d.ts.map +1 -1
  11. package/dist/@types/domains/client.d.ts +40 -1
  12. package/dist/@types/domains/client.d.ts.map +1 -1
  13. package/dist/@types/domains/content.d.ts +2 -3
  14. package/dist/@types/domains/content.d.ts.map +1 -1
  15. package/dist/@types/domains/group.d.ts +6 -2
  16. package/dist/@types/domains/group.d.ts.map +1 -1
  17. package/dist/@types/domains/message.d.ts +37 -17
  18. package/dist/@types/domains/message.d.ts.map +1 -1
  19. package/dist/@types/domains/post.d.ts +2 -2
  20. package/dist/@types/domains/post.d.ts.map +1 -1
  21. package/dist/@types/domains/subChannel.d.ts +39 -0
  22. package/dist/@types/domains/subChannel.d.ts.map +1 -0
  23. package/dist/@types/global.d.ts +7 -0
  24. package/dist/@types/global.d.ts.map +1 -1
  25. package/dist/@types/index.d.ts +1 -0
  26. package/dist/@types/index.d.ts.map +1 -1
  27. package/dist/cache/api/tests/dropFromCache.test.d.ts +2 -0
  28. package/dist/cache/api/tests/dropFromCache.test.d.ts.map +1 -0
  29. package/dist/cache/api/tests/enableCache.test.d.ts +2 -0
  30. package/dist/cache/api/tests/enableCache.test.d.ts.map +1 -0
  31. package/dist/cache/api/tests/pullFromCache.test.d.ts +2 -0
  32. package/dist/cache/api/tests/pullFromCache.test.d.ts.map +1 -0
  33. package/dist/cache/api/tests/upsertInCache.test.d.ts +2 -0
  34. package/dist/cache/api/tests/upsertInCache.test.d.ts.map +1 -0
  35. package/dist/cache/utils/tests/encodeKey.test.d.ts +2 -0
  36. package/dist/cache/utils/tests/encodeKey.test.d.ts.map +1 -0
  37. package/dist/cache/utils/tests/partialMatch.test.d.ts +2 -0
  38. package/dist/cache/utils/tests/partialMatch.test.d.ts.map +1 -0
  39. package/dist/channel/api/banChannelMembers.d.ts.map +1 -1
  40. package/dist/channel/api/createChannel.d.ts +1 -1
  41. package/dist/channel/api/index.d.ts +2 -0
  42. package/dist/channel/api/index.d.ts.map +1 -1
  43. package/dist/channel/api/queryChannelMembers.d.ts.map +1 -1
  44. package/dist/channel/api/removeChannelMembers.d.ts.map +1 -1
  45. package/dist/channel/api/startReading.d.ts +17 -0
  46. package/dist/channel/api/startReading.d.ts.map +1 -0
  47. package/dist/channel/api/stopReading.d.ts +16 -0
  48. package/dist/channel/api/stopReading.d.ts.map +1 -0
  49. package/dist/channel/api/tests/createChannel.test.d.ts +2 -0
  50. package/dist/channel/api/tests/createChannel.test.d.ts.map +1 -0
  51. package/dist/channel/api/tests/joinChannel.test.d.ts +2 -0
  52. package/dist/channel/api/tests/joinChannel.test.d.ts.map +1 -0
  53. package/dist/channel/api/tests/removeChannelMembers.test.d.ts +2 -0
  54. package/dist/channel/api/tests/removeChannelMembers.test.d.ts.map +1 -0
  55. package/dist/channel/api/tests/startReading.test.d.ts +2 -0
  56. package/dist/channel/api/tests/startReading.test.d.ts.map +1 -0
  57. package/dist/channel/api/tests/stopReading.test.d.ts +2 -0
  58. package/dist/channel/api/tests/stopReading.test.d.ts.map +1 -0
  59. package/dist/channel/api/unbanChannelMembers.d.ts.map +1 -1
  60. package/dist/channel/events/index.d.ts +1 -0
  61. package/dist/channel/events/index.d.ts.map +1 -1
  62. package/dist/channel/events/onChannelJoined.d.ts +2 -2
  63. package/dist/channel/events/onChannelJoined.d.ts.map +1 -1
  64. package/dist/channel/events/onChannelLeft.d.ts +2 -2
  65. package/dist/channel/events/onChannelLeft.d.ts.map +1 -1
  66. package/dist/channel/events/onChannelMemberAdded.d.ts.map +1 -1
  67. package/dist/channel/events/onChannelMemberBanned.d.ts.map +1 -1
  68. package/dist/channel/events/onChannelMemberRemoved.d.ts.map +1 -1
  69. package/dist/channel/events/onChannelMemberUnbanned.d.ts.map +1 -1
  70. package/dist/channel/events/onChannelMuted.d.ts +17 -0
  71. package/dist/channel/events/onChannelMuted.d.ts.map +1 -0
  72. package/dist/channel/events/onChannelUpdated.d.ts +1 -1
  73. package/dist/channel/events/onChannelUpdated.d.ts.map +1 -1
  74. package/dist/channel/events/tests/onChannelCreated.test.d.ts +2 -0
  75. package/dist/channel/events/tests/onChannelCreated.test.d.ts.map +1 -0
  76. package/dist/channel/events/tests/onChannelJoined.test.d.ts +2 -0
  77. package/dist/channel/events/tests/onChannelJoined.test.d.ts.map +1 -0
  78. package/dist/channel/events/tests/onChannelMemberAdded.test.d.ts +2 -0
  79. package/dist/channel/events/tests/onChannelMemberAdded.test.d.ts.map +1 -0
  80. package/dist/channel/events/tests/onChannelMemberRemoved.test.d.ts +2 -0
  81. package/dist/channel/events/tests/onChannelMemberRemoved.test.d.ts.map +1 -0
  82. package/dist/channel/events/tests/onChannelUpdated.test.d.ts +2 -0
  83. package/dist/channel/events/tests/onChannelUpdated.test.d.ts.map +1 -0
  84. package/dist/channel/observers/index.d.ts +1 -0
  85. package/dist/channel/observers/index.d.ts.map +1 -1
  86. package/dist/channel/observers/liveChannel.d.ts +21 -0
  87. package/dist/channel/observers/liveChannel.d.ts.map +1 -0
  88. package/dist/channel/observers/liveChannelMembers.d.ts.map +1 -1
  89. package/dist/channel/observers/liveChannels.d.ts.map +1 -1
  90. package/dist/channel/observers/observeChannel.d.ts +1 -1
  91. package/dist/channel/observers/observeChannel.d.ts.map +1 -1
  92. package/dist/channel/observers/observeChannels.d.ts.map +1 -1
  93. package/dist/channel/utils/index.d.ts +2 -1
  94. package/dist/channel/utils/index.d.ts.map +1 -1
  95. package/dist/client/api/accessTokenExpiryWatcher.d.ts +4 -0
  96. package/dist/client/api/accessTokenExpiryWatcher.d.ts.map +1 -0
  97. package/dist/client/api/activeUser.d.ts +1 -1
  98. package/dist/client/api/activeUser.d.ts.map +1 -1
  99. package/dist/client/api/connectClient.d.ts +1 -1
  100. package/dist/client/api/connectClient.d.ts.map +1 -1
  101. package/dist/client/api/createClient.d.ts +1 -1
  102. package/dist/client/api/createClient.d.ts.map +1 -1
  103. package/dist/client/api/disconnectClient.d.ts +0 -1
  104. package/dist/client/api/disconnectClient.d.ts.map +1 -1
  105. package/dist/client/api/getChatSettings.d.ts +15 -0
  106. package/dist/client/api/getChatSettings.d.ts.map +1 -0
  107. package/dist/client/api/getSocialSettings.d.ts +15 -0
  108. package/dist/client/api/getSocialSettings.d.ts.map +1 -0
  109. package/dist/client/api/getToken.d.ts +4 -4
  110. package/dist/client/api/index.d.ts +1 -0
  111. package/dist/client/api/index.d.ts.map +1 -1
  112. package/dist/client/api/renewal.d.ts +2 -0
  113. package/dist/client/api/renewal.d.ts.map +1 -0
  114. package/dist/client/api/setSessionState.d.ts +12 -0
  115. package/dist/client/api/setSessionState.d.ts.map +1 -0
  116. package/dist/client/api/terminateClient.d.ts +9 -0
  117. package/dist/client/api/terminateClient.d.ts.map +1 -0
  118. package/dist/client/api/tests/accessTokenExpiryWatcher.test.d.ts +2 -0
  119. package/dist/client/api/tests/accessTokenExpiryWatcher.test.d.ts.map +1 -0
  120. package/dist/client/api/tests/activeClient.test.d.ts +2 -0
  121. package/dist/client/api/tests/activeClient.test.d.ts.map +1 -0
  122. package/dist/client/api/tests/activeUser.test.d.ts +2 -0
  123. package/dist/client/api/tests/activeUser.test.d.ts.map +1 -0
  124. package/dist/client/api/tests/connectClient.test.d.ts +2 -0
  125. package/dist/client/api/tests/connectClient.test.d.ts.map +1 -0
  126. package/dist/client/api/tests/createClient.test.d.ts +2 -0
  127. package/dist/client/api/tests/createClient.test.d.ts.map +1 -0
  128. package/dist/client/api/tests/disconnectClient.test.d.ts +2 -0
  129. package/dist/client/api/tests/disconnectClient.test.d.ts.map +1 -0
  130. package/dist/client/api/tests/getToken.test.d.ts +2 -0
  131. package/dist/client/api/tests/getToken.test.d.ts.map +1 -0
  132. package/dist/client/api/tests/renewal.test.d.ts +2 -0
  133. package/dist/client/api/tests/renewal.test.d.ts.map +1 -0
  134. package/dist/client/api/tests/setSessionState.test.d.ts +2 -0
  135. package/dist/client/api/tests/setSessionState.test.d.ts.map +1 -0
  136. package/dist/client/api/tests/terminateClient.test.d.ts +2 -0
  137. package/dist/client/api/tests/terminateClient.test.d.ts.map +1 -0
  138. package/dist/client/events/index.d.ts +1 -0
  139. package/dist/client/events/index.d.ts.map +1 -1
  140. package/dist/client/events/onClientBanned.d.ts +1 -1
  141. package/dist/client/events/onClientBanned.d.ts.map +1 -1
  142. package/dist/client/events/onSessionStateChange.d.ts +17 -0
  143. package/dist/client/events/onSessionStateChange.d.ts.map +1 -0
  144. package/dist/client/events/onTokenExpired.d.ts +17 -0
  145. package/dist/client/events/onTokenExpired.d.ts.map +1 -0
  146. package/dist/client/events/onTokenTerminated.d.ts +11 -0
  147. package/dist/client/events/onTokenTerminated.d.ts.map +1 -0
  148. package/dist/client/events/tests/onSessionStateChange.test.d.ts +2 -0
  149. package/dist/client/events/tests/onSessionStateChange.test.d.ts.map +1 -0
  150. package/dist/client/events/tests/onTokenTerminated.test.d.ts +2 -0
  151. package/dist/client/events/tests/onTokenTerminated.test.d.ts.map +1 -0
  152. package/dist/client/tests/connectClient.test.d.ts +2 -0
  153. package/dist/client/tests/connectClient.test.d.ts.map +1 -0
  154. package/dist/client/utils/setClientToken.d.ts +19 -0
  155. package/dist/client/utils/setClientToken.d.ts.map +1 -0
  156. package/dist/comment/api/createComment.d.ts +1 -1
  157. package/dist/comment/api/createComment.d.ts.map +1 -1
  158. package/dist/comment/api/tests/createComment.test.d.ts +2 -0
  159. package/dist/comment/api/tests/createComment.test.d.ts.map +1 -0
  160. package/dist/comment/api/tests/getComments.test.d.ts +2 -0
  161. package/dist/comment/api/tests/getComments.test.d.ts.map +1 -0
  162. package/dist/comment/events/tests/onCommentCreated.test.d.ts +2 -0
  163. package/dist/comment/events/tests/onCommentCreated.test.d.ts.map +1 -0
  164. package/dist/comment/events/tests/onCommentDeleted.test.d.ts +2 -0
  165. package/dist/comment/events/tests/onCommentDeleted.test.d.ts.map +1 -0
  166. package/dist/comment/events/utils.d.ts +1 -1
  167. package/dist/comment/events/utils.d.ts.map +1 -1
  168. package/dist/community/api/queryCommunities.d.ts.map +1 -1
  169. package/dist/community/api/queryCommunityMembers.d.ts +6 -1
  170. package/dist/community/api/queryCommunityMembers.d.ts.map +1 -1
  171. package/dist/community/api/test/addCommunityMember.test.d.ts +2 -0
  172. package/dist/community/api/test/addCommunityMember.test.d.ts.map +1 -0
  173. package/dist/community/api/test/addCommunityMemberRole.test.d.ts +2 -0
  174. package/dist/community/api/test/addCommunityMemberRole.test.d.ts.map +1 -0
  175. package/dist/community/api/test/createCommunity.test.d.ts +2 -0
  176. package/dist/community/api/test/createCommunity.test.d.ts.map +1 -0
  177. package/dist/community/api/test/deleteCommunity.test.d.ts +2 -0
  178. package/dist/community/api/test/deleteCommunity.test.d.ts.map +1 -0
  179. package/dist/community/api/test/getCommunities.test.d.ts +2 -0
  180. package/dist/community/api/test/getCommunities.test.d.ts.map +1 -0
  181. package/dist/community/api/test/getCommunity.test.d.ts +2 -0
  182. package/dist/community/api/test/getCommunity.test.d.ts.map +1 -0
  183. package/dist/community/api/test/getRecommendedCommunities.test.d.ts +2 -0
  184. package/dist/community/api/test/getRecommendedCommunities.test.d.ts.map +1 -0
  185. package/dist/community/api/test/getTopTrendingCommunities.test.d.ts +2 -0
  186. package/dist/community/api/test/getTopTrendingCommunities.test.d.ts.map +1 -0
  187. package/dist/community/api/test/joinCommunity.test.d.ts +2 -0
  188. package/dist/community/api/test/joinCommunity.test.d.ts.map +1 -0
  189. package/dist/community/api/test/leaveCommunity.test.d.ts +2 -0
  190. package/dist/community/api/test/leaveCommunity.test.d.ts.map +1 -0
  191. package/dist/community/api/test/queryCommunity.test.d.ts +2 -0
  192. package/dist/community/api/test/queryCommunity.test.d.ts.map +1 -0
  193. package/dist/community/api/test/queryCommunityMembers.test.d.ts +2 -0
  194. package/dist/community/api/test/queryCommunityMembers.test.d.ts.map +1 -0
  195. package/dist/community/api/test/removeCommunityMemberRole.test.d.ts +2 -0
  196. package/dist/community/api/test/removeCommunityMemberRole.test.d.ts.map +1 -0
  197. package/dist/community/api/test/removeCommunityMembers.test.d.ts +2 -0
  198. package/dist/community/api/test/removeCommunityMembers.test.d.ts.map +1 -0
  199. package/dist/community/api/test/updateCommunity.test.d.ts +2 -0
  200. package/dist/community/api/test/updateCommunity.test.d.ts.map +1 -0
  201. package/dist/community/events/test/onCommunityCreated.test.d.ts +2 -0
  202. package/dist/community/events/test/onCommunityCreated.test.d.ts.map +1 -0
  203. package/dist/community/events/test/onCommunityDeleted.test.d.ts +2 -0
  204. package/dist/community/events/test/onCommunityDeleted.test.d.ts.map +1 -0
  205. package/dist/community/events/test/onCommunityJoined.test.d.ts +2 -0
  206. package/dist/community/events/test/onCommunityJoined.test.d.ts.map +1 -0
  207. package/dist/community/events/test/onCommunityLeft.test.d.ts +2 -0
  208. package/dist/community/events/test/onCommunityLeft.test.d.ts.map +1 -0
  209. package/dist/community/events/test/onCommunityUpdated.test.d.ts +2 -0
  210. package/dist/community/events/test/onCommunityUpdated.test.d.ts.map +1 -0
  211. package/dist/community/events/test/onCommunityUserAdded.test.d.ts +2 -0
  212. package/dist/community/events/test/onCommunityUserAdded.test.d.ts.map +1 -0
  213. package/dist/community/events/test/onCommunityUserBanned.test.d.ts +2 -0
  214. package/dist/community/events/test/onCommunityUserBanned.test.d.ts.map +1 -0
  215. package/dist/community/events/test/onCommunityUserRemoved.test.d.ts +2 -0
  216. package/dist/community/events/test/onCommunityUserRemoved.test.d.ts.map +1 -0
  217. package/dist/community/events/test/onCommunityUserUnbaned.test.d.ts +2 -0
  218. package/dist/community/events/test/onCommunityUserUnbaned.test.d.ts.map +1 -0
  219. package/dist/community/events/test/utils.test.d.ts +2 -0
  220. package/dist/community/events/test/utils.test.d.ts.map +1 -0
  221. package/dist/community/events/utils.d.ts +2 -2
  222. package/dist/community/events/utils.d.ts.map +1 -1
  223. package/dist/core/events.d.ts +3 -3
  224. package/dist/core/events.d.ts.map +1 -1
  225. package/dist/core/model/idResolvers.d.ts.map +1 -1
  226. package/dist/core/model/identifyModel.d.ts.map +1 -1
  227. package/dist/core/model/index.d.ts +5 -0
  228. package/dist/core/model/index.d.ts.map +1 -1
  229. package/dist/core/query/filtering.d.ts.map +1 -1
  230. package/dist/core/query/query.d.ts.map +1 -1
  231. package/dist/core/subscription.d.ts +26 -1
  232. package/dist/core/subscription.d.ts.map +1 -1
  233. package/dist/core/tests/subscription.test.d.ts +2 -0
  234. package/dist/core/tests/subscription.test.d.ts.map +1 -0
  235. package/dist/core/transports/http.d.ts.map +1 -1
  236. package/dist/feed/api/queryGlobalFeed.d.ts +1 -1
  237. package/dist/feed/api/queryGlobalFeed.d.ts.map +1 -1
  238. package/dist/feed/api/test/queryGlobalFeed.test.d.ts +2 -0
  239. package/dist/feed/api/test/queryGlobalFeed.test.d.ts.map +1 -0
  240. package/dist/follow/events/utils.d.ts +1 -1
  241. package/dist/follow/events/utils.d.ts.map +1 -1
  242. package/dist/group/utils/index.d.ts +2 -0
  243. package/dist/group/utils/index.d.ts.map +1 -0
  244. package/dist/group/utils/test/withUsers.test.d.ts +2 -0
  245. package/dist/group/utils/test/withUsers.test.d.ts.map +1 -0
  246. package/dist/group/utils/withUser.d.ts +38 -0
  247. package/dist/group/utils/withUser.d.ts.map +1 -0
  248. package/dist/index.cjs.js +2451 -870
  249. package/dist/index.d.ts +3 -0
  250. package/dist/index.d.ts.map +1 -1
  251. package/dist/index.esm.js +2424 -869
  252. package/dist/index.umd.js +4 -4
  253. package/dist/message/api/createMessage.d.ts +15 -9
  254. package/dist/message/api/createMessage.d.ts.map +1 -1
  255. package/dist/message/api/deleteMessage.d.ts +2 -2
  256. package/dist/message/api/getMessage.d.ts.map +1 -1
  257. package/dist/message/api/getMessages.d.ts.map +1 -1
  258. package/dist/message/api/queryMessages.d.ts.map +1 -1
  259. package/dist/message/api/updateMessage.d.ts +1 -1
  260. package/dist/message/api/updateMessage.d.ts.map +1 -1
  261. package/dist/message/events/index.d.ts +5 -1
  262. package/dist/message/events/index.d.ts.map +1 -1
  263. package/dist/message/events/onMessageCreated.d.ts.map +1 -1
  264. package/dist/message/events/onMessageDeleted.d.ts.map +1 -1
  265. package/dist/message/events/onMessageFlagCleared.d.ts +17 -0
  266. package/dist/message/events/onMessageFlagCleared.d.ts.map +1 -0
  267. package/dist/message/events/onMessageFlagged.d.ts +17 -0
  268. package/dist/message/events/onMessageFlagged.d.ts.map +1 -0
  269. package/dist/message/events/onMessageReactionAdded.d.ts +18 -0
  270. package/dist/message/events/onMessageReactionAdded.d.ts.map +1 -0
  271. package/dist/message/events/onMessageReactionRemoved.d.ts +18 -0
  272. package/dist/message/events/onMessageReactionRemoved.d.ts.map +1 -0
  273. package/dist/message/events/onMessageUnflagged.d.ts +17 -0
  274. package/dist/message/events/onMessageUnflagged.d.ts.map +1 -0
  275. package/dist/message/events/onMessageUpdated.d.ts.map +1 -1
  276. package/dist/message/observers/liveMessage.d.ts +7 -4
  277. package/dist/message/observers/liveMessage.d.ts.map +1 -1
  278. package/dist/message/observers/liveMessages.d.ts +7 -6
  279. package/dist/message/observers/liveMessages.d.ts.map +1 -1
  280. package/dist/message/observers/observeMessage.d.ts +1 -0
  281. package/dist/message/observers/observeMessage.d.ts.map +1 -1
  282. package/dist/message/observers/observeMessages.d.ts +5 -4
  283. package/dist/message/observers/observeMessages.d.ts.map +1 -1
  284. package/dist/message/tests/events.test.d.ts +2 -0
  285. package/dist/message/tests/events.test.d.ts.map +1 -0
  286. package/dist/message/utils/index.d.ts +18 -0
  287. package/dist/message/utils/index.d.ts.map +1 -0
  288. package/dist/post/api/queryPosts.d.ts.map +1 -1
  289. package/dist/post/api/tests/queryPosts.test.d.ts +2 -0
  290. package/dist/post/api/tests/queryPosts.test.d.ts.map +1 -0
  291. package/dist/post/events/tests/onPostApproved.test.d.ts +2 -0
  292. package/dist/post/events/tests/onPostApproved.test.d.ts.map +1 -0
  293. package/dist/post/events/tests/onPostCreated.test.d.ts +2 -0
  294. package/dist/post/events/tests/onPostCreated.test.d.ts.map +1 -0
  295. package/dist/post/events/tests/onPostDeclined.test.d.ts +2 -0
  296. package/dist/post/events/tests/onPostDeclined.test.d.ts.map +1 -0
  297. package/dist/post/events/tests/onPostDeleted.test.d.ts +2 -0
  298. package/dist/post/events/tests/onPostDeleted.test.d.ts.map +1 -0
  299. package/dist/post/events/tests/onPostFlagged.test.d.ts +2 -0
  300. package/dist/post/events/tests/onPostFlagged.test.d.ts.map +1 -0
  301. package/dist/post/events/tests/onPostReactionAdded.test.d.ts +2 -0
  302. package/dist/post/events/tests/onPostReactionAdded.test.d.ts.map +1 -0
  303. package/dist/post/events/tests/onPostReactionRemoved.test.d.ts +2 -0
  304. package/dist/post/events/tests/onPostReactionRemoved.test.d.ts.map +1 -0
  305. package/dist/post/events/tests/onPostUnflagged.test.d.ts +2 -0
  306. package/dist/post/events/tests/onPostUnflagged.test.d.ts.map +1 -0
  307. package/dist/post/events/tests/onPostUpdated.test.d.ts +2 -0
  308. package/dist/post/events/tests/onPostUpdated.test.d.ts.map +1 -0
  309. package/dist/post/events/utils.d.ts +1 -1
  310. package/dist/post/events/utils.d.ts.map +1 -1
  311. package/dist/post/observers/livePosts.d.ts.map +1 -1
  312. package/dist/post/observers/tests/livePosts.test.d.ts +2 -0
  313. package/dist/post/observers/tests/livePosts.test.d.ts.map +1 -0
  314. package/dist/reaction/api/addReaction.d.ts.map +1 -1
  315. package/dist/reaction/api/removeReaction.d.ts.map +1 -1
  316. package/dist/reaction/events/onReactionAdded.d.ts.map +1 -1
  317. package/dist/reaction/events/onReactionRemoved.d.ts.map +1 -1
  318. package/dist/reaction/events/onReactorAdded.d.ts.map +1 -1
  319. package/dist/reaction/events/onReactorRemoved.d.ts.map +1 -1
  320. package/dist/report/api/createReport.d.ts.map +1 -1
  321. package/dist/report/api/deleteReport.d.ts.map +1 -1
  322. package/dist/report/api/isReportedByMe.d.ts.map +1 -1
  323. package/dist/stream/api/tests/createStream.test.d.ts +2 -0
  324. package/dist/stream/api/tests/createStream.test.d.ts.map +1 -0
  325. package/dist/stream/api/tests/deleteStream.test.d.ts +2 -0
  326. package/dist/stream/api/tests/deleteStream.test.d.ts.map +1 -0
  327. package/dist/stream/api/tests/getStream.test.d.ts +2 -0
  328. package/dist/stream/api/tests/getStream.test.d.ts.map +1 -0
  329. package/dist/subChannel/api/createSubChannel.d.ts +16 -0
  330. package/dist/subChannel/api/createSubChannel.d.ts.map +1 -0
  331. package/dist/subChannel/api/deleteSubChannel.d.ts +16 -0
  332. package/dist/subChannel/api/deleteSubChannel.d.ts.map +1 -0
  333. package/dist/subChannel/api/getSubChannel.d.ts +32 -0
  334. package/dist/subChannel/api/getSubChannel.d.ts.map +1 -0
  335. package/dist/subChannel/api/getSubChannels.d.ts +32 -0
  336. package/dist/subChannel/api/getSubChannels.d.ts.map +1 -0
  337. package/dist/subChannel/api/index.d.ts +7 -0
  338. package/dist/subChannel/api/index.d.ts.map +1 -0
  339. package/dist/subChannel/api/querySubChannels.d.ts +32 -0
  340. package/dist/subChannel/api/querySubChannels.d.ts.map +1 -0
  341. package/dist/subChannel/api/tests/createSubChannel.test.d.ts +2 -0
  342. package/dist/subChannel/api/tests/createSubChannel.test.d.ts.map +1 -0
  343. package/dist/subChannel/api/updateSubChannel.d.ts +17 -0
  344. package/dist/subChannel/api/updateSubChannel.d.ts.map +1 -0
  345. package/dist/subChannel/events/index.d.ts +4 -0
  346. package/dist/subChannel/events/index.d.ts.map +1 -0
  347. package/dist/subChannel/events/onSubChannelCreated.d.ts +17 -0
  348. package/dist/subChannel/events/onSubChannelCreated.d.ts.map +1 -0
  349. package/dist/subChannel/events/onSubChannelDeleted.d.ts +17 -0
  350. package/dist/subChannel/events/onSubChannelDeleted.d.ts.map +1 -0
  351. package/dist/subChannel/events/onSubChannelFetched.d.ts +3 -0
  352. package/dist/subChannel/events/onSubChannelFetched.d.ts.map +1 -0
  353. package/dist/subChannel/events/onSubChannelUpdated.d.ts +17 -0
  354. package/dist/subChannel/events/onSubChannelUpdated.d.ts.map +1 -0
  355. package/dist/subChannel/observers/index.d.ts +3 -0
  356. package/dist/subChannel/observers/index.d.ts.map +1 -0
  357. package/dist/subChannel/observers/liveSubChannel.d.ts +21 -0
  358. package/dist/subChannel/observers/liveSubChannel.d.ts.map +1 -0
  359. package/dist/subChannel/observers/liveSubChannels.d.ts +21 -0
  360. package/dist/subChannel/observers/liveSubChannels.d.ts.map +1 -0
  361. package/dist/subChannel/observers/tests/liveSubChannel.test.d.ts +2 -0
  362. package/dist/subChannel/observers/tests/liveSubChannel.test.d.ts.map +1 -0
  363. package/dist/subChannel/observers/tests/liveSubChannels.test.d.ts +2 -0
  364. package/dist/subChannel/observers/tests/liveSubChannels.test.d.ts.map +1 -0
  365. package/dist/subChannel/utils/index.d.ts +8 -0
  366. package/dist/subChannel/utils/index.d.ts.map +1 -0
  367. package/dist/user/events/index.d.ts +0 -1
  368. package/dist/user/events/index.d.ts.map +1 -1
  369. package/dist/user/events/utils.d.ts +1 -1
  370. package/dist/user/events/utils.d.ts.map +1 -1
  371. package/dist/user/observers/liveUser.d.ts +7 -4
  372. package/dist/user/observers/liveUser.d.ts.map +1 -1
  373. package/dist/utils/constants.d.ts +2 -0
  374. package/dist/utils/constants.d.ts.map +1 -1
  375. package/dist/utils/index.d.ts +4 -0
  376. package/dist/utils/index.d.ts.map +1 -0
  377. package/dist/utils/tests/client.d.ts.map +1 -1
  378. package/dist/utils/tests/dummy/channel.d.ts +47 -22
  379. package/dist/utils/tests/dummy/channel.d.ts.map +1 -1
  380. package/dist/utils/tests/dummy/community.d.ts +33 -1
  381. package/dist/utils/tests/dummy/community.d.ts.map +1 -1
  382. package/dist/utils/tests/dummy/index.d.ts +5 -1
  383. package/dist/utils/tests/dummy/index.d.ts.map +1 -1
  384. package/dist/utils/tests/dummy/member.d.ts +2 -0
  385. package/dist/utils/tests/dummy/member.d.ts.map +1 -0
  386. package/dist/utils/tests/dummy/message.d.ts +2 -1
  387. package/dist/utils/tests/dummy/message.d.ts.map +1 -1
  388. package/dist/utils/tests/dummy/post.d.ts +15 -0
  389. package/dist/utils/tests/dummy/post.d.ts.map +1 -1
  390. package/dist/utils/tests/dummy/stream.d.ts +83 -0
  391. package/dist/utils/tests/dummy/stream.d.ts.map +1 -0
  392. package/dist/utils/tests/dummy/subChannel.d.ts +23 -0
  393. package/dist/utils/tests/dummy/subChannel.d.ts.map +1 -0
  394. package/dist/utils/tests/dummy/token.d.ts +11 -0
  395. package/dist/utils/tests/dummy/token.d.ts.map +1 -0
  396. package/dist/utils/tests/dummy/user.d.ts +1 -0
  397. package/dist/utils/tests/dummy/user.d.ts.map +1 -1
  398. package/dist/utils/tests/utils.d.ts +1 -0
  399. package/dist/utils/tests/utils.d.ts.map +1 -1
  400. package/package.json +1 -1
  401. package/src/@types/core/errors.ts +1 -0
  402. package/src/@types/core/events.ts +62 -28
  403. package/src/@types/core/model.ts +2 -0
  404. package/src/@types/core/payload.ts +21 -5
  405. package/src/@types/domains/channel.ts +23 -6
  406. package/src/@types/domains/client.ts +66 -1
  407. package/src/@types/domains/content.ts +4 -3
  408. package/src/@types/domains/group.ts +6 -2
  409. package/src/@types/domains/message.ts +59 -26
  410. package/src/@types/domains/post.ts +2 -2
  411. package/src/@types/domains/subChannel.ts +48 -0
  412. package/src/@types/global.ts +14 -0
  413. package/src/@types/index.ts +1 -0
  414. package/src/cache/api/tests/dropFromCache.test.ts +59 -0
  415. package/src/cache/api/tests/enableCache.test.ts +15 -0
  416. package/src/cache/api/tests/pullFromCache.test.ts +42 -0
  417. package/src/cache/api/tests/upsertInCache.test.ts +60 -0
  418. package/src/cache/utils/tests/encodeKey.test.ts +19 -0
  419. package/src/cache/utils/tests/partialMatch.test.ts +13 -0
  420. package/src/channel/api/addChannelMembers.ts +2 -2
  421. package/src/channel/api/banChannelMembers.ts +5 -3
  422. package/src/channel/api/createChannel.ts +1 -1
  423. package/src/channel/api/getChannels.ts +2 -2
  424. package/src/channel/api/index.ts +3 -0
  425. package/src/channel/api/queryChannelMembers.ts +15 -10
  426. package/src/channel/api/queryChannels.ts +1 -1
  427. package/src/channel/api/removeChannelMembers.ts +9 -1
  428. package/src/channel/api/startReading.ts +53 -0
  429. package/src/channel/api/stopReading.ts +49 -0
  430. package/src/channel/api/tests/addChannelMembers.test.ts +36 -8
  431. package/src/channel/api/tests/createChannel.test.ts +53 -0
  432. package/src/channel/api/tests/getChannel.test.ts +3 -2
  433. package/src/channel/api/tests/joinChannel.test.ts +52 -0
  434. package/src/channel/api/tests/queryChannelMembers.test.ts +27 -11
  435. package/src/channel/api/tests/queryChannels.test.ts +2 -2
  436. package/src/channel/api/tests/removeChannelMembers.test.ts +95 -0
  437. package/src/channel/api/tests/startReading.test.ts +25 -0
  438. package/src/channel/api/tests/stopReading.test.ts +25 -0
  439. package/src/channel/api/unbanChannelMembers.ts +6 -3
  440. package/src/channel/events/index.ts +1 -0
  441. package/src/channel/events/onChannelCreated.ts +1 -1
  442. package/src/channel/events/onChannelDeleted.ts +1 -1
  443. package/src/channel/events/onChannelJoined.ts +12 -7
  444. package/src/channel/events/onChannelLeft.ts +12 -7
  445. package/src/channel/events/onChannelMemberAdded.ts +8 -6
  446. package/src/channel/events/onChannelMemberBanned.ts +7 -4
  447. package/src/channel/events/onChannelMemberRemoved.ts +7 -9
  448. package/src/channel/events/onChannelMemberUnbanned.ts +7 -4
  449. package/src/channel/events/onChannelMuted.ts +34 -0
  450. package/src/channel/events/onChannelUpdated.ts +10 -1
  451. package/src/channel/events/tests/onChannelCreated.test.ts +55 -0
  452. package/src/channel/events/tests/onChannelJoined.test.ts +56 -0
  453. package/src/channel/events/tests/onChannelMemberAdded.test.ts +56 -0
  454. package/src/channel/events/tests/onChannelMemberBanned.test.ts +13 -12
  455. package/src/channel/events/tests/onChannelMemberRemoved.test.ts +56 -0
  456. package/src/channel/events/tests/onChannelMemberUnbanned.test.ts +13 -12
  457. package/src/channel/events/tests/onChannelUpdated.test.ts +55 -0
  458. package/src/channel/observers/index.ts +1 -0
  459. package/src/channel/observers/liveChannel.ts +108 -0
  460. package/src/channel/observers/liveChannelMembers.ts +40 -34
  461. package/src/channel/observers/liveChannels.ts +25 -14
  462. package/src/channel/observers/observeChannel.ts +2 -0
  463. package/src/channel/observers/observeChannels.ts +2 -0
  464. package/src/channel/observers/tests/liveChannelMembers.test.ts +107 -95
  465. package/src/channel/observers/tests/liveChannels.test.ts +385 -126
  466. package/src/channel/utils/index.ts +54 -1
  467. package/src/channel/utils/tests/prepareChannelPayload.test.ts +22 -22
  468. package/src/client/api/accessTokenExpiryWatcher.ts +83 -0
  469. package/src/client/api/activeUser.ts +1 -1
  470. package/src/client/api/connectClient.ts +114 -26
  471. package/src/client/api/createClient.ts +10 -2
  472. package/src/client/api/disconnectClient.ts +26 -2
  473. package/src/client/api/getChatSettings.ts +22 -0
  474. package/src/client/api/getSocialSettings.ts +24 -0
  475. package/src/client/api/getToken.ts +6 -6
  476. package/src/client/api/index.ts +2 -0
  477. package/src/client/api/renewal.ts +74 -0
  478. package/src/client/api/setSessionState.ts +75 -0
  479. package/src/client/api/terminateClient.ts +20 -0
  480. package/src/client/api/tests/accessTokenExpiryWatcher.test.ts +129 -0
  481. package/src/client/api/tests/activeClient.test.ts +20 -0
  482. package/src/client/api/tests/activeUser.test.ts +20 -0
  483. package/src/client/api/tests/connectClient.test.ts +84 -0
  484. package/src/client/api/tests/createClient.test.ts +48 -0
  485. package/src/client/api/tests/disconnectClient.test.ts +78 -0
  486. package/src/client/api/tests/getToken.test.ts +36 -0
  487. package/src/client/api/tests/renewal.test.ts +67 -0
  488. package/src/client/api/tests/setSessionState.test.ts +62 -0
  489. package/src/client/api/tests/terminateClient.test.ts +29 -0
  490. package/src/client/events/index.ts +2 -0
  491. package/src/client/events/onClientBanned.ts +12 -5
  492. package/src/client/events/onSessionStateChange.ts +31 -0
  493. package/src/client/events/onTokenExpired.ts +26 -0
  494. package/src/client/events/onTokenTerminated.ts +20 -0
  495. package/src/client/events/tests/onSessionStateChange.test.ts +37 -0
  496. package/src/client/events/tests/onTokenTerminated.test.ts +37 -0
  497. package/src/client/tests/connectClient.test.ts +40 -0
  498. package/src/client/utils/setClientToken.ts +39 -0
  499. package/src/comment/api/createComment.ts +3 -3
  500. package/src/comment/api/tests/createComment.test.ts +49 -0
  501. package/src/comment/api/tests/getComments.test.ts +36 -0
  502. package/src/comment/events/tests/onCommentCreated.test.ts +27 -0
  503. package/src/comment/events/tests/onCommentDeleted.test.ts +27 -0
  504. package/src/comment/events/utils.ts +1 -1
  505. package/src/comment/observers/liveComments.ts +8 -8
  506. package/src/community/api/queryCommunities.ts +3 -2
  507. package/src/community/api/queryCommunityMembers.ts +59 -14
  508. package/src/community/api/test/addCommunityMember.test.ts +71 -0
  509. package/src/community/api/test/addCommunityMemberRole.test.ts +67 -0
  510. package/src/community/api/test/createCommunity.test.ts +61 -0
  511. package/src/community/api/test/deleteCommunity.test.ts +74 -0
  512. package/src/community/api/test/getCommunities.test.ts +73 -0
  513. package/src/community/api/test/getCommunity.test.ts +69 -0
  514. package/src/community/api/test/getRecommendedCommunities.test.ts +102 -0
  515. package/src/community/api/test/getTopTrendingCommunities.test.ts +102 -0
  516. package/src/community/api/test/joinCommunity.test.ts +70 -0
  517. package/src/community/api/test/leaveCommunity.test.ts +78 -0
  518. package/src/community/api/test/queryCommunity.test.ts +108 -0
  519. package/src/community/api/test/queryCommunityMembers.test.ts +122 -0
  520. package/src/community/api/test/removeCommunityMemberRole.test.ts +67 -0
  521. package/src/community/api/test/removeCommunityMembers.test.ts +75 -0
  522. package/src/community/api/test/updateCommunity.test.ts +65 -0
  523. package/src/community/events/test/onCommunityCreated.test.ts +46 -0
  524. package/src/community/events/test/onCommunityDeleted.test.ts +35 -0
  525. package/src/community/events/test/onCommunityJoined.test.ts +50 -0
  526. package/src/community/events/test/onCommunityLeft.test.ts +50 -0
  527. package/src/community/events/test/onCommunityUpdated.test.ts +49 -0
  528. package/src/community/events/test/onCommunityUserAdded.test.ts +50 -0
  529. package/src/community/events/test/onCommunityUserBanned.test.ts +50 -0
  530. package/src/community/events/test/onCommunityUserRemoved.test.ts +50 -0
  531. package/src/community/events/test/onCommunityUserUnbaned.test.ts +50 -0
  532. package/src/community/events/test/utils.test.ts +158 -0
  533. package/src/community/events/utils.ts +18 -10
  534. package/src/core/events.ts +11 -20
  535. package/src/core/model/idResolvers.ts +1 -0
  536. package/src/core/model/identifyModel.ts +1 -0
  537. package/src/core/model/index.ts +15 -0
  538. package/src/core/query/filtering.ts +2 -9
  539. package/src/core/query/query.ts +2 -34
  540. package/src/core/subscription.ts +50 -10
  541. package/src/core/tests/query/query/runQuery.test.ts +15 -38
  542. package/src/core/tests/subscription.test.ts +15 -0
  543. package/src/core/transports/http.ts +36 -1
  544. package/src/core/transports/mqtt.ts +1 -1
  545. package/src/external/api/createUserToken.ts +2 -2
  546. package/src/feed/api/queryGlobalFeed.ts +1 -1
  547. package/src/feed/api/test/queryGlobalFeed.test.ts +138 -0
  548. package/src/follow/events/utils.ts +1 -1
  549. package/src/follow/observers/liveFollowers.ts +8 -8
  550. package/src/follow/observers/liveFollowings.ts +8 -8
  551. package/src/group/utils/index.ts +1 -0
  552. package/src/group/utils/test/withUsers.test.ts +103 -0
  553. package/src/group/utils/withUser.ts +92 -0
  554. package/src/index.ts +4 -0
  555. package/src/message/api/createMessage.ts +60 -29
  556. package/src/message/api/deleteMessage.ts +6 -6
  557. package/src/message/api/getMessage.ts +5 -4
  558. package/src/message/api/getMessages.ts +7 -5
  559. package/src/message/api/queryMessages.ts +13 -25
  560. package/src/message/api/tests/createMessage.test.ts +129 -37
  561. package/src/message/api/tests/deleteMessage.test.ts +18 -12
  562. package/src/message/api/tests/getMessage.test.ts +6 -4
  563. package/src/message/api/tests/getMessages.test.ts +7 -8
  564. package/src/message/api/tests/queryMessages.test.ts +20 -23
  565. package/src/message/api/tests/updateMessage.test.ts +13 -12
  566. package/src/message/api/updateMessage.ts +12 -9
  567. package/src/message/events/index.ts +7 -1
  568. package/src/message/events/onMessageCreated.ts +50 -3
  569. package/src/message/events/onMessageDeleted.ts +14 -2
  570. package/src/message/events/onMessageFetched.ts +1 -1
  571. package/src/message/events/onMessageFlagCleared.ts +34 -0
  572. package/src/message/events/onMessageFlagged.ts +33 -0
  573. package/src/message/events/onMessageReactionAdded.ts +35 -0
  574. package/src/message/events/onMessageReactionRemoved.ts +40 -0
  575. package/src/message/events/onMessageUnflagged.ts +32 -0
  576. package/src/message/events/onMessageUpdated.ts +14 -10
  577. package/src/message/observers/liveMessage.ts +42 -23
  578. package/src/message/observers/liveMessages.ts +30 -16
  579. package/src/message/observers/observeMessage.ts +1 -0
  580. package/src/message/observers/observeMessages.ts +6 -5
  581. package/src/message/tests/events.test.ts +53 -0
  582. package/src/message/tests/observers/liveMessage.test.ts +46 -49
  583. package/src/message/tests/observers/liveMessages.test.ts +45 -37
  584. package/src/message/utils/index.ts +129 -0
  585. package/src/post/api/queryPosts.ts +9 -0
  586. package/src/post/api/tests/queryPosts.test.ts +149 -0
  587. package/src/post/events/tests/onPostApproved.test.ts +33 -0
  588. package/src/post/events/tests/onPostCreated.test.ts +33 -0
  589. package/src/post/events/tests/onPostDeclined.test.ts +33 -0
  590. package/src/post/events/tests/onPostDeleted.test.ts +33 -0
  591. package/src/post/events/tests/onPostFlagged.test.ts +33 -0
  592. package/src/post/events/tests/onPostReactionAdded.test.ts +40 -0
  593. package/src/post/events/tests/onPostReactionRemoved.test.ts +40 -0
  594. package/src/post/events/tests/onPostUnflagged.test.ts +33 -0
  595. package/src/post/events/tests/onPostUpdated.test.ts +33 -0
  596. package/src/post/events/utils.ts +1 -1
  597. package/src/post/observers/livePosts.ts +32 -12
  598. package/src/post/observers/tests/livePosts.test.ts +302 -0
  599. package/src/reaction/api/addReaction.ts +1 -0
  600. package/src/reaction/api/removeReaction.ts +6 -1
  601. package/src/reaction/events/onReactionAdded.ts +4 -7
  602. package/src/reaction/events/onReactionRemoved.ts +4 -7
  603. package/src/reaction/events/onReactorAdded.ts +4 -2
  604. package/src/reaction/events/onReactorRemoved.ts +4 -7
  605. package/src/reaction/observers/liveReactions.ts +6 -6
  606. package/src/reaction/utils/dispatchReactable.ts +1 -1
  607. package/src/report/api/createReport.ts +28 -18
  608. package/src/report/api/deleteReport.ts +28 -18
  609. package/src/report/api/isReportedByMe.ts +9 -2
  610. package/src/stream/api/tests/createStream.test.ts +30 -0
  611. package/src/stream/api/tests/deleteStream.test.ts +48 -0
  612. package/src/stream/api/tests/getStream.test.ts +23 -0
  613. package/src/subChannel/api/createSubChannel.ts +41 -0
  614. package/src/subChannel/api/deleteSubChannel.ts +53 -0
  615. package/src/subChannel/api/getSubChannel.ts +85 -0
  616. package/src/subChannel/api/getSubChannels.ts +77 -0
  617. package/src/subChannel/api/index.ts +8 -0
  618. package/src/subChannel/api/querySubChannels.ts +115 -0
  619. package/src/subChannel/api/tests/createSubChannel.test.ts +103 -0
  620. package/src/subChannel/api/updateSubChannel.ts +43 -0
  621. package/src/subChannel/events/index.ts +3 -0
  622. package/src/subChannel/events/onSubChannelCreated.ts +32 -0
  623. package/src/subChannel/events/onSubChannelDeleted.ts +44 -0
  624. package/src/subChannel/events/onSubChannelFetched.ts +12 -0
  625. package/src/subChannel/events/onSubChannelUpdated.ts +32 -0
  626. package/src/subChannel/observers/index.ts +2 -0
  627. package/src/subChannel/observers/liveSubChannel.ts +84 -0
  628. package/src/subChannel/observers/liveSubChannels.ts +137 -0
  629. package/src/subChannel/observers/tests/liveSubChannel.test.ts +212 -0
  630. package/src/subChannel/observers/tests/liveSubChannels.test.ts +206 -0
  631. package/src/subChannel/utils/index.ts +50 -0
  632. package/src/user/events/index.ts +0 -1
  633. package/src/user/events/utils.ts +1 -1
  634. package/src/user/observers/liveUser.ts +29 -23
  635. package/src/user/tests/observers/liveUser.test.ts +5 -9
  636. package/src/utils/constants.ts +2 -0
  637. package/src/utils/index.ts +52 -0
  638. package/src/utils/tests/client.ts +18 -2
  639. package/src/utils/tests/dummy/channel.ts +123 -117
  640. package/src/utils/tests/dummy/community.ts +67 -3
  641. package/src/utils/tests/dummy/index.ts +6 -1
  642. package/src/utils/tests/dummy/member.ts +18 -0
  643. package/src/utils/tests/dummy/message.ts +37 -16
  644. package/src/utils/tests/dummy/post.ts +34 -0
  645. package/src/utils/tests/dummy/stream.ts +86 -0
  646. package/src/utils/tests/dummy/subChannel.ts +51 -0
  647. package/src/utils/tests/dummy/token.ts +12 -0
  648. package/src/utils/tests/dummy/user.ts +2 -0
  649. package/src/utils/tests/utils.ts +2 -0
  650. package/dist/channel/utils/prepareChannelPayload.d.ts +0 -3
  651. package/dist/channel/utils/prepareChannelPayload.d.ts.map +0 -1
  652. package/src/channel/utils/prepareChannelPayload.ts +0 -31
package/dist/index.cjs.js CHANGED
@@ -106,6 +106,78 @@ const isProduction = ((_a$1 = safeProcess.env) === null || _a$1 === void 0 ? voi
106
106
  var _a, _b;
107
107
  const VERSION$1 = (_b = (_a = safeProcess.env) === null || _a === void 0 ? void 0 : _a.VERSION) !== null && _b !== void 0 ? _b : '__dev__';
108
108
 
109
+ // cache constants
110
+ const CACHE_KEY_GET = 'get';
111
+ const CACHE_KEY_TOMBSTONE = 'dead';
112
+ const CACHE_LIFESPAN = 1 * 60 * 1000; // 1 minute
113
+ const CACHE_LIFESPAN_TOMBSTONE = 3 * 60 * 1000; // 3 minutes
114
+ /**
115
+ * Shallow-clones an object and sort its keys
116
+ *
117
+ * @param source a plain object to clone
118
+ * @returns a clone of source, with keys sorted with default javascript sorting
119
+ *
120
+ * @category Cache
121
+ * @hidden
122
+ */
123
+ const normalize = (source) => Object.keys(source)
124
+ .sort()
125
+ .reduce((acc, key) => (Object.assign(Object.assign({}, acc), { [key]: source[key] })), {});
126
+ /**
127
+ * Encodes a given {@link Amity.CacheKey} to a plain string
128
+ *
129
+ * @param key the key to encode
130
+ * @returns an encoded string
131
+ *
132
+ * @category Cache
133
+ * @hidden
134
+ */
135
+ const encodeKey = (key) => JSON.stringify(key, (_, val) => (typeof val === 'object' ? normalize(val) : val));
136
+ /**
137
+ * Decodes a string back into a {@link Amity.CacheKey}
138
+
139
+ *
140
+ * @param key the string key to decode
141
+ * @returns a plain Amity.CacheKey object.
142
+ *
143
+ * @category Cache
144
+ * @hidden
145
+ */
146
+ const decodeKey = (key) => JSON.parse(key);
147
+ /**
148
+ * Performs a recursive partial deep equal check on two objects.
149
+ *
150
+ * @param predicate the reference object containing the partial information
151
+ * @param candidate the object to check against
152
+ * @returns true if the candidate contains all the values of the predicate
153
+ *
154
+ * @category Cache
155
+ */
156
+ const partialMatch = (predicate, candidate) => {
157
+ if (predicate === candidate)
158
+ return true;
159
+ // if one or the other is nullish, there can't be equality
160
+ if (!predicate || !candidate)
161
+ return false;
162
+ // we only perform recursive check on objects
163
+ if (typeof predicate !== 'object') {
164
+ return false;
165
+ }
166
+ // recursively call for partial match based on the predicate
167
+ return Object.keys(predicate).every(key => partialMatch(predicate[key], candidate[key]));
168
+ };
169
+ /**
170
+ * checks if passed error code is included in
171
+ * Tombstone errors list
172
+ *
173
+ * @param errorCode as {@link Amity.ServerError}
174
+ * @returns success boolean if the given errorCode
175
+ * is included in Tombstone errors list
176
+ *
177
+ * @category Cache
178
+ */
179
+ const checkIfShouldGoesToTombstone = (errorCode) => [400400 /* Amity.ServerError.ITEM_NOT_FOUND */, 400300 /* Amity.ServerError.FORBIDDEN */].includes(errorCode);
180
+
109
181
  /**
110
182
  * Type guard to find if the a given decoded backend token uses "skip/limit" pagination style
111
183
  *
@@ -255,12 +327,180 @@ const toPageRaw = (token) => {
255
327
  return undefined;
256
328
  };
257
329
 
330
+ /* eslint-disable no-use-before-define */
331
+ /**
332
+ * Type guard to check and cast that a given async function is has the ".locally" property
333
+ *
334
+ * @param func any SDK APi function
335
+ * @returns success boolean if the function has a 'locally' twin
336
+ *
337
+ * @hidden
338
+ */
339
+ const isFetcher = (func) => 'locally' in func;
340
+ /**
341
+ * Type guard to check and cast that a given async function is has the ".optimistically" property
342
+ *
343
+ * @param func any SDK APi function
344
+ * @returns success boolean if the function has an 'optimistically' twin
345
+ *
346
+ * @hidden
347
+ */
348
+ const isMutator = (func) => 'optimistically' in func;
349
+ /**
350
+ * Type guard to check and cast that a given async function is has
351
+ * the ".locally" or ".optimistically" property
352
+ *
353
+ * @param func any SDK APi function
354
+ * @returns success boolean if the function has an offline twin
355
+ *
356
+ * @hidden
357
+ */
358
+ const isOffline = (func) => isFetcher(func) || isMutator(func);
359
+ /**
360
+ * Type guard to check and cast that a given object has the "cachedAt" property
361
+ *
362
+ * @param model any object to check on
363
+ * @returns success boolean if the object has property "cachedAt"
364
+ *
365
+ * @hidden
366
+ */
367
+ const isCachable = (model) => model === null || model === void 0 ? void 0 : model.hasOwnProperty('cachedAt');
368
+ /**
369
+ * Checks if a model is considered local (cachedAt === -1)
370
+ *
371
+ * @param model any cachable object to check
372
+ * @returns success boolean if the object is marked as local
373
+ *
374
+ * @hidden
375
+ */
376
+ const isLocal = (model) => {
377
+ return isCachable(model) && (model === null || model === void 0 ? void 0 : model.cachedAt) === -1;
378
+ };
379
+ /**
380
+ * Checks if a model is considered fresh
381
+ *
382
+ * @param model any cachable object to check
383
+ * @param lifeSpan the supposedly duration for which the object is considered synced
384
+ * @returns success boolean if the object is below the given lifespan
385
+ *
386
+ * @hidden
387
+ */
388
+ const isFresh = (model, lifeSpan = CACHE_LIFESPAN) => {
389
+ var _a;
390
+ return Date.now() - ((_a = model === null || model === void 0 ? void 0 : model.cachedAt) !== null && _a !== void 0 ? _a : 0) <= lifeSpan;
391
+ };
392
+ /**
393
+ * ```js
394
+ * import { createQuery, getUser } from '@amityco/ts-sdk'
395
+ * const query = createQuery(getUser, 'foobar')
396
+ * ```
397
+ *
398
+ * Creates a wrapper for the API call you wish to call.
399
+ * This wrapper is necessary to create for optimistically calls
400
+ *
401
+ *
402
+ * @param func A compatible API function from the ts sdk
403
+ * @param args The arguments to pass to the function passed as `fn`
404
+ * @returns A wrapper containing both the function and its future arguments
405
+ *
406
+ * @category Query
407
+ */
408
+ const createQuery = (func, ...args) => ({ func, args });
409
+ /**
410
+ * ```js
411
+ * import { queryOptions } from '@amityco/ts-sdk'
412
+ * const options = queryOptions('no_fetch', lifeSpan)
413
+ * ```
414
+ *
415
+ * Creates a query options object based on the query policy passed
416
+ *
417
+ * @param policy The policy to apply to a query
418
+ * @returns A properly set query options object
419
+ *
420
+ * @category Query
421
+ */
422
+ const queryOptions = (policy, lifeSpan = CACHE_LIFESPAN) => {
423
+ if (policy === 'cache_only')
424
+ return { lifeSpan: Infinity };
425
+ return { lifeSpan: lifeSpan < CACHE_LIFESPAN ? CACHE_LIFESPAN : lifeSpan };
426
+ };
427
+ /**
428
+ * ```js
429
+ * import { createQuery, getUser, runQuery } from '@amityco/ts-sdk'
430
+ * const query = createQuery(getUser, client, 'foobar')
431
+ * runQuery(query, user => console.log(user))
432
+ * ```
433
+ *
434
+ * Calls an API function wrapped around a Amity.Query, and executes the callback whenever
435
+ * a value is available. The value can be picked either from the local cache and/or
436
+ * from the server afterwards depending on the query options passed
437
+ *
438
+ * @param query A query object wrapping the call to be made
439
+ * @param callback A function to execute when a value is available
440
+ * @param options the query options
441
+ *
442
+ * @category Query
443
+ */
444
+ const runQuery = ({ func, args }, callback, options = queryOptions('cache_then_server')) => {
445
+ let local;
446
+ const { lifeSpan } = queryOptions('cache_then_server', options.lifeSpan);
447
+ // offline first
448
+ if (isOffline(func)) {
449
+ try {
450
+ local = isMutator(func) ? func.optimistically(...args) : func.locally(...args);
451
+ }
452
+ catch (error) {
453
+ callback === null || callback === void 0 ? void 0 : callback(createSnapshot(undefined, {
454
+ origin: 'local',
455
+ loading: false,
456
+ error,
457
+ }));
458
+ }
459
+ const shouldAbort = isCachable(local) && isFresh(local, lifeSpan);
460
+ callback === null || callback === void 0 ? void 0 : callback(createSnapshot(local, {
461
+ origin: 'local',
462
+ loading: !(isFetcher(func) && shouldAbort),
463
+ }));
464
+ if (shouldAbort)
465
+ return;
466
+ }
467
+ else {
468
+ callback === null || callback === void 0 ? void 0 : callback(createSnapshot(undefined, {
469
+ origin: 'local',
470
+ loading: true,
471
+ }));
472
+ }
473
+ func(...args)
474
+ .then(fresh => {
475
+ // @ts-ignore i know.
476
+ // isLocal(local) && syncInCache(local, fresh)
477
+ callback === null || callback === void 0 ? void 0 : callback(createSnapshot(fresh, {
478
+ origin: 'server',
479
+ loading: false,
480
+ }));
481
+ })
482
+ .catch(error => {
483
+ callback === null || callback === void 0 ? void 0 : callback(createSnapshot(undefined, {
484
+ origin: 'server',
485
+ loading: false,
486
+ error,
487
+ }));
488
+ });
489
+ };
490
+ // eslint-disable-next-line no-redeclare
491
+ function createSnapshot(data, options) {
492
+ if (isPaged(data) || isCachable(data))
493
+ return Object.assign(Object.assign({}, options), data);
494
+ return Object.assign(Object.assign({}, options), { data });
495
+ }
496
+
258
497
  /** @hidden */
259
498
  const idResolvers = {
260
499
  user: ({ userId }) => userId,
261
500
  file: ({ fileId }) => fileId,
262
501
  role: ({ roleId }) => roleId,
263
502
  channel: ({ channelId }) => channelId,
503
+ subChannel: ({ subChannelId }) => subChannelId,
264
504
  channelUsers: ({ channelId, userId }) => `${channelId}#${userId}`,
265
505
  message: ({ messageId }) => messageId,
266
506
  community: ({ communityId }) => communityId,
@@ -297,6 +537,7 @@ const CRITERIAS = {
297
537
  user: ['userId', 'avatarFileId'],
298
538
  role: ['roleId'],
299
539
  channel: ['channelId', 'rateLimit'],
540
+ subChannel: ['subChannelId'],
300
541
  channelUsers: ['channelId', 'userId', 'membership'],
301
542
  message: ['messageId'],
302
543
  community: ['communityId', 'postSetting'],
@@ -355,6 +596,7 @@ const PAYLOAD2MODEL = {
355
596
  files: 'file',
356
597
  roles: 'role',
357
598
  channels: 'channel',
599
+ messageFeeds: 'subChannel',
358
600
  channelUsers: 'channelUsers',
359
601
  messages: 'message',
360
602
  communities: 'community',
@@ -368,277 +610,17 @@ const PAYLOAD2MODEL = {
368
610
  videoStreamings: 'stream',
369
611
  follows: 'follow',
370
612
  followCounts: 'followCount',
371
- };
613
+ };
614
+ /** hidden */
615
+ const hasUpdates = (prevData, nextData) => {
616
+ return new Date(prevData.updatedAt) < new Date(nextData.updatedAt);
617
+ };
618
+ /** hidden */
619
+ function getFutureDate(date = new Date().toISOString()) {
620
+ return new Date(new Date(date).getTime() + 1).toISOString();
621
+ }
372
622
 
373
- // cache constants
374
- const CACHE_KEY_GET = 'get';
375
- const CACHE_KEY_TOMBSTONE = 'dead';
376
- const CACHE_LIFESPAN = 1 * 60 * 1000; // 1 minute
377
- const CACHE_LIFESPAN_TOMBSTONE = 3 * 60 * 1000; // 3 minutes
378
- /**
379
- * Shallow-clones an object and sort its keys
380
- *
381
- * @param source a plain object to clone
382
- * @returns a clone of source, with keys sorted with default javascript sorting
383
- *
384
- * @category Cache
385
- * @hidden
386
- */
387
- const normalize = (source) => Object.keys(source)
388
- .sort()
389
- .reduce((acc, key) => (Object.assign(Object.assign({}, acc), { [key]: source[key] })), {});
390
- /**
391
- * Encodes a given {@link Amity.CacheKey} to a plain string
392
- *
393
- * @param key the key to encode
394
- * @returns an encoded string
395
- *
396
- * @category Cache
397
- * @hidden
398
- */
399
- const encodeKey = (key) => JSON.stringify(key, (_, val) => (typeof val === 'object' ? normalize(val) : val));
400
- /**
401
- * Decodes a string back into a {@link Amity.CacheKey}
402
-
403
- *
404
- * @param key the string key to decode
405
- * @returns a plain Amity.CacheKey object.
406
- *
407
- * @category Cache
408
- * @hidden
409
- */
410
- const decodeKey = (key) => JSON.parse(key);
411
- /**
412
- * Performs a recursive partial deep equal check on two objects.
413
- *
414
- * @param predicate the reference object containing the partial information
415
- * @param candidate the object to check against
416
- * @returns true if the candidate contains all the values of the predicate
417
- *
418
- * @category Cache
419
- */
420
- const partialMatch = (predicate, candidate) => {
421
- if (predicate === candidate)
422
- return true;
423
- // if one or the other is nullish, there can't be equality
424
- if (!predicate || !candidate)
425
- return false;
426
- // we only perform recursive check on objects
427
- if (typeof predicate !== 'object') {
428
- return false;
429
- }
430
- // recursively call for partial match based on the predicate
431
- return Object.keys(predicate).every(key => partialMatch(predicate[key], candidate[key]));
432
- };
433
- /**
434
- * checks if passed error code is included in
435
- * Tombstone errors list
436
- *
437
- * @param errorCode as {@link Amity.ServerError}
438
- * @returns success boolean if the given errorCode
439
- * is included in Tombstone errors list
440
- *
441
- * @category Cache
442
- */
443
- const checkIfShouldGoesToTombstone = (errorCode) => [400400 /* Amity.ServerError.ITEM_NOT_FOUND */, 400300 /* Amity.ServerError.FORBIDDEN */].includes(errorCode);
444
-
445
- /* eslint-disable no-use-before-define */
446
- /**
447
- * Type guard to check and cast that a given async function is has the ".locally" property
448
- *
449
- * @param func any SDK APi function
450
- * @returns success boolean if the function has a 'locally' twin
451
- *
452
- * @hidden
453
- */
454
- const isFetcher = (func) => 'locally' in func;
455
- /**
456
- * Type guard to check and cast that a given async function is has the ".optimistically" property
457
- *
458
- * @param func any SDK APi function
459
- * @returns success boolean if the function has an 'optimistically' twin
460
- *
461
- * @hidden
462
- */
463
- const isMutator = (func) => 'optimistically' in func;
464
- /**
465
- * Type guard to check and cast that a given async function is has
466
- * the ".locally" or ".optimistically" property
467
- *
468
- * @param func any SDK APi function
469
- * @returns success boolean if the function has an offline twin
470
- *
471
- * @hidden
472
- */
473
- const isOffline = (func) => isFetcher(func) || isMutator(func);
474
- /**
475
- * Type guard to check and cast that a given object has the "cachedAt" property
476
- *
477
- * @param model any object to check on
478
- * @returns success boolean if the object has property "cachedAt"
479
- *
480
- * @hidden
481
- */
482
- const isCachable = (model) => model === null || model === void 0 ? void 0 : model.hasOwnProperty('cachedAt');
483
- /**
484
- * Checks if a model is considered local (cachedAt === -1)
485
- *
486
- * @param model any cachable object to check
487
- * @returns success boolean if the object is marked as local
488
- *
489
- * @hidden
490
- */
491
- const isLocal = (model) => {
492
- return isCachable(model) && (model === null || model === void 0 ? void 0 : model.cachedAt) === -1;
493
- };
494
- /**
495
- * Checks if a model is considered fresh
496
- *
497
- * @param model any cachable object to check
498
- * @param lifeSpan the supposedly duration for which the object is considered synced
499
- * @returns success boolean if the object is below the given lifespan
500
- *
501
- * @hidden
502
- */
503
- const isFresh = (model, lifeSpan = CACHE_LIFESPAN) => {
504
- var _a;
505
- return Date.now() - ((_a = model === null || model === void 0 ? void 0 : model.cachedAt) !== null && _a !== void 0 ? _a : 0) <= lifeSpan;
506
- };
507
- /**
508
- * ```js
509
- * import { createQuery, getUser } from '@amityco/ts-sdk'
510
- * const query = createQuery(getUser, 'foobar')
511
- * ```
512
- *
513
- * Creates a wrapper for the API call you wish to call.
514
- * This wrapper is necessary to create for optimistically calls
515
- *
516
- *
517
- * @param func A compatible API function from the ts sdk
518
- * @param args The arguments to pass to the function passed as `fn`
519
- * @returns A wrapper containing both the function and its future arguments
520
- *
521
- * @category Query
522
- */
523
- const createQuery = (func, ...args) => ({ func, args });
524
- /**
525
- * ```js
526
- * import { queryOptions } from '@amityco/ts-sdk'
527
- * const options = queryOptions('no_fetch', lifeSpan)
528
- * ```
529
- *
530
- * Creates a query options object based on the query policy passed
531
- *
532
- * @param policy The policy to apply to a query
533
- * @returns A properly set query options object
534
- *
535
- * @category Query
536
- */
537
- const queryOptions = (policy, lifeSpan = CACHE_LIFESPAN) => {
538
- if (policy === 'cache_only')
539
- return { lifeSpan: Infinity };
540
- return { lifeSpan: lifeSpan < CACHE_LIFESPAN ? CACHE_LIFESPAN : lifeSpan };
541
- };
542
- /**
543
- * ```js
544
- * import { createQuery, getUser, runQuery } from '@amityco/ts-sdk'
545
- * const query = createQuery(getUser, client, 'foobar')
546
- * runQuery(query, user => console.log(user))
547
- * ```
548
- *
549
- * Calls an API function wrapped around a Amity.Query, and executes the callback whenever
550
- * a value is available. The value can be picked either from the local cache and/or
551
- * from the server afterwards depending on the query options passed
552
- *
553
- * @param query A query object wrapping the call to be made
554
- * @param callback A function to execute when a value is available
555
- * @param options the query options
556
- *
557
- * @category Query
558
- */
559
- const runQuery = ({ func, args }, callback, options = queryOptions('cache_then_server')) => {
560
- let local;
561
- const { lifeSpan } = queryOptions('cache_then_server', options.lifeSpan);
562
- // offline first
563
- if (isOffline(func)) {
564
- try {
565
- local = isMutator(func) ? func.optimistically(...args) : func.locally(...args);
566
- }
567
- catch (error) {
568
- callback === null || callback === void 0 ? void 0 : callback(createSnapshot(undefined, {
569
- origin: 'local',
570
- loading: false,
571
- error,
572
- }));
573
- }
574
- const shouldAbort = isCachable(local) && isFresh(local, lifeSpan);
575
- callback === null || callback === void 0 ? void 0 : callback(createSnapshot(local, {
576
- origin: 'local',
577
- loading: !(isFetcher(func) && shouldAbort),
578
- }));
579
- if (shouldAbort)
580
- return;
581
- }
582
- else {
583
- callback === null || callback === void 0 ? void 0 : callback(createSnapshot(undefined, {
584
- origin: 'local',
585
- loading: true,
586
- }));
587
- }
588
- let optimisticArgs = args;
589
- /* get args for optimistic method calls
590
- *
591
- * On optimistic updates, the modal key for the update needs to be passed to
592
- * the server so as to avoid duplicate modal creation
593
- *
594
- * ex: on creating a new message pass the modalKey is messageId, pass this
595
- * id onto the server so that a duplicate with seperate messageId is not
596
- * created.
597
- */
598
- if (isMutator(func)) {
599
- // @ts-ignore
600
- const modelKey = local && local.data && identifyModelKey(local.data);
601
- if (modelKey) {
602
- /*
603
- * modal key is only required for create as update and delete queries pass
604
- * the modal key in the param itself
605
- * For update & delete the first argument is always an id which is of type
606
- * string, whereas for create the first and only argument is the param object
607
- *
608
- * When creating an AmityObject optimistically we need to pass the modal key
609
- * on to the server. ex: for create message modal key will be 'messageId`
610
- */
611
- if (typeof args[0] !== 'string') {
612
- // @ts-ignore
613
- optimisticArgs = [Object.assign(Object.assign({}, args[0]), { [modelKey]: local.data[modelKey] })];
614
- }
615
- }
616
- }
617
- func(...optimisticArgs)
618
- .then(fresh => {
619
- // @ts-ignore i know.
620
- // isLocal(local) && syncInCache(local, fresh)
621
- callback === null || callback === void 0 ? void 0 : callback(createSnapshot(fresh, {
622
- origin: 'server',
623
- loading: false,
624
- }));
625
- })
626
- .catch(error => {
627
- callback === null || callback === void 0 ? void 0 : callback(createSnapshot(undefined, {
628
- origin: 'server',
629
- loading: false,
630
- error,
631
- }));
632
- });
633
- };
634
- // eslint-disable-next-line no-redeclare
635
- function createSnapshot(data, options) {
636
- if (isPaged(data) || isCachable(data))
637
- return Object.assign(Object.assign({}, options), data);
638
- return Object.assign(Object.assign({}, options), { data });
639
- }
640
-
641
- /* eslint-disable max-classes-per-file */
623
+ /* eslint-disable max-classes-per-file */
642
624
  /**
643
625
  * Generic ASC error
644
626
  * @category Errors
@@ -1094,16 +1076,10 @@ const filterByChannelMembership = (collection, membership, userId) => {
1094
1076
  'get',
1095
1077
  channelUserCacheKey,
1096
1078
  ])) === null || _a === void 0 ? void 0 : _a.data;
1097
- // if channel user is defined for user, user is a member
1098
- if (membership === 'member' && channelUser) {
1099
- return true;
1100
- }
1101
- // if channel user by user id not found, user is not a member of that
1102
- // channel
1103
- if (membership === 'notMember' && !channelUser) {
1079
+ if (membership === 'member' && channelUser && channelUser.membership !== 'none') {
1104
1080
  return true;
1105
1081
  }
1106
- return false;
1082
+ return membership === 'notMember' && (!channelUser || channelUser.membership === 'none');
1107
1083
  });
1108
1084
  };
1109
1085
 
@@ -1164,19 +1140,9 @@ const WS_EVENTS = [
1164
1140
  'connect_error',
1165
1141
  'reconnect_error',
1166
1142
  'reconnect_failed',
1167
- 'v3.channel.didCreate',
1168
- 'v3.channel.didUpdate',
1169
- 'v3.channel.didDelete',
1170
- 'v3.channel.didJoin',
1171
- 'v3.channel.didLeave',
1172
- 'v3.channel.didAddUsers',
1173
- 'v3.channel.didRemoveUsers',
1174
- 'v3.channel.didBan',
1175
- 'v3.channel.didUnban',
1176
- 'v3.message.didFetch',
1177
- 'v3.message.didCreate',
1178
- 'v3.message.didUpdate',
1179
- 'v3.message.didDelete',
1143
+ 'sessionStateChange',
1144
+ // for internal use by accessTokenExpiryWatcher
1145
+ 'tokenExpired',
1180
1146
  ];
1181
1147
  const MQTT_EVENTS = [
1182
1148
  'connect',
@@ -1186,6 +1152,7 @@ const MQTT_EVENTS = [
1186
1152
  'close',
1187
1153
  'end',
1188
1154
  'reconnect',
1155
+ 'user.didGlobalBan',
1189
1156
  ];
1190
1157
  /** @hidden */
1191
1158
  const createEventEmitter = () => {
@@ -1203,12 +1170,16 @@ const createEventEmitter = () => {
1203
1170
  */
1204
1171
  const proxyWebsocketEvents = (ws, emitter) => {
1205
1172
  WS_EVENTS.forEach(event => {
1206
- ws.on(event, (param) => emitter.emit(event, param));
1173
+ ws.on(event, (param) => {
1174
+ emitter.emit(event, param);
1175
+ });
1207
1176
  });
1208
1177
  };
1209
1178
  const proxyMqttEvents = (mqttClient, emitter) => {
1210
1179
  MQTT_EVENTS.forEach(event => {
1211
- mqttClient.on(event, (...params) => emitter.emit(event, params.length === 1 ? params[0] : params));
1180
+ mqttClient.on(event, (...params) => {
1181
+ emitter.emit(event, params.length === 1 ? params[0] : params);
1182
+ });
1212
1183
  });
1213
1184
  // @ts-ignore
1214
1185
  mqttClient.on('message', (topic, payload) => {
@@ -1292,6 +1263,7 @@ const getCommunityUserTopic = (path, level) => {
1292
1263
  return path;
1293
1264
  }
1294
1265
  };
1266
+ const getNetworkId = (user) => user.path.split('/user/')[0];
1295
1267
  const getCommunityTopic = ({ path }, level = exports.SubscriptionLevels.COMMUNITY) => getCommunityUserTopic(path, level);
1296
1268
  const getUserTopic = ({ path }, level = exports.SubscriptionLevels.USER) => getCommunityUserTopic(level === exports.SubscriptionLevels.USER ? path : path.replace(/^(\w*)/, '$1/social'), level);
1297
1269
  const getPostTopic = ({ path }, level = exports.SubscriptionLevels.POST) => {
@@ -1307,26 +1279,58 @@ const getCommentTopic = ({ path }) => {
1307
1279
  };
1308
1280
  const getMyFollowersTopic = () => {
1309
1281
  const user = getActiveUser();
1310
- const [networkId] = user.path.split('/user/');
1311
- return `${networkId}/membership/${user._id}/+/+`;
1282
+ return `${getNetworkId(user)}/membership/${user._id}/+/+`;
1312
1283
  };
1313
1284
  const getMyFollowingsTopic = () => {
1314
1285
  const user = getActiveUser();
1315
- const [networkId] = user.path.split('/user/');
1316
- return `${networkId}/membership/+/${user._id}/+`;
1286
+ return `${getNetworkId(user)}/membership/+/${user._id}/+`;
1317
1287
  };
1318
- /** @hidden */
1288
+ const getChannelTopic = (channel) => `${channel.path}/#`;
1289
+ const getSubChannelTopic = (subChannel) => `${subChannel.path}/#`;
1290
+ const getMessageTopic = (message) => message.path;
1291
+ /**
1292
+ * @hidden
1293
+ *
1294
+ * Create a topic to subscribe to network level events like 'user is deleted from the network'
1295
+ */
1319
1296
  const getNetworkTopic = () => {
1320
- const user = getActiveUser();
1321
- const [networkId] = user.path.split('/user/');
1322
- return networkId;
1297
+ return getNetworkId(getActiveUser());
1323
1298
  };
1324
- let mqttAccessToken;
1325
- let mqttUserId;
1326
- function subscribeTopic(topic, callback) {
1327
- const { mqtt, emitter, accessToken } = getActiveClient();
1299
+ /**
1300
+ * @hidden
1301
+ *
1302
+ * Create a topic to subscribe to channel events for 'conversation', 'community' channel
1303
+ */
1304
+ const getSmartFeedChannelTopic = () => {
1328
1305
  const user = getActiveUser();
1329
- if (mqttAccessToken !== accessToken || mqttUserId !== user._id) {
1306
+ return `${getNetworkId(user)}/smartfeed/${user._id}/channels`;
1307
+ };
1308
+ /**
1309
+ * @hidden
1310
+ *
1311
+ * Create a topic to subscribe to sub channel events for 'conversation', 'community' channel
1312
+ */
1313
+ const getSmartFeedSubChannelTopic = () => {
1314
+ const user = getActiveUser();
1315
+ return `${getNetworkId(user)}/smartfeed/${user._id}/messagefeeds`;
1316
+ };
1317
+ /**
1318
+ * @hidden
1319
+ *
1320
+ * Create a topic to subscribe to message events for 'conversation', 'community' channel
1321
+ */
1322
+ const getSmartFeedMessageTopic = () => {
1323
+ const user = getActiveUser();
1324
+ return `${getNetworkId(user)}/smartfeed/${user._id}/messages`;
1325
+ };
1326
+ let mqttAccessToken;
1327
+ let mqttUserId;
1328
+ function subscribeTopic(topic, callback) {
1329
+ var _a;
1330
+ const { mqtt, emitter, token } = getActiveClient();
1331
+ const accessToken = (_a = token === null || token === void 0 ? void 0 : token.accessToken) !== null && _a !== void 0 ? _a : '';
1332
+ const user = getActiveUser();
1333
+ if (mqttAccessToken !== accessToken || mqttUserId !== user._id) {
1330
1334
  mqttAccessToken = accessToken;
1331
1335
  mqttUserId = user._id;
1332
1336
  mqtt.connect({ accessToken: mqttAccessToken, userId: mqttUserId });
@@ -1422,12 +1426,32 @@ const createHttpTransport = (endpoint) => {
1422
1426
  httpsAgent: new HttpAgent.HttpsAgent(options),
1423
1427
  paramsSerializer: stringify,
1424
1428
  });
1429
+ instance.interceptors.request.use(config => {
1430
+ var _a;
1431
+ // check global.ts for the extension of AxiosRequestConfig
1432
+ const tokenExpiry = (_a = config.metadata) === null || _a === void 0 ? void 0 : _a.tokenExpiry;
1433
+ if (tokenExpiry) {
1434
+ if (Date.now() >= Date.parse(tokenExpiry)) {
1435
+ return Object.assign(Object.assign({}, config), { cancelToken: new axios__default["default"].CancelToken(cancel => cancel('Token Expired')) });
1436
+ }
1437
+ }
1438
+ return config;
1439
+ });
1425
1440
  instance.interceptors.response.use(response => response, error => {
1426
1441
  var _a;
1427
1442
  const { response } = error;
1428
1443
  // eslint-disable-next-line no-console
1429
1444
  console.error((_a = response === null || response === void 0 ? void 0 : response.data) !== null && _a !== void 0 ? _a : error);
1430
- if (response)
1445
+ // handle unauthorized request
1446
+ if (response.data.code === 400100 /* Amity.ServerError.UNAUTHORIZED */) {
1447
+ fireEvent('tokenTerminated', "terminated" /* Amity.SessionStates.TERMINATED */);
1448
+ }
1449
+ // handle request cancellation
1450
+ if (axios__default["default"].isCancel(error)) {
1451
+ fireEvent('tokenExpired', "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */);
1452
+ throw new ASCError('Token expired', 800403 /* Amity.ClientError.TOKEN_EXPIRED */, "fatal" /* Amity.ErrorLevel.FATAL */);
1453
+ }
1454
+ if (response === null || response === void 0 ? void 0 : response.data)
1431
1455
  unwrapPayload(response.data);
1432
1456
  });
1433
1457
  return instance;
@@ -20162,7 +20186,7 @@ var MqttError;
20162
20186
  MqttError[MqttError["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED";
20163
20187
  })(MqttError || (MqttError = {}));
20164
20188
  function getMqttOptions(params) {
20165
- return Object.assign({ clean: false, clientId: `mqttjs_ + ${Math.random().toString(16).substr(2, 8)}`, protocolId: 'MQTT', protocolVersion: 4, reconnectPeriod: 0, will: {
20189
+ return Object.assign({ clean: false, clientId: `mqttjs_ + ${Math.random().toString(16).substring(2, 10)}`, protocolId: 'MQTT', protocolVersion: 4, reconnectPeriod: 0, will: {
20166
20190
  topic: 'WillMsg',
20167
20191
  payload: 'Connection Closed abnormally..!',
20168
20192
  qos: 0,
@@ -20293,54 +20317,153 @@ const getFeedSettings = async () => {
20293
20317
  }));
20294
20318
  };
20295
20319
 
20296
- const DEFAULT_DEBUG_SESSION = 'amity';
20320
+ const COLLECTION_DEFAULT_PAGINATION_LIMIT = 5;
20321
+ const COLLECTION_DEFAULT_CACHING_POLICY = 'cache_then_server';
20322
+ const ENABLE_CACHE_MESSAGE = 'For using Live Collection feature you need to enable Cache!';
20323
+ const LIVE_OBJECT_ENABLE_CACHE_MESSAGE = 'For using Live Object feature you need to enable Cache!';
20324
+ const UNSYNCED_OBJECT_CACHED_AT_MESSAGE = 'Observing unsynced object is not supported by Live Object.';
20325
+ const UNSYNCED_OBJECT_CACHED_AT_VALUE = -5;
20326
+ const MINUTE = 60 * 1000;
20327
+ const ACCESS_TOKEN_WATCHER_INTERVAL = 10 * MINUTE;
20328
+
20329
+ // TODO: find a way to uniquely identify the device
20330
+ /** @hidden */
20331
+ const VERSION = '11.0.0';
20332
+ /** @hidden */
20333
+ const getDeviceId = () => {
20334
+ // here maybe put some auto detection of the device id based on if it's react or not?
20335
+ // anyhow we let consumer branch out if they want, but it doesn't mean we shouldn't try to be nice
20336
+ // and do things automatically
20337
+ // https://www.npmjs.com/package/react-native-device-info#getuniqueid
20338
+ // how to make sure that the react native package will not be included when build is for web
20339
+ return `ascWebSdk#${Math.random().toString(16)}`;
20340
+ };
20341
+ /** @hidden */
20342
+ const getDeviceModel = () => {
20343
+ var _a, _b;
20344
+ if ((_a = safeProcess.versions) === null || _a === void 0 ? void 0 : _a.node)
20345
+ return safeProcess.versions.node;
20346
+ if (navigator)
20347
+ return `${navigator.product.toLowerCase()}#${(_b = navigator.userAgent) !== null && _b !== void 0 ? _b : 'unknown_agent'}`;
20348
+ return 'unknown_model';
20349
+ };
20350
+ /** @hidden */
20351
+ const getDeviceInfo = () => {
20352
+ const model = getDeviceModel();
20353
+ return {
20354
+ version: VERSION,
20355
+ // TODO: replace with: kind: process.versions ? 'node' : 'web', when backend has fixed this
20356
+ kind: 'web',
20357
+ model,
20358
+ };
20359
+ };
20360
+
20361
+ /*
20362
+ * Session States cannot be set arbitarily.
20363
+ * These are the possible new states based on the current state
20364
+ * Check tech spec for details:
20365
+ * https://ekoapp.atlassian.net/wiki/spaces/UP/pages/2082537485/ASC+Core+-+Session+Management+3.0#Session-State
20366
+ */
20367
+ const sessisonStateTransitions = {
20368
+ // notLoggedIn -> establishing
20369
+ ["notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */]: ["establishing" /* Amity.SessionStates.ESTABLISHING */],
20370
+ // terminated -> establishing
20371
+ ["terminated" /* Amity.SessionStates.TERMINATED */]: ["establishing" /* Amity.SessionStates.ESTABLISHING */],
20372
+ // establishing -> notLoggedIn, established
20373
+ ["establishing" /* Amity.SessionStates.ESTABLISHING */]: [
20374
+ "notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */,
20375
+ "established" /* Amity.SessionStates.ESTABLISHED */,
20376
+ ],
20377
+ /*
20378
+ * established -> notLoggedIn, terminated, tokenExpired, establishing (for
20379
+ * cases when logging in same user)
20380
+ */
20381
+ ["established" /* Amity.SessionStates.ESTABLISHED */]: [
20382
+ "notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */,
20383
+ "terminated" /* Amity.SessionStates.TERMINATED */,
20384
+ "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */,
20385
+ "establishing" /* Amity.SessionStates.ESTABLISHING */,
20386
+ ],
20387
+ // tokenExpired -> establishing
20388
+ ["tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */]: ["establishing" /* Amity.SessionStates.ESTABLISHING */],
20389
+ };
20390
+ const isValidStateChange = (prevState, nextState) => {
20391
+ return sessisonStateTransitions[prevState].includes(nextState);
20392
+ };
20297
20393
  /**
20298
- * ```js
20299
- * import { createClient } from '@amityco/ts-sdk'
20300
- * const client = createClient(apiKey, 'https://asc.server/', 'myClient')
20301
- * ```
20394
+ * Checks if a {@link Amity.Client} instance is connected to ASC servers
20302
20395
  *
20303
- * Creates a new {@link Amity.Client} instance
20304
20396
  *
20305
- * @param apiKey for the {@link Amity.Client} instance
20306
- * @param apiRegion endpoint to connect to
20307
- * @param apiEndpoint custom endpoint in case you don't want to use a preset endpoint
20308
- * @param debugSession session's identifier for the client's logger instance
20309
- * @returns A {@link Amity.Client} instance
20397
+ * @param state the new session state
20398
+ * @returns a success boolean if connected
20399
+ *
20400
+ * @category private
20401
+ */
20402
+ const setSessionState = (state) => {
20403
+ const client = getActiveClient();
20404
+ client.log('client/api/setSessionState', state);
20405
+ const { sessionState: prevState } = client;
20406
+ if (prevState === state)
20407
+ return false;
20408
+ // check if transition is valid
20409
+ if (!isValidStateChange(prevState, state)) {
20410
+ throw new ASCError(`Session state cannot change from ${prevState} to ${state}`, 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
20411
+ }
20412
+ client.sessionState = state;
20413
+ fireEvent('sessionStateChange', state);
20414
+ return true;
20415
+ };
20416
+
20417
+ /**
20418
+ * Retrieves a pair of {@link Amity.Tokens} necessary for connection
20419
+ *
20420
+ * @param params.userId The userId to use to issue a token
20421
+ * @param params.displayName The user's displayName
20422
+ * @param params.deviceId The user's device Id (can be manually set for native users)
20423
+ * @param params.authToken The authentication token - necessary when network option is set to secure
20424
+ * @return The accessToken for the given userId
20310
20425
  *
20311
20426
  * @category Client API
20312
- * */
20313
- const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAULT_DEBUG_SESSION, apiEndpoint, } = {}) => {
20314
- var _a, _b;
20315
- const log = createLogger(debugSession);
20316
- log('client/api/createClient', {
20317
- apiKey: apiKey.replace(/.{5}$/g, 'xxxxx'),
20318
- apiRegion,
20427
+ * @hidden
20428
+ */
20429
+ const getToken = async (params) => {
20430
+ const client = getActiveClient();
20431
+ client.log('client/api/getToken', params);
20432
+ const deviceInfo = getDeviceInfo();
20433
+ const { data } = await client.http.post('/api/v3/sessions', Object.assign(Object.assign({}, params), { deviceInfo }), {
20434
+ // @ts-ignore
20435
+ headers: { 'X-API-Key': client.apiKey },
20319
20436
  });
20320
- const httpEndpoint = (_a = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.http) !== null && _a !== void 0 ? _a : computeUrl('http', apiRegion);
20321
- const mqttEndpoint = (_b = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.mqtt) !== null && _b !== void 0 ? _b : computeUrl('mqtt', apiRegion);
20322
- const http = createHttpTransport(httpEndpoint);
20323
- const ws = createWebsocketTransport(httpEndpoint);
20324
- const mqtt = createMqttTransport(mqttEndpoint);
20325
- const emitter = createEventEmitter();
20326
- const client = {
20327
- version: `${VERSION$1}`,
20328
- apiKey,
20329
- log,
20330
- http,
20331
- ws,
20332
- mqtt,
20333
- emitter,
20334
- use: () => setActiveClient(client),
20335
- getFeedSettings,
20336
- };
20337
- try {
20338
- getActiveClient();
20339
- }
20340
- catch (_c) {
20341
- setActiveClient(client);
20342
- }
20343
- return client;
20437
+ return data;
20438
+ };
20439
+
20440
+ /**
20441
+ * A util to set or refresh client token
20442
+ *
20443
+ * @param params.userId the user ID for the current session
20444
+ * @param params.displayName the user's displayName for the current session
20445
+ * @param params.deviceId Manual override of the user's device id (for device management)
20446
+ * @param params.authToken The authentication token - necessary when network option is set to secure
20447
+ * @returns token & user info
20448
+ *
20449
+ * @category private
20450
+ * @async
20451
+ */
20452
+ const setClientToken = async (params) => {
20453
+ const client = getActiveClient();
20454
+ // begin establishing session
20455
+ setSessionState("establishing" /* Amity.SessionStates.ESTABLISHING */);
20456
+ // @ts-ignore: in that particular case, typing can be
20457
+ // ignored since we enforce default values just before.
20458
+ const { accessToken, users, expiresAt, issuedAt, refreshToken } = await getToken(params);
20459
+ // manually setup the token for http transport
20460
+ client.http.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
20461
+ client.http.defaults.metadata = { tokenExpiry: expiresAt };
20462
+ // manually setup the token for ws transport
20463
+ client.ws.io.opts.query = { token: accessToken };
20464
+ client.token = { accessToken, issuedAt, expiresAt };
20465
+ setSessionState("established" /* Amity.SessionStates.ESTABLISHED */);
20466
+ return { accessToken, users, refreshToken };
20344
20467
  };
20345
20468
 
20346
20469
  /**
@@ -20351,7 +20474,6 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
20351
20474
  *
20352
20475
  * Disconnects an {@link Amity.Client} instance from ASC servers
20353
20476
  *
20354
- * @param client The {@link Amity.Client} instance to disconnect
20355
20477
  * @returns a success boolean if disconnected
20356
20478
  *
20357
20479
  * @category Client API
@@ -20370,42 +20492,30 @@ const disconnectClient = async () => {
20370
20492
  client.ws.removeAllListeners();
20371
20493
  client.mqtt.removeAllListeners();
20372
20494
  client.userId = undefined;
20373
- client.accessToken = undefined;
20495
+ client.token = undefined;
20496
+ client.http.defaults.headers.common.Authorization = '';
20497
+ client.ws.io.opts.query = { token: '' };
20498
+ /*
20499
+ * for cases when session state is terminated (example on ban) or token expired,
20500
+ * the terminating block will set session state to terminated or for the or
20501
+ * in the case of expired token the same happens
20502
+ *
20503
+ * establishing state also ignored in cases where accessTokenExpiryWatcher
20504
+ * calls renewal. There is a possibility that renewal will be called before
20505
+ * disconnectClient finishes execution
20506
+ */
20507
+ if (client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */)
20508
+ setSessionState("notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */);
20509
+ /*
20510
+ * Cache should be usable if tokenExpired
20511
+ * https://ekoapp.atlassian.net/wiki/spaces/UP/pages/2082537485/ASC+Core+-+Session+Management+3.0#SDK-usability-based-on-Session-State
20512
+ */
20513
+ if (client.sessionState !== "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */ && client.cache) {
20514
+ client.cache = { data: {} };
20515
+ }
20374
20516
  return !client.ws.connected;
20375
20517
  };
20376
20518
 
20377
- // TODO: find a way to uniquely identify the device
20378
- /** @hidden */
20379
- const VERSION = '11.0.0';
20380
- /** @hidden */
20381
- const getDeviceId = () => {
20382
- // here maybe put some auto detection of the device id based on if it's react or not?
20383
- // anyhow we let consumer branch out if they want, but it doesn't mean we shouldn't try to be nice
20384
- // and do things automatically
20385
- // https://www.npmjs.com/package/react-native-device-info#getuniqueid
20386
- // how to make sure that the react native package will not be included when build is for web
20387
- return `ascWebSdk#${Math.random().toString(16)}`;
20388
- };
20389
- /** @hidden */
20390
- const getDeviceModel = () => {
20391
- var _a, _b;
20392
- if ((_a = safeProcess.versions) === null || _a === void 0 ? void 0 : _a.node)
20393
- return safeProcess.versions.node;
20394
- if (navigator)
20395
- return `${navigator.product.toLowerCase()}#${(_b = navigator.userAgent) !== null && _b !== void 0 ? _b : 'unknown_agent'}`;
20396
- return 'unknown_model';
20397
- };
20398
- /** @hidden */
20399
- const getDeviceInfo = () => {
20400
- const model = getDeviceModel();
20401
- return {
20402
- version: VERSION,
20403
- // TODO: replace with: kind: process.versions ? 'node' : 'web', when backend has fixed this
20404
- kind: 'web',
20405
- model,
20406
- };
20407
- };
20408
-
20409
20519
  /**
20410
20520
  * Ingest a payload (v3) into the cache
20411
20521
  *
@@ -20457,26 +20567,17 @@ const createUserEventSubscriber = (event, callback) => {
20457
20567
  const onUserDeleted = (callback) => createUserEventSubscriber('user.deleted', callback);
20458
20568
 
20459
20569
  /**
20460
- * Retrieves a pair of {@link Amity.Tokens} necessary for connection
20570
+ * Terminates {@link Amity.Client} instance
20461
20571
  *
20462
- * @param userId The userId to use to issue a token
20463
- * @param displayName The user's displayName
20464
- * @param deviceId The user's device Id (can be manually set for native users)
20465
- * @param authToken The authentication token - necessary when network option is set to secure
20466
- * @return The accessToken for the given userId
20467
20572
  *
20468
- * @category Client API
20469
- * @hidden
20573
+ *
20574
+ * @category private
20470
20575
  */
20471
- const getToken = async (params) => {
20576
+ const terminateClient = () => {
20472
20577
  const client = getActiveClient();
20473
- client.log('client/api/getToken', params);
20474
- const deviceInfo = await getDeviceInfo();
20475
- const { data } = await client.http.post('/v1/device', Object.assign(Object.assign({}, params), { deviceInfo }), {
20476
- // @ts-ignore
20477
- headers: { 'X-API-Key': client.apiKey },
20478
- });
20479
- return data;
20578
+ setSessionState("terminated" /* Amity.SessionStates.TERMINATED */);
20579
+ client.sessionHandler = undefined;
20580
+ disconnectClient();
20480
20581
  };
20481
20582
 
20482
20583
  const EVENTS = [
@@ -20551,12 +20652,71 @@ const onClientDisconnected = (callback) => {
20551
20652
  * @category Client Events
20552
20653
  */
20553
20654
  const onClientBanned = (callback) => {
20554
- return onConnectionError(({ code }) => {
20555
- code === 400312 /* Amity.ServerError.GLOBAL_BAN */ && callback();
20556
- });
20655
+ const client = getActiveClient();
20656
+ return createEventSubscriber(client, `client/onConnectionError(user.didGlobalBan)`, 'user.didGlobalBan', callback);
20657
+ };
20658
+
20659
+ /**
20660
+ * ```js
20661
+ * import { onSessionStateChange } from '@amityco/ts-sdk'
20662
+ * const dispose = onSessionStateChange((state: Amity.SessionStates) => {
20663
+ * // ...
20664
+ * })
20665
+ * ```
20666
+ *
20667
+ * Fired when any {@link Amity.Client} has a session state change
20668
+ *
20669
+ * @param callback The function to call when the event was fired
20670
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
20671
+ *
20672
+ * @category Client Events
20673
+ */
20674
+ const onSessionStateChange = (callback) => {
20675
+ const client = getActiveClient();
20676
+ return createEventSubscriber(client, `client/onSessionStateChange`, 'sessionStateChange', callback);
20677
+ };
20678
+
20679
+ /**
20680
+ * ```js
20681
+ * import { onTokenExpired } from '@amityco/ts-sdk'
20682
+ * const dispose = onTokenExpired((state: Amity.SessionStates.TOKEN_EXPIRED) => {
20683
+ * // ...
20684
+ * })
20685
+ * ```
20686
+ *
20687
+ * Fired when any {@link Amity.Client} session state has expired
20688
+ *
20689
+ * @param callback The function to call when the event was fired
20690
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
20691
+ *
20692
+ * @category private
20693
+ */
20694
+ const onTokenExpired = (callback) => {
20695
+ const client = getActiveClient();
20696
+ return createEventSubscriber(client, `client/onTokenExpired`, 'tokenExpired', callback);
20697
+ };
20698
+
20699
+ /**
20700
+ *
20701
+ * Fired when any {@link Amity.Client} session state has terminated
20702
+ *
20703
+ * @param callback The function to call when the event was fired
20704
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
20705
+ *
20706
+ * @category private
20707
+ */
20708
+ const onTokenTerminated = (callback) => {
20709
+ const client = getActiveClient();
20710
+ return createEventSubscriber(client, `client/onTokenTerminated`, 'tokenTerminated', callback);
20557
20711
  };
20558
20712
 
20559
20713
  /* eslint-disable no-param-reassign */
20714
+ /*
20715
+ * declared earlier to accomodate case when logging in with a different user
20716
+ * than the one already connected, in which case the existing subscriptions need
20717
+ * to be cleared
20718
+ */
20719
+ const subscriptions = [];
20560
20720
  /**
20561
20721
  * ```js
20562
20722
  * import { connectClient } from '@amityco/ts-sdk/client/api'
@@ -20577,44 +20737,258 @@ const onClientBanned = (callback) => {
20577
20737
  * @category Client API
20578
20738
  * @async
20579
20739
  */
20580
- const connectClient = async (params, config) => {
20581
- var _a;
20740
+ const connectClient = async (params, sessionHandler, config) => {
20741
+ var _a, _b, _c;
20582
20742
  const client = getActiveClient();
20583
- client.log('client/api/connectClient', Object.assign({ apiKey: client.apiKey }, params));
20743
+ let unsubWatcher;
20744
+ client.log('client/api/connectClient', Object.assign({ apiKey: client.apiKey, sessionState: client.sessionState }, params));
20745
+ // if connecting to a different userId than the one that is connected currently
20746
+ if (client.userId && client.userId !== params.userId) {
20747
+ await disconnectClient();
20748
+ // Remove subscription to ban and delete
20749
+ subscriptions.forEach(fn => fn());
20750
+ }
20584
20751
  // default values
20585
20752
  (_a = params.deviceId) !== null && _a !== void 0 ? _a : (params.deviceId = getDeviceId());
20586
- // @ts-ignore: in that particular case, typing can be
20587
- // ignored since we enforce default values just before.
20588
- const { accessToken, users } = await getToken(params);
20589
- // manually setup the token for http transport
20590
- client.http.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
20591
- // manually setup the token for ws transport
20592
- client.ws.io.opts.query = { token: accessToken };
20593
- // FIXME: events are duplicated if connectClient is called few times without disconnectClient
20594
- // wire websocket events to our event emitter
20595
- proxyWebsocketEvents(client.ws, client.emitter);
20596
- // TODO: in phase 2, this should not be necessary. we should have WS
20597
- // to be connected "on demand" rather than "by default"
20598
- await new Promise(resolve => {
20599
- client.ws.once('connect', resolve);
20600
- client.ws.open();
20601
- });
20602
- client.userId = params.userId;
20603
- client.accessToken = accessToken;
20604
- setActiveUser(users[0]);
20605
- if ((config === null || config === void 0 ? void 0 : config.disableRTE) !== true) {
20753
+ try {
20754
+ // @ts-ignore: in that particular case, typing can be
20755
+ // ignored since we enforce default values just before.
20756
+ const { users } = await setClientToken(params);
20757
+ // FIXME: events are duplicated if connectClient is called few times without disconnectClient
20758
+ // wire websocket events to our event emitter
20759
+ proxyWebsocketEvents(client.ws, client.emitter);
20760
+ // TODO: in phase 2, this should not be necessary. we should have WS
20761
+ // to be connected "on demand" rather than "by default"
20762
+ await new Promise(resolve => {
20763
+ client.ws.once('connect', resolve);
20764
+ client.ws.open();
20765
+ });
20766
+ client.userId = params.userId;
20767
+ client.sessionHandler = sessionHandler;
20768
+ /*
20769
+ * Cannot push to subscriptions as watcher needs to continue working even if
20770
+ * token expires
20771
+ */
20772
+ unsubWatcher = client.accessTokenExpiryWatcher((_b = client.token) === null || _b === void 0 ? void 0 : _b.issuedAt, (_c = client.token) === null || _c === void 0 ? void 0 : _c.expiresAt, sessionHandler);
20773
+ setActiveUser(users[0]);
20774
+ }
20775
+ catch (error) {
20776
+ /*
20777
+ * if getting token failed session state reverts to initial state when app
20778
+ * is first launched
20779
+ */
20780
+ setSessionState("notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */);
20781
+ // pass error down tree so the calling function handle it
20782
+ throw error;
20783
+ }
20784
+ if ((config === null || config === void 0 ? void 0 : config.disableRTE) !== true) {
20606
20785
  subscribeTopic(getNetworkTopic());
20786
+ subscribeTopic(getSmartFeedChannelTopic());
20787
+ subscribeTopic(getSmartFeedSubChannelTopic());
20788
+ subscribeTopic(getSmartFeedMessageTopic());
20789
+ // subscribing to user topic is necessary to handle ban event
20790
+ subscribeTopic(getUserTopic(getActiveUser()));
20607
20791
  }
20608
- const subscriptions = [
20609
- onClientBanned(() => {
20610
- disconnectClient();
20792
+ subscriptions.push(
20793
+ // GLOBAL_BAN
20794
+ onClientBanned((_) => {
20795
+ terminateClient();
20796
+ subscriptions.forEach(fn => fn());
20797
+ unsubWatcher();
20798
+ }), onTokenTerminated(_ => {
20799
+ terminateClient();
20800
+ subscriptions.forEach(fn => fn());
20801
+ unsubWatcher();
20802
+ }), onUserDeleted((user) => {
20803
+ if (user.userId === client.userId) {
20804
+ terminateClient();
20611
20805
  subscriptions.forEach(fn => fn());
20612
- }),
20613
- onUserDeleted(() => null),
20614
- ];
20806
+ unsubWatcher();
20807
+ }
20808
+ }), onTokenExpired(state => {
20809
+ setSessionState(state);
20810
+ disconnectClient();
20811
+ subscriptions.forEach(fn => fn());
20812
+ }), onUserDeleted(() => null));
20615
20813
  return client.ws.connected;
20616
20814
  };
20617
20815
 
20816
+ /*
20817
+ * Renewal defintion accepted by SessionHandler interface
20818
+ *
20819
+ * Tech Spec:
20820
+ * https://ekoapp.atlassian.net/wiki/spaces/UP/pages/2082537485/ASC+Core+-+Session+Management+3.0#Session-Handler
20821
+ *
20822
+ * @category private
20823
+ */
20824
+ const renewal = () => {
20825
+ let tokenRenewed = false;
20826
+ let renewTimeoutId;
20827
+ const client = getActiveClient();
20828
+ client.log('initiating access token renewal');
20829
+ /*
20830
+ * Renews a token if it is hasn't been renewed before. Also marks token as
20831
+ * renewed once done
20832
+ * Per instance of Renewal, only one renewal is allowed
20833
+ */
20834
+ const renewToken = async (authToken) => {
20835
+ const { userId, displayName } = getActiveUser();
20836
+ const deviceId = getDeviceId();
20837
+ const params = { userId, displayName, authToken, deviceId };
20838
+ if (client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
20839
+ // sessionHandler will never be empty when renewal is instantiatied
20840
+ await connectClient(params, client.sessionHandler);
20841
+ }
20842
+ else {
20843
+ // about to expire
20844
+ // @ts-ignore: in that particular case, typing can be
20845
+ // ignored since we enforce default values just before.
20846
+ await setClientToken(params);
20847
+ }
20848
+ tokenRenewed = true;
20849
+ if (renewTimeoutId)
20850
+ clearTimeout(renewTimeoutId);
20851
+ };
20852
+ return {
20853
+ renew: () => {
20854
+ if (tokenRenewed) {
20855
+ console.log("'renew' method can be called only once per renewal instance");
20856
+ return;
20857
+ }
20858
+ renewToken();
20859
+ },
20860
+ renewWithAuthToken: (authToken) => {
20861
+ if (tokenRenewed) {
20862
+ console.log("'renewWithAuthToken' method can be called only once per renewal instance");
20863
+ return;
20864
+ }
20865
+ renewToken(authToken);
20866
+ },
20867
+ unableToRetrieveAuthToken: () => {
20868
+ renewTimeoutId = setTimeout(() => {
20869
+ var _a;
20870
+ (_a = client.sessionHandler) === null || _a === void 0 ? void 0 : _a.sessionWillRenewAccessToken(renewal());
20871
+ }, ACCESS_TOKEN_WATCHER_INTERVAL);
20872
+ },
20873
+ };
20874
+ };
20875
+
20876
+ const ABOUT_TO_EXPIRE_THRESHOLD = 80 / 100;
20877
+ const COMPENSATED_DELAY = 5 * MINUTE;
20878
+ /*
20879
+ * a helper function to check if the token has expires
20880
+ *
20881
+ * @param token to be checked
20882
+ * @returns boolean indicating if token expires
20883
+ *
20884
+ * @category private
20885
+ */
20886
+ const isExpired = (expiresAt) => Date.now() > Date.parse(expiresAt) - COMPENSATED_DELAY;
20887
+ /*
20888
+ * a helper function to check if the token is about to expire
20889
+ *
20890
+ * @param token to be checked
20891
+ * @returns boolean indicating if token is aboutToExpire
20892
+ *
20893
+ * @category private
20894
+ */
20895
+ const isAboutToExpire = (expiresAt, issuedAt) => {
20896
+ const expires = Date.parse(expiresAt);
20897
+ const issued = Date.parse(issuedAt);
20898
+ const now = Date.now();
20899
+ const duration = expires - issued - COMPENSATED_DELAY;
20900
+ const aboutToExpireAt = issued + duration * ABOUT_TO_EXPIRE_THRESHOLD;
20901
+ return now > aboutToExpireAt && now < expires;
20902
+ };
20903
+ /*
20904
+ * Monitors time to expire of token and updates session state to aboutToExpire
20905
+ *
20906
+ * @returns intervalId to be cleared after trigger
20907
+ *
20908
+ * @category private
20909
+ */
20910
+ const accessTokenExpiryWatcher = (expiresAt, issuedAt, sessionHandler) => {
20911
+ const interval = setInterval(() => {
20912
+ if (isExpired(expiresAt)) {
20913
+ /*
20914
+ * the event handler will take care of updating session state
20915
+ * Note, this will also clear the interval id, so this event will only be
20916
+ * fired once
20917
+ */
20918
+ fireEvent('tokenExpired', "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */);
20919
+ /*
20920
+ * https://ekoapp.atlassian.net/wiki/spaces/UP/pages/2082537485/ASC+Core+-+Session+Management+3.0#Automatically-initiate-renewal-flow
20921
+ *
20922
+ * Why sechduled task?
20923
+ * Since fireEvent is scheduled, it will be called
20924
+ * after sessionHandler leading to an invalid state change from
20925
+ * establishing to tokenExpired
20926
+ */
20927
+ scheduleTask(() => sessionHandler.sessionWillRenewAccessToken(renewal()));
20928
+ return;
20929
+ }
20930
+ if (isAboutToExpire(issuedAt, expiresAt)) {
20931
+ sessionHandler.sessionWillRenewAccessToken(renewal());
20932
+ }
20933
+ }, ACCESS_TOKEN_WATCHER_INTERVAL);
20934
+ return () => clearInterval(interval);
20935
+ };
20936
+
20937
+ const DEFAULT_DEBUG_SESSION = 'amity';
20938
+ /**
20939
+ * ```js
20940
+ * import { createClient } from '@amityco/ts-sdk'
20941
+ * const client = createClient(apiKey, 'https://asc.server/', 'myClient')
20942
+ * ```
20943
+ *
20944
+ * Creates a new {@link Amity.Client} instance
20945
+ *
20946
+ * @param apiKey for the {@link Amity.Client} instance
20947
+ * @param apiRegion endpoint to connect to
20948
+ * @param apiEndpoint custom endpoint in case you don't want to use a preset endpoint
20949
+ * @param param.debugSession session's identifier for the client's logger instance
20950
+ * @returns A {@link Amity.Client} instance
20951
+ *
20952
+ * @category Client API
20953
+ * */
20954
+ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAULT_DEBUG_SESSION, apiEndpoint, } = {}) => {
20955
+ var _a, _b;
20956
+ const log = createLogger(debugSession);
20957
+ log('client/api/createClient', {
20958
+ apiKey: apiKey.replace(/.{5}$/g, 'xxxxx'),
20959
+ apiRegion,
20960
+ });
20961
+ const httpEndpoint = (_a = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.http) !== null && _a !== void 0 ? _a : computeUrl('http', apiRegion);
20962
+ const mqttEndpoint = (_b = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.mqtt) !== null && _b !== void 0 ? _b : computeUrl('mqtt', apiRegion);
20963
+ const http = createHttpTransport(httpEndpoint);
20964
+ const ws = createWebsocketTransport(httpEndpoint);
20965
+ const mqtt = createMqttTransport(mqttEndpoint);
20966
+ const emitter = createEventEmitter();
20967
+ const sessionState = "notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */;
20968
+ const sessionHandler = undefined;
20969
+ const client = {
20970
+ version: `${VERSION$1}`,
20971
+ apiKey,
20972
+ log,
20973
+ http,
20974
+ ws,
20975
+ mqtt,
20976
+ emitter,
20977
+ accessTokenExpiryWatcher,
20978
+ use: () => setActiveClient(client),
20979
+ sessionState,
20980
+ sessionHandler,
20981
+ getFeedSettings,
20982
+ };
20983
+ try {
20984
+ return getActiveClient();
20985
+ }
20986
+ catch (_c) {
20987
+ setActiveClient(client);
20988
+ }
20989
+ return client;
20990
+ };
20991
+
20618
20992
  /**
20619
20993
  * ```js
20620
20994
  * import { isConnected } from '@amityco/ts-sdk'
@@ -20956,23 +21330,6 @@ const updateUser = async (userId, patch) => {
20956
21330
  };
20957
21331
  };
20958
21332
 
20959
- /**
20960
- * ```js
20961
- * import { onUserFetched } from '@amityco/ts-sdk'
20962
- * const dispose = onUserFetched(user => {
20963
- * // ...
20964
- * })
20965
- * ```
20966
- *
20967
- * Fired when a {@link Amity.User} has been fetched
20968
- *
20969
- * @param callback The function to call when the event was fired
20970
- * @returns an {@link Amity.Unsubscriber} function to stop listening
20971
- *
20972
- * @category User Events
20973
- */
20974
- const onUserFetched = (callback) => createUserEventSubscriber('user.fetched', callback);
20975
-
20976
21333
  /**
20977
21334
  * ```js
20978
21335
  * import { onUserUpdated } from '@amityco/ts-sdk'
@@ -21041,61 +21398,74 @@ const onUserUnflagged = (callback) => createUserEventSubscriber('user.unflagged'
21041
21398
  */
21042
21399
  const onUserFlagCleared = (callback) => createUserEventSubscriber('user.flagCleared', callback);
21043
21400
 
21044
- const COLLECTION_DEFAULT_PAGINATION_LIMIT = 5;
21045
- const COLLECTION_DEFAULT_CACHING_POLICY = 'cache_then_server';
21046
- const ENABLE_CACHE_MESSAGE = 'For using Live Collection feature you need to enable Cache!';
21047
- const LIVE_OBJECT_ENABLE_CACHE_MESSAGE = 'For using Live Object feature you need to enable Cache!';
21048
- const UNSYNCED_OBJECT_CACHED_AT_MESSAGE = 'Observing unsynced object is not supported by Live Object.';
21049
- const UNSYNCED_OBJECT_CACHED_AT_VALUE = -5;
21401
+ /**
21402
+ * ```js
21403
+ * import { onUserFetched } from '@amityco/ts-sdk'
21404
+ * const dispose = onUserFetched(user => {
21405
+ * // ...
21406
+ * })
21407
+ * ```
21408
+ *
21409
+ * Fired when a {@link Amity.User} has been fetched
21410
+ *
21411
+ * @param callback The function to call when the event was fired
21412
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
21413
+ *
21414
+ * @category User Events
21415
+ */
21416
+ const onUserFetched = (callback) => createUserEventSubscriber('user.fetched', callback);
21050
21417
 
21051
21418
  /**
21052
21419
  * ```js
21053
- * import { liveUser } from '@amityco/ts-sdk'
21420
+ * import { liveUser } from '@amityco/ts-sdk';
21054
21421
  *
21055
- * let users = []
21056
- * const unsub = liveUser(userId, response => merge(users, response.data))
21422
+ * let user;
21423
+ *
21424
+ * const unsubscribe = liveUser(userId, response => {
21425
+ * user = response.data;
21426
+ * });
21057
21427
  * ```
21058
21428
  *
21059
21429
  * Observe all mutation on a given {@link Amity.User}
21060
21430
  *
21061
21431
  * @param userId the ID of the user to observe
21062
21432
  * @param callback the function to call when new data are available
21063
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the users
21433
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the user
21064
21434
  *
21065
21435
  * @category Message Live Object
21066
21436
  */
21067
21437
  const liveUser = (userId, callback) => {
21068
21438
  const { log, cache } = getActiveClient();
21069
- let user;
21439
+ const timestamp = Date.now();
21440
+ log(`liveUser(tmpid: ${timestamp}) > listen`);
21070
21441
  if (!cache) {
21071
21442
  console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
21072
21443
  }
21073
- const timestamp = Date.now();
21074
- log(`liveUser(tmpid: ${timestamp}) > listen`);
21444
+ let user;
21075
21445
  const disposers = [];
21076
21446
  const dispatcher = (data) => {
21077
- var _a;
21078
- // we check updatedAt to see if the current snapshot is new so
21079
- // we won't send old data back, only fresh new data
21080
- 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')
21081
- return;
21082
- callback(data);
21083
21447
  user = data.data;
21448
+ callback(data);
21084
21449
  };
21085
- const realtimeRouter = (user, action) => {
21086
- dispatcher({ loading: false, data: user, origin: 'event' });
21450
+ const realtimeRouter = (eventUser) => {
21451
+ if (userId !== eventUser.userId) {
21452
+ return;
21453
+ }
21454
+ if (user && !hasUpdates(user, eventUser)) {
21455
+ return;
21456
+ }
21457
+ dispatcher({ loading: false, data: eventUser, origin: 'event' });
21087
21458
  };
21088
21459
  const onFetch = () => {
21089
21460
  const query = createQuery(getUser, userId, true);
21090
21461
  runQuery(query, ({ loading, data, error, origin }) => {
21091
21462
  dispatcher({ loading, data, origin, error });
21092
21463
  if (error) {
21093
- // Terminate observe functionality on error
21094
21464
  disposers.forEach(fn => fn());
21095
21465
  }
21096
21466
  });
21097
21467
  };
21098
- 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)));
21468
+ disposers.push(onUserFetched(realtimeRouter), onUserUpdated(realtimeRouter), onUserDeleted(realtimeRouter), onUserFlagged(realtimeRouter), onUserUnflagged(realtimeRouter), onUserFlagCleared(realtimeRouter));
21099
21469
  onFetch();
21100
21470
  return () => {
21101
21471
  log(`liveUser(tmpid: ${timestamp}) > dispose`);
@@ -21509,7 +21879,7 @@ getRole.locally = (roleId) => {
21509
21879
  const dispatchReactable = (referenceType, model) => {
21510
21880
  if (referenceType === 'message')
21511
21881
  // @ts-ignore: refactor later
21512
- fireEvent('v3.message.didUpdate', { messages: [model] });
21882
+ fireEvent('local.message.updated', { messages: [model] });
21513
21883
  else if (referenceType === 'post')
21514
21884
  // @ts-ignore: refactor later
21515
21885
  fireEvent('post.updated', { posts: [model] });
@@ -21518,6 +21888,100 @@ const dispatchReactable = (referenceType, model) => {
21518
21888
  fireEvent('comment.updated', { comments: [model] });
21519
21889
  };
21520
21890
 
21891
+ /** @hidden */
21892
+ /*
21893
+ * @param message payload from http request without myReactions
21894
+ * add myReactions to http response if the event was a reaction event
21895
+ */
21896
+ const prepareMessagePayloadForCache = (payload) => {
21897
+ const client = getActiveClient();
21898
+ const cached = pullFromCache(['message', 'get', payload.messageId]);
21899
+ // '[]' in cases where the new reaction is the first one
21900
+ const myReactions = (cached === null || cached === void 0 ? void 0 : cached.data.myReactions) || [];
21901
+ // add myReactions to the payload
21902
+ Object.assign(payload, { myReactions });
21903
+ // check if there are any updates to the reactions
21904
+ const latestReaction = payload === null || payload === void 0 ? void 0 : payload.latestReaction;
21905
+ const isLatestReactionMine = latestReaction && latestReaction.userId === client.userId;
21906
+ if (!isLatestReactionMine) {
21907
+ return;
21908
+ }
21909
+ // new reaction added
21910
+ if (latestReaction.eventName === 'add' && !myReactions.includes(latestReaction.reactionName)) {
21911
+ Object.assign(payload, {
21912
+ myReactions: [...myReactions, latestReaction.reactionName],
21913
+ });
21914
+ }
21915
+ // existing reaction removed
21916
+ if (latestReaction.eventName === 'remove' && myReactions.includes(latestReaction.reactionName)) {
21917
+ Object.assign(payload, {
21918
+ myReactions: myReactions.filter(x => x !== latestReaction.reactionName),
21919
+ });
21920
+ }
21921
+ };
21922
+
21923
+ function convertFromRaw$2(_a) {
21924
+ 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"]);
21925
+ let cache;
21926
+ if (referenceId) {
21927
+ try {
21928
+ cache = pullFromCache(['message', 'get', referenceId]);
21929
+ // eslint-disable-next-line no-empty
21930
+ }
21931
+ catch (_b) { }
21932
+ }
21933
+ if (!cache) {
21934
+ try {
21935
+ cache = pullFromCache(['message', 'get', rest.messageId]);
21936
+ // eslint-disable-next-line no-empty
21937
+ }
21938
+ catch (_c) { }
21939
+ }
21940
+ 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 });
21941
+ if (mentionedUsers) {
21942
+ out.mentionees = mentionedUsers.map(mention => {
21943
+ if (mention.type === 'channel') {
21944
+ return mention;
21945
+ }
21946
+ return { type: 'user', userIds: mention.userPublicIds };
21947
+ });
21948
+ }
21949
+ if (myReactions) {
21950
+ // http response
21951
+ out.myReactions = myReactions;
21952
+ }
21953
+ else {
21954
+ // mqtt event
21955
+ try {
21956
+ prepareMessagePayloadForCache(out);
21957
+ // eslint-disable-next-line no-empty
21958
+ }
21959
+ catch (_d) { }
21960
+ }
21961
+ return out;
21962
+ }
21963
+ const prepareMessagePayload = (payload) => {
21964
+ return Object.assign(Object.assign({}, payload), { messages: payload.messages.map(convertFromRaw$2) });
21965
+ };
21966
+ const convertResponseFromRaw = (response) => {
21967
+ return Object.assign(Object.assign({}, response), { data: Object.assign(Object.assign({}, response.data), { messages: response.data.messages.map(convertFromRaw$2) }) });
21968
+ };
21969
+ function convertParams(_a) {
21970
+ var { subChannelId, mentionees } = _a, rest = __rest(_a, ["subChannelId", "mentionees"]);
21971
+ return Object.assign({ messageFeedId: subChannelId, mentionedUsers: mentionees }, rest);
21972
+ }
21973
+ function convertQueryParams$1(_a) {
21974
+ var { page, sortBy, subChannelId, tags } = _a, rest = __rest(_a, ["page", "sortBy", "subChannelId", "tags"]);
21975
+ const out = Object.assign(Object.assign({}, rest), { messageFeedId: subChannelId, options: { token: toToken(page || { limit: 10 }, 'afterbeforeraw') } });
21976
+ if (sortBy !== undefined) {
21977
+ out.options.sortBy = sortBy;
21978
+ }
21979
+ if (tags) {
21980
+ out.includeTags = tags;
21981
+ }
21982
+ return out;
21983
+ }
21984
+
21521
21985
  /**
21522
21986
  * ```js
21523
21987
  * import { getMessage } from '@amityco/ts-sdk'
@@ -21542,7 +22006,9 @@ const getMessage = async (messageId, isLive = false) => {
21542
22006
  let data;
21543
22007
  try {
21544
22008
  // API-FIX: endpoint should not be /list, parameters should be querystring.
21545
- const response = await client.http.get(`/api/v3/messages/${encodeURIComponent(messageId)}`);
22009
+ const response = await client.http
22010
+ .get(`/api/v5/messages/${encodeURIComponent(messageId)}`)
22011
+ .then(convertResponseFromRaw);
21546
22012
  data = response.data;
21547
22013
  }
21548
22014
  catch (error) {
@@ -21555,7 +22021,7 @@ const getMessage = async (messageId, isLive = false) => {
21555
22021
  if (client.cache)
21556
22022
  ingestInCache(data, { cachedAt });
21557
22023
  const { messages } = data;
21558
- fireEvent('v3.message.didFetch', { messages });
22024
+ fireEvent('local.message.fetched', { messages });
21559
22025
  return {
21560
22026
  data: messages.find(message => message.messageId === messageId),
21561
22027
  cachedAt,
@@ -21605,15 +22071,16 @@ getMessage.locally = (messageId) => {
21605
22071
  const getMessages = async (messageIds) => {
21606
22072
  const client = getActiveClient();
21607
22073
  client.log('message/getMessages', messageIds);
21608
- // API-FIX: endpoint should not be /list, parameters should be querystring.
21609
- const { data } = await client.http.get(`/api/v3/messages/list`, {
21610
- params: { messageIds },
21611
- });
22074
+ const { data } = await client.http
22075
+ .get(`/api/v5/messages/list`, {
22076
+ params: { messageIds: messageIds.map(encodeURIComponent) },
22077
+ })
22078
+ .then(convertResponseFromRaw);
21612
22079
  const cachedAt = client.cache && Date.now();
21613
22080
  if (client.cache)
21614
22081
  ingestInCache(data, { cachedAt });
21615
22082
  const { messages } = data;
21616
- fireEvent('v3.message.didFetch', { messages });
22083
+ fireEvent('local.message.fetched', { messages });
21617
22084
  return {
21618
22085
  data: messages,
21619
22086
  cachedAt,
@@ -21668,31 +22135,25 @@ getMessages.locally = (messageIds) => {
21668
22135
  const queryMessages = async (query) => {
21669
22136
  const client = getActiveClient();
21670
22137
  client.log('message/queryMessages', query);
21671
- const { page = { limit: 10 } } = query, params = __rest(query, ["page"]);
22138
+ const params = convertQueryParams$1(query);
21672
22139
  // API-FIX: parameters should be querystring. (1)
21673
22140
  // API-FIX: backend should answer Amity.Response (2)
21674
22141
  // API-FIX: pagination should not be indexed on channelSegment (3)
21675
22142
  // const { data } = await client.http.get<Amity.Response<Amity.Paged<Amity.MessagePayload>>>(
21676
- const { data } = await client.http.get(`/api/v3/messages`, {
21677
- params: Object.assign(Object.assign({}, params), { options: {
21678
- token: toToken(page, 'afterbefore'),
21679
- } }),
21680
- });
22143
+ const response = await client.http
22144
+ .get(`/api/v5/messages`, { params })
22145
+ .then(convertResponseFromRaw);
21681
22146
  // API-FIX: backend should answer Amity.Response (2)
21682
22147
  // const { paging, messages } = unwrapPayload(data)
21683
- const { paging } = data, payload = __rest(data, ["paging"]);
21684
- const { messages } = payload;
22148
+ const _a = response.data, { paging } = _a, data = __rest(_a, ["paging"]);
22149
+ const { messages } = data;
21685
22150
  const cachedAt = client.cache && Date.now();
21686
22151
  if (client.cache) {
21687
- ingestInCache(payload, { cachedAt });
21688
- const cacheKey = [
21689
- 'message',
21690
- 'query',
21691
- Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
21692
- ];
22152
+ ingestInCache(data, { cachedAt });
22153
+ const cacheKey = ['message', 'query', params];
21693
22154
  pushToCache(cacheKey, { messages: messages.map(getResolver('message')), paging });
21694
22155
  }
21695
- fireEvent('v3.message.didFetch', { messages });
22156
+ fireEvent('local.message.fetched', { messages });
21696
22157
  const nextPage = toPage(paging.next);
21697
22158
  const prevPage = toPage(paging.previous);
21698
22159
  return { data: messages, cachedAt, prevPage, nextPage };
@@ -21716,8 +22177,8 @@ queryMessages.locally = (query) => {
21716
22177
  client.log('message/queryMessages.locally', query);
21717
22178
  if (!client.cache)
21718
22179
  return;
21719
- const { page = { limit: 10 } } = query, params = __rest(query, ["page"]);
21720
- const queryKey = ['message', 'query', Object.assign(Object.assign({}, params), { options: Object.assign({}, page) })];
22180
+ const params = convertQueryParams$1(query);
22181
+ const queryKey = ['message', 'query', params];
21721
22182
  const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
21722
22183
  if (!(data === null || data === void 0 ? void 0 : data.messages.length))
21723
22184
  return;
@@ -21734,13 +22195,20 @@ queryMessages.locally = (query) => {
21734
22195
 
21735
22196
  const uuid = () => nativeIdGenerator__default["default"].v4().toString();
21736
22197
 
22198
+ // FIXME: temp solution
22199
+ let uniqueId;
21737
22200
  /**
21738
22201
  * ```js
21739
- * import { createMessage } from '@amityco/ts-sdk'
21740
- * const created = await createMessage({
21741
- * channelId: 'foobar',
21742
- * data: { text: 'hello world' }
21743
- * })
22202
+ * import { createMessage, createQuery, runQuery } from '@amityco/ts-sdk'
22203
+ *
22204
+ * const query = createQuery(createMessage, {
22205
+ * subChannelId: 'foobar',
22206
+ * data: { text: 'hello world' },
22207
+ * });
22208
+ *
22209
+ * runQuery(query, ({ data: message, loading }) => {
22210
+ * console.log(message);
22211
+ * });
21744
22212
  * ```
21745
22213
  *
21746
22214
  * Creates an {@link Amity.Message}
@@ -21753,13 +22221,19 @@ const uuid = () => nativeIdGenerator__default["default"].v4().toString();
21753
22221
  */
21754
22222
  const createMessage = async (bundle) => {
21755
22223
  const client = getActiveClient();
21756
- client.log('user/createMessage', bundle);
21757
- const { data } = await client.http.post('/api/v3/messages', bundle);
22224
+ client.log('message/createMessage', bundle);
22225
+ const referenceId = uniqueId;
22226
+ uniqueId = undefined;
22227
+ const { data } = await client.http
22228
+ .post('/api/v5/messages', Object.assign(Object.assign({}, convertParams(bundle)), { referenceId }))
22229
+ .then(convertResponseFromRaw);
21758
22230
  const cachedAt = client.cache && Date.now();
21759
- if (client.cache)
22231
+ if (client.cache) {
22232
+ dropFromCache(['message', 'get', referenceId]);
21760
22233
  ingestInCache(data, { cachedAt });
22234
+ }
21761
22235
  const { messages } = data;
21762
- fireEvent('v3.message.didCreate', { messages });
22236
+ fireEvent('local.message.created', { messages });
21763
22237
  return {
21764
22238
  data: messages[0],
21765
22239
  cachedAt,
@@ -21768,7 +22242,8 @@ const createMessage = async (bundle) => {
21768
22242
  /**
21769
22243
  * ```js
21770
22244
  * import { createMessage } from '@amityco/ts-sdk'
21771
- * const created = createMessage.locally({
22245
+ *
22246
+ * const created = createMessage.optimistically({
21772
22247
  * channelId: 'foobar',
21773
22248
  * data: { text: 'hello world' }
21774
22249
  * })
@@ -21793,17 +22268,26 @@ createMessage.optimistically = (bundle) => {
21793
22268
  * Updated to handle client requirement to add messageId while uploading
21794
22269
  * message with image. Temporary!
21795
22270
  */
21796
- const bundleWithMessageId = Object.assign({ messageId: uuid() }, bundle);
21797
- // only log if cache is enabled
21798
- client.log('user/createMessage.locally', bundleWithMessageId);
21799
- const channel = pullFromCache(['channel', 'get', bundleWithMessageId.channelId]);
21800
- 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 }));
22271
+ const localId = `LOCAL_${uuid()}`;
22272
+ uniqueId = localId;
22273
+ const bundleWithMessageId = Object.assign({ messageId: localId, uniqueId: localId }, bundle);
22274
+ client.log('message/createMessage.optimistically', bundleWithMessageId);
22275
+ const subChannel = pullFromCache(['subChannel', 'get', bundle.subChannelId]);
22276
+ if (subChannel) {
22277
+ upsertInCache(['subChannel', 'get', bundle.subChannelId], Object.assign(Object.assign({}, subChannel.data), { messageCount: subChannel.data.messageCount + 1 }));
22278
+ if (subChannel.data.channelId === subChannel.data.subChannelId) {
22279
+ const channel = pullFromCache(['channel', 'get', subChannel.data.channelId]);
22280
+ if (channel === null || channel === void 0 ? void 0 : channel.data) {
22281
+ upsertInCache(['channel', 'get', subChannel.data.channelId], Object.assign(Object.assign({}, channel.data), { messageCount: ((_a = channel.data.messageCount) !== null && _a !== void 0 ? _a : 0) + 1 }));
22282
+ }
22283
+ }
22284
+ }
21801
22285
  // as reused to update created and updated time, which should be the same
21802
22286
  const createdTime = new Date().toISOString();
21803
- 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);
22287
+ 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);
21804
22288
  const cachedAt = UNSYNCED_OBJECT_CACHED_AT_VALUE;
21805
22289
  pushToCache(['message', 'get', message.messageId], message, { cachedAt });
21806
- fireEvent('v3.message.didCreate', { messages: [message] });
22290
+ fireEvent('local.message.created', { messages: [message] });
21807
22291
  return {
21808
22292
  cachedAt,
21809
22293
  data: message,
@@ -21829,13 +22313,15 @@ createMessage.optimistically = (bundle) => {
21829
22313
  */
21830
22314
  const updateMessage = async (messageId, patch) => {
21831
22315
  const client = getActiveClient();
21832
- client.log('user/updateMessage', patch);
21833
- const { data } = await client.http.put(`/api/v3/messages/${encodeURIComponent(messageId)}`, patch);
22316
+ client.log('message/updateMessage', patch);
22317
+ const { data } = await client.http
22318
+ .put(`/api/v5/messages/${encodeURIComponent(messageId)}`, convertParams(patch))
22319
+ .then(convertResponseFromRaw);
21834
22320
  const cachedAt = client.cache && Date.now();
21835
22321
  if (client.cache)
21836
22322
  ingestInCache(data, { cachedAt });
21837
22323
  const { messages } = data;
21838
- fireEvent('v3.message.didUpdate', { messages });
22324
+ fireEvent('local.message.updated', { messages });
21839
22325
  return {
21840
22326
  data: messages.find(message => message.messageId === messageId),
21841
22327
  cachedAt,
@@ -21844,7 +22330,7 @@ const updateMessage = async (messageId, patch) => {
21844
22330
  /**
21845
22331
  * ```js
21846
22332
  * import { updateMessage } from '@amityco/ts-sdk'
21847
- * const updated = updateMessage.locally('foobar', {
22333
+ * const updated = updateMessage.optimistically('foobar', {
21848
22334
  * data: { text: 'hello world' }
21849
22335
  * })
21850
22336
  * ```
@@ -21859,7 +22345,7 @@ const updateMessage = async (messageId, patch) => {
21859
22345
  */
21860
22346
  updateMessage.optimistically = (messageId, patch) => {
21861
22347
  const client = getActiveClient();
21862
- client.log('user/updateMessage', patch);
22348
+ client.log('message/updateMessage.optimistically', patch);
21863
22349
  if (!client.cache)
21864
22350
  return;
21865
22351
  const message = pullFromCache(['message', 'get', messageId]);
@@ -21868,7 +22354,7 @@ updateMessage.optimistically = (messageId, patch) => {
21868
22354
  const cachedAt = -1;
21869
22355
  const updated = Object.assign(Object.assign(Object.assign({}, message.data), patch), { updatedAt: new Date().toISOString() });
21870
22356
  upsertInCache(['message', 'get', messageId], updated, { cachedAt });
21871
- fireEvent('v3.message.didUpdate', { messages: [updated] });
22357
+ fireEvent('local.message.updated', { messages: [updated] });
21872
22358
  return {
21873
22359
  data: updated,
21874
22360
  cachedAt,
@@ -21883,7 +22369,7 @@ updateMessage.optimistically = (messageId, patch) => {
21883
22369
  *
21884
22370
  * Delete a {@link Amity.Message}
21885
22371
  *
21886
- * @param The ID of the {@link Amity.Message} to delete
22372
+ * @param messageId the ID of the {@link Amity.Message} to delete
21887
22373
  * @return A success boolean if the {@link Amity.Message} was deleted
21888
22374
  *
21889
22375
  * @category Message API
@@ -21893,15 +22379,15 @@ const deleteMessage = async (messageId) => {
21893
22379
  const client = getActiveClient();
21894
22380
  client.log('message/deleteMessage', messageId);
21895
22381
  // API-FIX: This endpoint has not been implemented yet.
21896
- await client.http.delete(`/api/v3/messages/${encodeURIComponent(messageId)}`);
22382
+ await client.http.delete(`/api/v5/messages/${encodeURIComponent(messageId)}`);
21897
22383
  const deleted = await getMessage(messageId);
21898
- fireEvent('v3.message.didDelete', { messages: [deleted.data] });
22384
+ fireEvent('local.message.deleted', { messages: [deleted.data] });
21899
22385
  return deleted.data;
21900
22386
  };
21901
22387
  /**
21902
22388
  * ```js
21903
22389
  * import { deleteMessage } from '@amityco/ts-sdk'
21904
- * const success = deleteMessage.locally('foobar')
22390
+ * const success = deleteMessage.optimistically('foobar')
21905
22391
  * ```
21906
22392
  *
21907
22393
  * Deletes a {@link Amity.Message}
@@ -21913,14 +22399,14 @@ const deleteMessage = async (messageId) => {
21913
22399
  */
21914
22400
  deleteMessage.optimistically = (messageId) => {
21915
22401
  const client = getActiveClient();
21916
- client.log('message/deleteMessage', messageId);
22402
+ client.log('message/deleteMessage.optimistically', messageId);
21917
22403
  const message = pullFromCache(['message', 'get', messageId]);
21918
22404
  if (!message)
21919
22405
  return;
21920
22406
  const cachedAt = -1;
21921
22407
  const deleted = Object.assign(Object.assign({}, message.data), { isDeleted: true, updatedAt: new Date().toISOString() });
21922
22408
  upsertInCache(['message', 'get', messageId], deleted, { cachedAt });
21923
- fireEvent('v3.message.didDelete', { messages: [deleted] });
22409
+ fireEvent('local.message.deleted', { messages: [deleted] });
21924
22410
  return {
21925
22411
  data: deleted,
21926
22412
  cachedAt,
@@ -21945,11 +22431,20 @@ const queryPosts = async (query) => {
21945
22431
  const client = getActiveClient();
21946
22432
  client.log('post/queryPosts', query);
21947
22433
  const { page = { limit: 10 } } = query, params = __rest(query, ["page"]);
22434
+ const { dataTypes, matchingOnlyParentPost } = params;
21948
22435
  // API-FIX: parameters should be querystring. (1)
21949
22436
  // API-FIX: backend should answer Amity.Response (2)
21950
22437
  // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.PostPayload>>>(
21951
22438
  const { data } = await client.http.get(`/api/v4/posts`, {
21952
- params: Object.assign(Object.assign({}, params), { options: {
22439
+ params: Object.assign(Object.assign({}, params), {
22440
+ /*
22441
+ * when creating post like image, file, video BE will create 2 posts
22442
+ * 1. parent post to store text with dataType=text
22443
+ * 2. child post to store dataTypes post data
22444
+ *
22445
+ * By default BE queries only parent post
22446
+ */
22447
+ matchingOnlyParentPost: matchingOnlyParentPost !== null && matchingOnlyParentPost !== void 0 ? matchingOnlyParentPost : !(dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length), options: {
21953
22448
  token: toToken(page, 'afterbeforeraw'),
21954
22449
  } }),
21955
22450
  });
@@ -22247,12 +22742,13 @@ const queryCommunities = async (query) => {
22247
22742
  const client = getActiveClient();
22248
22743
  client.log('channel/queryCommunities', query);
22249
22744
  // safe decapsulation
22250
- const _a = query !== null && query !== void 0 ? query : {}, { page, displayName, membership } = _a, params = __rest(_a, ["page", "displayName", "membership"]);
22745
+ const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
22746
+ const _b = params !== null && params !== void 0 ? params : {}, { displayName, membership } = _b, restParams = __rest(_b, ["displayName", "membership"]);
22251
22747
  // API-FIX: parameters should be querystring.
22252
22748
  // API-FIX: backend doesnt answer Amity.Response
22253
22749
  // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<CommunityPayload>>>(
22254
22750
  const { data } = await client.http.get(`/api/v3/communities`, {
22255
- params: Object.assign(Object.assign({}, params), { keyword: displayName, filter: membership, options: {
22751
+ params: Object.assign(Object.assign({}, restParams), { keyword: displayName, filter: membership, options: {
22256
22752
  token: toToken(page, 'skiplimit'),
22257
22753
  } }),
22258
22754
  });
@@ -22548,10 +23044,62 @@ const leaveCommunity = async (communityId) => {
22548
23044
  };
22549
23045
 
22550
23046
  /**
22551
- * ```js
22552
- * import { queryCommunityMembers } from '@amityco/ts-sdk'
22553
- * const communityMembers = await queryCommunityMembers({ communityId: 'foo' })
22554
- * ```
23047
+ * Attach user object to membership model
23048
+ * - If cache is not enabled, set user to undefined ({..., user: undefined})
23049
+ * - If user object is not found in cache, set user to undefined
23050
+ * ({..., user: undefined})
23051
+ * - If a user is found in the cache, it attaches the user from the cache
23052
+ * ({..., user: { userId, displayName,... }})
23053
+ *
23054
+ * @param member The membership model object
23055
+ * @param userIdProp The user ID prop name of membership object
23056
+ * @param userProp The user prop name of destination object
23057
+ * @returns The membership model object that is already mapped to user
23058
+ * @hidden
23059
+ */
23060
+ const withUser = (member, userIdProp = 'userId', userProp = 'user') => (Object.assign({ get [userProp]() {
23061
+ var _a;
23062
+ const client = getActiveClient();
23063
+ if (!client.cache)
23064
+ return undefined;
23065
+ const userCache = (_a = pullFromCache(['user', 'get', member[userIdProp]])) === null || _a === void 0 ? void 0 : _a.data;
23066
+ if (!userCache) {
23067
+ return undefined;
23068
+ }
23069
+ return userCache;
23070
+ } }, member));
23071
+ /**
23072
+ * Mapping membership model with user object
23073
+ *
23074
+ * @param members The membership model objects
23075
+ * @param userIdProp The user ID prop name of membership object
23076
+ * @param userProp The user prop name of destination object
23077
+ * @returns The membership model objects that is already
23078
+ * mapped to users
23079
+ * @hidden
23080
+ */
23081
+ const withUsers = (members, userIdProp = 'userId', userProp = 'user') => members.map(member => withUser(member, userIdProp, userProp));
23082
+ /**
23083
+ * Transform members prop in any payload with attached users members
23084
+ *
23085
+ * @param payload The payload contain members prop
23086
+ * @param memberProp A name of members prop
23087
+ * @param userIdProp The user ID prop name of membership object
23088
+ * @param userProp The user prop name of destination object
23089
+ * @returns The transforming payload
23090
+ * @hidden
23091
+ */
23092
+ const prepareMembershipPayload = (payload, memberProp, userIdProp = 'userId', userProp = 'user') => {
23093
+ const _a = payload, _b = memberProp, memberPayload = _a[_b], rest = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
23094
+ const members = withUsers(memberPayload, userIdProp, userProp);
23095
+ return Object.assign(Object.assign({}, rest), { [memberProp]: members });
23096
+ };
23097
+
23098
+ /**
23099
+ * ```js
23100
+ * import { queryCommunityMembers } from '@amityco/ts-sdk'
23101
+ * const communityMembers = await queryCommunityMembers({ communityId: 'foo' })
23102
+ * ```
22555
23103
  *
22556
23104
  * Queries a paginable list of {@link Amity.CommunityUser} objects
22557
23105
  *
@@ -22564,17 +23112,27 @@ const leaveCommunity = async (communityId) => {
22564
23112
  const queryCommunityMembers = async (query) => {
22565
23113
  const client = getActiveClient();
22566
23114
  client.log('community/queryCommunityMembers', query);
22567
- const _a = query !== null && query !== void 0 ? query : {}, { page, communityId } = _a, params = __rest(_a, ["page", "communityId"]);
22568
- const { data } = await client.http.get(`/api/v3/communities/${communityId}/users`, {
23115
+ const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
23116
+ const { data: queryPayload } = await client.http.get(`/api/v3/communities/${params.communityId}/users`, {
22569
23117
  params: Object.assign(Object.assign({}, params), { options: {
22570
23118
  token: toToken(page, 'skiplimit'),
22571
23119
  } }),
22572
23120
  });
22573
- const { paging } = data, payload = __rest(data, ["paging"]);
22574
- const { communityUsers } = payload;
23121
+ const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
23122
+ const preparedPayload = prepareMembershipPayload(payload, 'communityUsers');
23123
+ const { communityUsers } = preparedPayload;
22575
23124
  const cachedAt = client.cache && Date.now();
22576
23125
  if (client.cache) {
22577
- ingestInCache(payload, { cachedAt });
23126
+ ingestInCache(preparedPayload, { cachedAt });
23127
+ const cacheKey = [
23128
+ 'communityUsers',
23129
+ 'query',
23130
+ Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
23131
+ ];
23132
+ pushToCache(cacheKey, {
23133
+ communityUsers: communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
23134
+ paging,
23135
+ });
22578
23136
  }
22579
23137
  const nextPage = toPage(paging.next);
22580
23138
  const prevPage = toPage(paging.previous);
@@ -22594,9 +23152,29 @@ const queryCommunityMembers = async (query) => {
22594
23152
  * @category Post API
22595
23153
  */
22596
23154
  queryCommunityMembers.locally = (query) => {
23155
+ var _a, _b;
22597
23156
  const client = getActiveClient();
22598
23157
  client.log('community/queryCommunityMembers', query);
22599
- // TODO
23158
+ if (!client.cache)
23159
+ return;
23160
+ const _c = query !== null && query !== void 0 ? query : {}, { page } = _c, params = __rest(_c, ["page"]);
23161
+ const cacheKey = [
23162
+ 'communityUsers',
23163
+ 'query',
23164
+ Object.assign(Object.assign({}, params), { options: Object.assign({}, page) }),
23165
+ ];
23166
+ const { data, cachedAt } = (_a = pullFromCache(cacheKey)) !== null && _a !== void 0 ? _a : {};
23167
+ if (!(data === null || data === void 0 ? void 0 : data.communityUsers.length))
23168
+ return;
23169
+ const communityUsers = data.communityUsers
23170
+ .map(key => pullFromCache(['communityUsers', 'get', key]))
23171
+ .filter(Boolean)
23172
+ .map(({ data }) => data);
23173
+ const prevPage = toPage(data === null || data === void 0 ? void 0 : data.paging.previous);
23174
+ const nextPage = toPage(data === null || data === void 0 ? void 0 : data.paging.next);
23175
+ return communityUsers.length === ((_b = data === null || data === void 0 ? void 0 : data.communityUsers) === null || _b === void 0 ? void 0 : _b.length)
23176
+ ? { data: communityUsers, cachedAt, prevPage, nextPage }
23177
+ : undefined;
22600
23178
  };
22601
23179
 
22602
23180
  /**
@@ -23305,38 +23883,6 @@ const preparePayloadForCache = (event, payload) => {
23305
23883
  }
23306
23884
  };
23307
23885
 
23308
- /** @hidden */
23309
- /*
23310
- * @param message payload from http request without myReactions
23311
- * add myReactions to http response if the event was a reaction event
23312
- */
23313
- const prepareMessagePayloadForCache = (payload) => {
23314
- const client = getActiveClient();
23315
- const cached = pullFromCache(['message', 'get', payload.messageId]);
23316
- // '[]' in cases where the new reaction is the first one
23317
- const myReactions = (cached === null || cached === void 0 ? void 0 : cached.data.myReactions) || [];
23318
- // add myReactions to the payload
23319
- Object.assign(payload, { myReactions });
23320
- // check if there are any updates to the reactions
23321
- const latestReaction = payload === null || payload === void 0 ? void 0 : payload.latestReaction;
23322
- const isLatestReactionMine = latestReaction && latestReaction.userId === client.userId;
23323
- if (!isLatestReactionMine) {
23324
- return;
23325
- }
23326
- // new reaction added
23327
- if (latestReaction.eventName === 'add' && !myReactions.includes(latestReaction.reactionName)) {
23328
- Object.assign(payload, {
23329
- myReactions: [...myReactions, latestReaction.reactionName],
23330
- });
23331
- }
23332
- // existing reaction removed
23333
- if (latestReaction.eventName === 'remove' && myReactions.includes(latestReaction.reactionName)) {
23334
- Object.assign(payload, {
23335
- myReactions: myReactions.filter(x => x !== latestReaction.reactionName),
23336
- });
23337
- }
23338
- };
23339
-
23340
23886
  /**
23341
23887
  * ```js
23342
23888
  * import { addReaction } from '@amityco/ts-sdk'
@@ -23364,6 +23910,7 @@ const addReaction = async (referenceType, referenceId, reactionName) => {
23364
23910
  referenceId,
23365
23911
  referenceType,
23366
23912
  reactionName,
23913
+ referenceVersion: referenceType === 'message' ? 5 : undefined,
23367
23914
  });
23368
23915
  if (client.cache) {
23369
23916
  const model = pullFromCache([
@@ -23440,7 +23987,12 @@ const removeReaction = async (referenceType, referenceId, reactionName) => {
23440
23987
  reactionName,
23441
23988
  });
23442
23989
  await client.http.delete(`/api/v2/reactions`, {
23443
- data: { referenceId, referenceType, reactionName },
23990
+ data: {
23991
+ referenceId,
23992
+ referenceType,
23993
+ reactionName,
23994
+ referenceVersion: referenceType === 'message' ? 5 : undefined,
23995
+ },
23444
23996
  });
23445
23997
  if (client.cache) {
23446
23998
  const model = pullFromCache([
@@ -23953,8 +24505,9 @@ const onReactionAdded = (referenceType, referenceId, callback) => {
23953
24505
  */
23954
24506
  if (referenceType === 'message') {
23955
24507
  const client = getActiveClient();
23956
- const filter = (payload) => {
24508
+ const filter = (rawPayload) => {
23957
24509
  var _a;
24510
+ const payload = prepareMessagePayload(rawPayload);
23958
24511
  const cached = pullFromCache([
23959
24512
  'message',
23960
24513
  'get',
@@ -23966,7 +24519,7 @@ const onReactionAdded = (referenceType, referenceId, callback) => {
23966
24519
  callbackWrapper(payload.messages[0]);
23967
24520
  }
23968
24521
  };
23969
- return createEventSubscriber(client, 'reaction/onReactionAdded', 'v3.message.didUpdate', filter);
24522
+ return createEventSubscriber(client, 'reaction/onReactionAdded', 'message.updated', filter);
23970
24523
  }
23971
24524
  if (referenceType === 'post') {
23972
24525
  return onPostReactionAdded(callbackWrapper);
@@ -23999,8 +24552,9 @@ const onReactionRemoved = (referenceType, referenceId, callback) => {
23999
24552
  };
24000
24553
  if (referenceType === 'message') {
24001
24554
  const client = getActiveClient();
24002
- const filter = (payload) => {
24555
+ const filter = (rawPayload) => {
24003
24556
  var _a;
24557
+ const payload = prepareMessagePayload(rawPayload);
24004
24558
  const cached = pullFromCache([
24005
24559
  'message',
24006
24560
  'get',
@@ -24012,7 +24566,7 @@ const onReactionRemoved = (referenceType, referenceId, callback) => {
24012
24566
  callbackWrapper(payload.messages[0]);
24013
24567
  }
24014
24568
  };
24015
- return createEventSubscriber(client, 'reaction/onReactionRemoved', 'v3.message.didUpdate', filter);
24569
+ return createEventSubscriber(client, 'reaction/onReactionRemoved', 'message.updated', filter);
24016
24570
  }
24017
24571
  if (referenceType === 'post') {
24018
24572
  return onPostReactionRemoved(callbackWrapper);
@@ -24045,7 +24599,8 @@ const onReactorAdded = (referenceType, referenceId, callback) => {
24045
24599
  }
24046
24600
  };
24047
24601
  if (referenceType === 'message') {
24048
- const filter = (payload) => {
24602
+ const filter = (rawPayload) => {
24603
+ const payload = prepareMessagePayload(rawPayload);
24049
24604
  if (!payload.messages[0].latestReaction)
24050
24605
  return;
24051
24606
  const _a = payload.messages[0].latestReaction, { eventName, referenceId, referenceType, userDisplayName } = _a, reactor = __rest(_a, ["eventName", "referenceId", "referenceType", "userDisplayName"]);
@@ -24055,7 +24610,7 @@ const onReactorAdded = (referenceType, referenceId, callback) => {
24055
24610
  ingestInCache({ reactions: [reactor] });
24056
24611
  callbackWrapper('message', payload.messages[0].messageId, reactor);
24057
24612
  };
24058
- return createEventSubscriber(client, 'reaction/onReactorAdded', 'v3.message.didUpdate', filter);
24613
+ return createEventSubscriber(client, 'reaction/onReactorAdded', 'message.updated', filter);
24059
24614
  }
24060
24615
  if (referenceType === 'post') {
24061
24616
  const filter = (payload) => {
@@ -24100,7 +24655,8 @@ const onReactorRemoved = (referenceType, referenceId, callback) => {
24100
24655
  }
24101
24656
  };
24102
24657
  if (referenceType === 'message') {
24103
- const filter = (payload) => {
24658
+ const filter = (rawPayload) => {
24659
+ const payload = prepareMessagePayload(rawPayload);
24104
24660
  if (!payload.messages[0].latestReaction)
24105
24661
  return;
24106
24662
  const _a = payload.messages[0].latestReaction, { eventName, referenceId, referenceType } = _a, reactor = __rest(_a, ["eventName", "referenceId", "referenceType"]);
@@ -24110,7 +24666,7 @@ const onReactorRemoved = (referenceType, referenceId, callback) => {
24110
24666
  ingestInCache({ reactions: [reactor] });
24111
24667
  callbackWrapper('message', payload.messages[0].messageId, reactor);
24112
24668
  };
24113
- return createEventSubscriber(client, 'reaction/onReactorRemoved', 'v3.message.didUpdate', filter);
24669
+ return createEventSubscriber(client, 'reaction/onReactorRemoved', 'message.updated', filter);
24114
24670
  }
24115
24671
  if (referenceType === 'post') {
24116
24672
  const filter = (payload) => {
@@ -24180,7 +24736,7 @@ const liveReactions = (params, callback, config) => {
24180
24736
  error: data.error,
24181
24737
  });
24182
24738
  };
24183
- const realtimeRouter = (reaction, action) => {
24739
+ const realtimeRouter = (action) => (reaction) => {
24184
24740
  var _a;
24185
24741
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24186
24742
  if (!collection)
@@ -24217,7 +24773,7 @@ const liveReactions = (params, callback, config) => {
24217
24773
  responder(data);
24218
24774
  }, queryOptions(policy));
24219
24775
  };
24220
- disposers.push(onReactorAdded(queryParams.referenceType, queryParams.referenceId, reaction => realtimeRouter(reaction, 'onAdded')), onReactorRemoved(queryParams.referenceType, queryParams.referenceId, reaction => realtimeRouter(reaction, 'onRemoved')));
24776
+ disposers.push(onReactorAdded(queryParams.referenceType, queryParams.referenceId, realtimeRouter('onAdded')), onReactorRemoved(queryParams.referenceType, queryParams.referenceId, realtimeRouter('onRemoved')));
24221
24777
  onFetch();
24222
24778
  return () => {
24223
24779
  log(`liveReactions(tmpid: ${timestamp}) > dispose`);
@@ -24264,16 +24820,26 @@ var REFERENCE_TYPES = {
24264
24820
  const createReport = async (referenceType, referenceId) => {
24265
24821
  const client = getActiveClient();
24266
24822
  client.log('report/createReport', { referenceType, referenceId });
24267
- const { domainName } = REFERENCE_TYPES[referenceType];
24268
- const { data } = await client.http.post(`/api/${referenceType === 'user'
24269
- ? `v4/me/flags/${encodeURIComponent(referenceId)}`
24270
- : `v3/${domainName}/${encodeURIComponent(referenceId)}/flag`}`);
24823
+ const getAPIUrl = () => {
24824
+ if (referenceType === 'user') {
24825
+ return `/api/v4/me/flags/${encodeURIComponent(referenceId)}`;
24826
+ }
24827
+ if (referenceType === 'message') {
24828
+ return `/api/v5/messages/${encodeURIComponent(referenceId)}/flags`;
24829
+ }
24830
+ const { domainName } = REFERENCE_TYPES[referenceType];
24831
+ return `/api/v3/${domainName}/${encodeURIComponent(referenceId)}/flag`;
24832
+ };
24833
+ const { data } = await client.http.post(getAPIUrl());
24271
24834
  if (client.cache)
24272
- ingestInCache(data);
24273
- const event = referenceType === 'message'
24274
- ? 'v3.message.didUpdate'
24275
- : `${referenceType}.flagged`;
24276
- fireEvent(event, data);
24835
+ ingestInCache(referenceType === 'message' ? prepareMessagePayload(data) : data);
24836
+ if (referenceType === 'message') {
24837
+ fireEvent('message.flagged', data);
24838
+ }
24839
+ else {
24840
+ // @ts-ignore
24841
+ fireEvent(`${referenceType}.flagged`, data);
24842
+ }
24277
24843
  return !!data;
24278
24844
  };
24279
24845
 
@@ -24293,16 +24859,26 @@ const createReport = async (referenceType, referenceId) => {
24293
24859
  const deleteReport = async (referenceType, referenceId) => {
24294
24860
  const client = getActiveClient();
24295
24861
  client.log('report/deleteReport', { referenceType, referenceId });
24296
- const { domainName } = REFERENCE_TYPES[referenceType];
24297
- const { data } = await client.http.delete(`/api/${referenceType === 'user'
24298
- ? `v4/me/flags/${encodeURIComponent(referenceId)}`
24299
- : `v3/${domainName}/${encodeURIComponent(referenceId)}/unflag`}`);
24862
+ const getAPIUrl = () => {
24863
+ if (referenceType === 'user') {
24864
+ return `/api/v4/me/flags/${encodeURIComponent(referenceId)}`;
24865
+ }
24866
+ if (referenceType === 'message') {
24867
+ return `/api/v5/messages/${encodeURIComponent(referenceId)}/flags`;
24868
+ }
24869
+ const { domainName } = REFERENCE_TYPES[referenceType];
24870
+ return `/api/v3/${domainName}/${encodeURIComponent(referenceId)}/unflag`;
24871
+ };
24872
+ const { data } = await client.http.delete(getAPIUrl());
24300
24873
  if (client.cache)
24301
- ingestInCache(data);
24302
- const event = referenceType === 'message'
24303
- ? 'v3.message.didUpdate'
24304
- : `${referenceType}.unflagged`;
24305
- fireEvent(event, data);
24874
+ ingestInCache(referenceType === 'message' ? prepareMessagePayload(data) : data);
24875
+ if (referenceType === 'message') {
24876
+ fireEvent('message.unflagged', data);
24877
+ }
24878
+ else {
24879
+ // @ts-ignore
24880
+ fireEvent(`${referenceType}.unflagged`, data);
24881
+ }
24306
24882
  return !!data;
24307
24883
  };
24308
24884
 
@@ -24324,26 +24900,45 @@ const isReportedByMe = async (referenceType, referenceId) => {
24324
24900
  const client = getActiveClient();
24325
24901
  client.log('report/isReportedByMe', { referenceType, referenceId });
24326
24902
  const { eventName, primaryKey } = REFERENCE_TYPES[referenceType];
24903
+ if (referenceType === 'message') {
24904
+ const { data } = await client.http.get(`/api/v5/messages/${encodeURIComponent(referenceId)}/flags`);
24905
+ return data.result;
24906
+ }
24327
24907
  const { result, isFlagByMe } = (_a = (await synchronousWSCall(client, eventName, {
24328
24908
  [primaryKey]: referenceId,
24329
24909
  }))) !== null && _a !== void 0 ? _a : {};
24330
24910
  return (_b = result !== null && result !== void 0 ? result : isFlagByMe) !== null && _b !== void 0 ? _b : false;
24331
24911
  };
24332
24912
 
24333
- /** @hidden */
24913
+ function convertFromRaw$1(_a, params) {
24914
+ var { _id } = _a, rest = __rest(_a, ["_id"]);
24915
+ return Object.assign(Object.assign(Object.assign({}, rest), params), { defaultSubChannelId: _id });
24916
+ }
24917
+ function getSegmentParams(rawChannel) {
24918
+ let cached;
24919
+ try {
24920
+ cached = pullFromCache(['channel', 'get', rawChannel.channelId]);
24921
+ // eslint-disable-next-line no-empty
24922
+ }
24923
+ catch (_a) { }
24924
+ if (cached) {
24925
+ return {
24926
+ defaultSubChannelHasUnreadMention: cached.data.defaultSubChannelHasUnreadMention,
24927
+ defaultSubChannelUnreadCount: cached.data.defaultSubChannelUnreadCount,
24928
+ localReadToSegment: cached.data.localReadToSegment,
24929
+ localLastMentionSegment: cached.data.localLastMentionSegment,
24930
+ };
24931
+ }
24932
+ return {
24933
+ defaultSubChannelHasUnreadMention: false,
24934
+ defaultSubChannelUnreadCount: 0,
24935
+ // @ts-ignore
24936
+ localReadToSegment: rawChannel.messageCount > 0 ? rawChannel.messageCount - 1 : 0,
24937
+ localLastMentionSegment: 0,
24938
+ };
24939
+ }
24334
24940
  const prepareChannelPayload = (payload) => {
24335
- const client = getActiveClient();
24336
- const channels = payload.channels.map(channel => {
24337
- const channelUser = payload.channelUsers.find(channelUser => channelUser.userId === client.userId && channel.channelId === channelUser.channelId);
24338
- const hasMention = channelUser
24339
- ? channelUser.readToSegment < channelUser.lastMentionedSegment
24340
- : false;
24341
- const unreadCount = channelUser && channelUser.membership === 'member' && channel.messageCount
24342
- ? Math.max(0, channel.messageCount - channelUser.readToSegment)
24343
- : 0;
24344
- return Object.assign(Object.assign({}, channel), { hasMention,
24345
- unreadCount });
24346
- });
24941
+ const channels = payload.channels.map(channel => convertFromRaw$1(channel, getSegmentParams(channel)));
24347
24942
  return Object.assign(Object.assign({}, payload), { channels });
24348
24943
  };
24349
24944
 
@@ -24479,10 +25074,10 @@ getChannels.locally = (channelIds) => {
24479
25074
  const cached = channelIds
24480
25075
  .map(channelId => pullFromCache(['channel', 'get', channelId]))
24481
25076
  .filter(Boolean);
24482
- const channels = cached.map(({ data }) => data);
24483
- const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
24484
25077
  if ((cached === null || cached === void 0 ? void 0 : cached.length) < channelIds.length)
24485
25078
  return;
25079
+ const channels = cached.map(({ data }) => data);
25080
+ const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
24486
25081
  return {
24487
25082
  data: channels,
24488
25083
  cachedAt: oldest.cachedAt,
@@ -24557,7 +25152,7 @@ getChannel.locally = (channelId) => {
24557
25152
  /**
24558
25153
  * ```js
24559
25154
  * import { createChannel } from '@amityco/ts-sdk'
24560
- * const created = await createChannel({ channelId: 'foobar', displayName: 'foobar' })
25155
+ * const created = await createChannel({ displayName: 'foobar' })
24561
25156
  * ```
24562
25157
  *
24563
25158
  * Creates an {@link Amity.Channel}
@@ -24709,18 +25304,19 @@ const leaveChannel = async (channelId) => {
24709
25304
  const queryChannelMembers = async (query) => {
24710
25305
  const client = getActiveClient();
24711
25306
  client.log('channel/queryChannelMembers', query);
24712
- const _a = query !== null && query !== void 0 ? query : {}, { page = { limit: 10 } } = _a, params = __rest(_a, ["page"]);
25307
+ const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
24713
25308
  const { data: queryPayload } = await client.http.get(`/api/v4/channels/${encodeURIComponent(params.channelId)}/users`, {
24714
25309
  params: Object.assign(Object.assign({}, params), { options: {
24715
25310
  token: toToken(page, 'skiplimit'),
24716
25311
  } }),
24717
25312
  });
24718
25313
  const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
24719
- const data = prepareChannelPayload(payload);
24720
- const { channelUsers } = data;
25314
+ const channelPayload = prepareChannelPayload(payload);
25315
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25316
+ const { channelUsers } = preparedPayload;
24721
25317
  const cachedAt = client.cache && Date.now();
24722
25318
  if (client.cache) {
24723
- ingestInCache(data);
25319
+ ingestInCache(preparedPayload);
24724
25320
  const cacheKey = [
24725
25321
  'channelUsers',
24726
25322
  'query',
@@ -24733,7 +25329,12 @@ const queryChannelMembers = async (query) => {
24733
25329
  }
24734
25330
  const nextPage = toPage(paging.next);
24735
25331
  const prevPage = toPage(paging.previous);
24736
- return { data: channelUsers, cachedAt, nextPage, prevPage };
25332
+ return {
25333
+ data: channelUsers,
25334
+ cachedAt,
25335
+ nextPage,
25336
+ prevPage,
25337
+ };
24737
25338
  };
24738
25339
  /**
24739
25340
  * ```js
@@ -24754,7 +25355,7 @@ queryChannelMembers.locally = (query) => {
24754
25355
  client.log('channel/queryChannelMembers.locally', query);
24755
25356
  if (!client.cache)
24756
25357
  return;
24757
- const { page = { limit: 10 } } = query, params = __rest(query, ["page"]);
25358
+ const { page } = query, params = __rest(query, ["page"]);
24758
25359
  const cacheKey = [
24759
25360
  'channelUsers',
24760
25361
  'query',
@@ -24800,7 +25401,7 @@ const addChannelMembers = async (channelId, userIds) => {
24800
25401
  /*
24801
25402
  * should fire event for each user that was added
24802
25403
  */
24803
- userIds.forEach(id => fireEvent('v3.channel.didAddUsers', Object.assign(Object.assign({}, data), { channelUsers: data.channelUsers.filter(u => u.userId === id) })));
25404
+ userIds.forEach(id => fireEvent('channel.membersAdded', Object.assign(Object.assign({}, payload), { channelUsers: data.channelUsers.filter(u => u.userId === id) })));
24804
25405
  const { channelUsers } = data;
24805
25406
  return !!channelUsers.find(channelUser => channelUser.channelId === channelId && channelUser.membership === 'member');
24806
25407
  };
@@ -24827,7 +25428,10 @@ const removeChannelMembers = async (channelId, userIds) => {
24827
25428
  const data = prepareChannelPayload(payload);
24828
25429
  if (client.cache)
24829
25430
  ingestInCache(data);
24830
- fireEvent('v3.channel.didRemoveUsers', data);
25431
+ /*
25432
+ * should fire event for each user that was removed
25433
+ */
25434
+ userIds.forEach(id => fireEvent('channel.membersRemoved', Object.assign(Object.assign({}, payload), { channelUsers: data.channelUsers.filter(u => u.userId === id) })));
24831
25435
  const { channelUsers } = data;
24832
25436
  return !!channelUsers.find(channelUser => channelUser.channelId === channelId && channelUser.membership !== 'member');
24833
25437
  };
@@ -24906,11 +25510,12 @@ const banChannelMembers = async (channelId, userIds) => {
24906
25510
  const { data: payload } = await client.http.put(`/api/v3/channels/${channelId}/users/ban`, {
24907
25511
  userIds,
24908
25512
  });
24909
- const data = prepareChannelPayload(payload);
25513
+ const channelPayload = prepareChannelPayload(payload);
25514
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25515
+ const { channelUsers } = preparedPayload;
24910
25516
  const cachedAt = client.cache && Date.now();
24911
25517
  if (client.cache)
24912
- ingestInCache(data, { cachedAt });
24913
- const { channelUsers } = data;
25518
+ ingestInCache(preparedPayload, { cachedAt });
24914
25519
  return {
24915
25520
  data: channelUsers === null || channelUsers === void 0 ? void 0 : channelUsers.filter(user => user.membership === 'banned'),
24916
25521
  cachedAt,
@@ -24937,17 +25542,92 @@ const unbanChannelMembers = async (channelId, userIds) => {
24937
25542
  const { data: payload } = await client.http.put(`/api/v3/channels/${encodeURIComponent(channelId)}/users/unban`, {
24938
25543
  userIds,
24939
25544
  });
24940
- const data = prepareChannelPayload(payload);
25545
+ const channelPayload = prepareChannelPayload(payload);
25546
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
24941
25547
  const cachedAt = client.cache && Date.now();
24942
25548
  if (client.cache)
24943
- ingestInCache(data, { cachedAt });
24944
- const { channelUsers } = data;
25549
+ ingestInCache(preparedPayload, { cachedAt });
25550
+ const { channelUsers } = preparedPayload;
24945
25551
  return {
24946
25552
  data: channelUsers === null || channelUsers === void 0 ? void 0 : channelUsers.filter(user => user.membership === 'member'),
24947
25553
  cachedAt,
24948
25554
  };
24949
25555
  };
24950
25556
 
25557
+ /**
25558
+ * ```js
25559
+ * import { startReading } from '@amityco/ts-sdk'
25560
+ * const success = await startReading('foo')
25561
+ * ```
25562
+ *
25563
+ * Mark all messages as read and start reading message inside channel
25564
+ *
25565
+ * @param {string} subChannelId - The channel ID to start reading.
25566
+ * @param {string} userId - The user ID of channel member.
25567
+ * @return {Promise<boolean>>} A success boolean if the channel reading of the sub channel had begun.
25568
+ *
25569
+ * @category Message API
25570
+ * @async
25571
+ */
25572
+ const startReading = async (subChannelId, userId = getActiveClient().userId) => {
25573
+ const client = getActiveClient();
25574
+ client.log('message/startReading', { subChannelId });
25575
+ const subChannel = pullFromCache(['subChannel', 'get', subChannelId]);
25576
+ if (!subChannel) {
25577
+ return;
25578
+ }
25579
+ const { channelId } = subChannel.data;
25580
+ const channel = pullFromCache(['channel', 'get', channelId]);
25581
+ if (!channel || channel.data.defaultSubChannelId !== subChannelId) {
25582
+ return;
25583
+ }
25584
+ const update = Object.assign(Object.assign({}, channel.data), {
25585
+ // @ts-ignore
25586
+ localReading: true, defaultSubChannelUnreadCount: 0, defaultSubChannelHasUnreadMention: false });
25587
+ pushToCache(['channel', 'get', channelId], update);
25588
+ client.emitter.emit('local.channel.updated', { channels: [update] });
25589
+ const result = await synchronousWSCall(client, 'channel.startReading', {
25590
+ channelId,
25591
+ });
25592
+ return !!result;
25593
+ };
25594
+
25595
+ /**
25596
+ * ```js
25597
+ * import { stopReading } from '@amityco/ts-sdk'
25598
+ * const success = await stopReading('foo')
25599
+ * ```
25600
+ *
25601
+ * Stop reading message inside channel
25602
+ *
25603
+ * @param {string} subChannelId - The channel ID to stop reading.
25604
+ * @return {Promise<boolean>>} A success boolean if the sub channel reading was halted.
25605
+ *
25606
+ * @category Message API
25607
+ * @async
25608
+ */
25609
+ const stopReading = async (subChannelId) => {
25610
+ const client = getActiveClient();
25611
+ client.log('message/stopReading', { subChannelId });
25612
+ const subChannel = pullFromCache(['subChannel', 'get', subChannelId]);
25613
+ if (!subChannel) {
25614
+ return;
25615
+ }
25616
+ const { channelId } = subChannel.data;
25617
+ const channel = pullFromCache(['channel', 'get', channelId]);
25618
+ if (!channel || channel.data.defaultSubChannelId !== subChannelId) {
25619
+ return;
25620
+ }
25621
+ const update = Object.assign(Object.assign({}, channel.data), {
25622
+ // @ts-ignore
25623
+ localReading: false });
25624
+ pushToCache(['channel', 'get', channelId], update);
25625
+ const result = await synchronousWSCall(client, 'channel.stopReading', {
25626
+ channelId,
25627
+ });
25628
+ return !!result;
25629
+ };
25630
+
24951
25631
  /**
24952
25632
  * ```js
24953
25633
  * import { onChannelCreated } from '@amityco/ts-sdk'
@@ -24970,7 +25650,7 @@ const onChannelCreated = (callback) => {
24970
25650
  ingestInCache(data);
24971
25651
  callback(data.channels[0]);
24972
25652
  };
24973
- return createEventSubscriber(client, 'onChannelCreated', 'v3.channel.didCreate', filter);
25653
+ return createEventSubscriber(client, 'onChannelCreated', 'channel.created', filter);
24974
25654
  };
24975
25655
 
24976
25656
  /**
@@ -24995,7 +25675,13 @@ const onChannelUpdated = (callback) => {
24995
25675
  ingestInCache(data);
24996
25676
  callback(data.channels[0]);
24997
25677
  };
24998
- return createEventSubscriber(client, 'onChannelUpdated', 'v3.channel.didUpdate', filter);
25678
+ const disposers = [
25679
+ createEventSubscriber(client, 'onChannelUpdated', 'channel.updated', filter),
25680
+ createEventSubscriber(client, 'local.channel.updated', 'local.channel.updated', payload => callback(payload.channels[0])),
25681
+ ];
25682
+ return () => {
25683
+ disposers.forEach(fn => fn());
25684
+ };
24999
25685
  };
25000
25686
 
25001
25687
  /**
@@ -25020,13 +25706,13 @@ const onChannelDeleted = (callback) => {
25020
25706
  ingestInCache(data);
25021
25707
  callback(data.channels[0]);
25022
25708
  };
25023
- return createEventSubscriber(client, 'onChannelDeleted', 'v3.channel.didDelete', filter);
25709
+ return createEventSubscriber(client, 'onChannelDeleted', 'channel.deleted', filter);
25024
25710
  };
25025
25711
 
25026
25712
  /**
25027
25713
  * ```js
25028
25714
  * import { onChannelJoined } from '@amityco/ts-sdk'
25029
- * const dispose = onChannelJoined(channel => {
25715
+ * const dispose = onChannelJoined((channel, member) => {
25030
25716
  * // ...
25031
25717
  * })
25032
25718
  * ```
@@ -25041,17 +25727,19 @@ const onChannelDeleted = (callback) => {
25041
25727
  const onChannelJoined = (callback) => {
25042
25728
  const client = getActiveClient();
25043
25729
  const filter = (payload) => {
25044
- const data = prepareChannelPayload(payload);
25045
- ingestInCache(data);
25046
- callback(data.channels[0]);
25730
+ const channelPayload = prepareChannelPayload(payload);
25731
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25732
+ const { channels, channelUsers } = preparedPayload;
25733
+ ingestInCache(preparedPayload);
25734
+ callback(channels[0], channelUsers[0]);
25047
25735
  };
25048
- return createEventSubscriber(client, 'onChannelJoined', 'v3.channel.didJoin', filter);
25736
+ return createEventSubscriber(client, 'onChannelJoined', 'channel.joined', filter);
25049
25737
  };
25050
25738
 
25051
25739
  /**
25052
25740
  * ```js
25053
25741
  * import { onChannelLeft } from '@amityco/ts-sdk'
25054
- * const dispose = onChannelLeft(channel => {
25742
+ * const dispose = onChannelLeft((channel, member) => {
25055
25743
  * // ...
25056
25744
  * })
25057
25745
  * ```
@@ -25064,13 +25752,40 @@ const onChannelJoined = (callback) => {
25064
25752
  * @category Channel Events
25065
25753
  */
25066
25754
  const onChannelLeft = (callback) => {
25755
+ const client = getActiveClient();
25756
+ const filter = (payload) => {
25757
+ const channelPayload = prepareChannelPayload(payload);
25758
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25759
+ const { channels, channelUsers } = preparedPayload;
25760
+ ingestInCache(preparedPayload);
25761
+ callback(channels[0], channelUsers[0]);
25762
+ };
25763
+ return createEventSubscriber(client, 'onChannelLeft', 'channel.left', filter);
25764
+ };
25765
+
25766
+ /**
25767
+ * ```js
25768
+ * import { onChannelMuted } from '@amityco/ts-sdk'
25769
+ * const dispose = onChannelMuted(channel => {
25770
+ * // ...
25771
+ * })
25772
+ * ```
25773
+ *
25774
+ * Fired when any {@link Amity.Channel} have been muted
25775
+ *
25776
+ * @param callback The function to call when the event was fired
25777
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
25778
+ *
25779
+ * @category Channel Events
25780
+ */
25781
+ const onChannelMuted = (callback) => {
25067
25782
  const client = getActiveClient();
25068
25783
  const filter = (payload) => {
25069
25784
  const data = prepareChannelPayload(payload);
25070
25785
  ingestInCache(data);
25071
25786
  callback(data.channels[0]);
25072
25787
  };
25073
- return createEventSubscriber(client, 'onChannelLeft', 'v3.channel.didLeave', filter);
25788
+ return createEventSubscriber(client, 'onChannelMuted', 'channel.setMuted', filter);
25074
25789
  };
25075
25790
 
25076
25791
  /**
@@ -25091,11 +25806,13 @@ const onChannelLeft = (callback) => {
25091
25806
  const onChannelMemberAdded = (callback) => {
25092
25807
  const client = getActiveClient();
25093
25808
  const filter = (payload) => {
25094
- const data = prepareChannelPayload(payload);
25095
- ingestInCache(data);
25096
- callback(data.channels[0], data.channelUsers[0]);
25809
+ const channelPayload = prepareChannelPayload(payload);
25810
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25811
+ const { channels, channelUsers } = preparedPayload;
25812
+ ingestInCache(preparedPayload);
25813
+ callback(channels[0], channelUsers.find(cu => cu.membership === 'member'));
25097
25814
  };
25098
- return createEventSubscriber(client, 'onChannelMemberAdded', 'v3.channel.didAddUsers', filter);
25815
+ return createEventSubscriber(client, 'onChannelMemberAdded', 'channel.membersAdded', filter);
25099
25816
  };
25100
25817
 
25101
25818
  /**
@@ -25116,11 +25833,13 @@ const onChannelMemberAdded = (callback) => {
25116
25833
  const onChannelMemberRemoved = (callback) => {
25117
25834
  const client = getActiveClient();
25118
25835
  const filter = (payload) => {
25119
- const data = prepareChannelPayload(payload);
25120
- ingestInCache(data);
25121
- callback(data.channels[0], data.channelUsers[0]);
25836
+ const channelPayload = prepareChannelPayload(payload);
25837
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25838
+ const { channels, channelUsers } = preparedPayload;
25839
+ ingestInCache(preparedPayload);
25840
+ callback(channels[0], channelUsers[0]);
25122
25841
  };
25123
- return createEventSubscriber(client, 'onChannelMemberRemoved', 'v3.channel.didRemoveUsers', filter);
25842
+ return createEventSubscriber(client, 'onChannelMemberRemoved', 'channel.membersRemoved', filter);
25124
25843
  };
25125
25844
 
25126
25845
  /**
@@ -25141,11 +25860,13 @@ const onChannelMemberRemoved = (callback) => {
25141
25860
  const onChannelMemberBanned = (callback) => {
25142
25861
  const client = getActiveClient();
25143
25862
  const filter = (payload) => {
25144
- const data = prepareChannelPayload(payload);
25145
- ingestInCache(data);
25146
- callback(data.channels[0], data.channelUsers.find(cu => cu.membership === 'banned'));
25863
+ const channelPayload = prepareChannelPayload(payload);
25864
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25865
+ const { channels, channelUsers } = preparedPayload;
25866
+ ingestInCache(preparedPayload);
25867
+ callback(channels[0], channelUsers.find(cu => cu.membership === 'banned'));
25147
25868
  };
25148
- return createEventSubscriber(client, 'onChannelMemberBanned', 'v3.channel.didBan', filter);
25869
+ return createEventSubscriber(client, 'onChannelMemberBanned', 'channel.banned', filter);
25149
25870
  };
25150
25871
 
25151
25872
  /**
@@ -25166,11 +25887,13 @@ const onChannelMemberBanned = (callback) => {
25166
25887
  const onChannelMemberUnbanned = (callback) => {
25167
25888
  const client = getActiveClient();
25168
25889
  const filter = (payload) => {
25169
- const data = prepareChannelPayload(payload);
25170
- ingestInCache(data);
25171
- callback(data.channels[0], data.channelUsers.find(cu => cu.membership === 'none'));
25890
+ const channelPayload = prepareChannelPayload(payload);
25891
+ const preparedPayload = prepareMembershipPayload(channelPayload, 'channelUsers');
25892
+ const { channels, channelUsers } = preparedPayload;
25893
+ ingestInCache(preparedPayload);
25894
+ callback(channels[0], channelUsers.find(cu => cu.membership === 'none'));
25172
25895
  };
25173
- return createEventSubscriber(client, 'onChannelMemberBanned', 'v3.channel.didUnban', filter);
25896
+ return createEventSubscriber(client, 'onChannelMemberUnbanned', 'channel.unbanned', filter);
25174
25897
  };
25175
25898
 
25176
25899
  /**
@@ -25206,7 +25929,7 @@ const observeChannel = (channelId, callback) => {
25206
25929
  (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
25207
25930
  };
25208
25931
  const disposers = [];
25209
- 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')));
25932
+ 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')));
25210
25933
  runQuery(createQuery(getChannel, channelId), result => result.data && router(result, 'onFetch'));
25211
25934
  return () => {
25212
25935
  log(`observeChannel(tmpid: ${timestamp}) > dispose`);
@@ -25241,44 +25964,384 @@ const observeChannels = (callback) => {
25241
25964
  (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, channel);
25242
25965
  (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, channel);
25243
25966
  };
25244
- 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')));
25967
+ 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')));
25245
25968
  return () => {
25246
25969
  log(`observeChannels(tmpid: ${timestamp}) > dispose`);
25247
25970
  disposers.forEach(fn => fn());
25248
25971
  };
25249
25972
  };
25250
25973
 
25974
+ function hasMention(model, userId) {
25975
+ var _a, _b;
25976
+ const channelMention = (_a = model === null || model === void 0 ? void 0 : model.mentionees) === null || _a === void 0 ? void 0 : _a.find(x => x.type === 'channel');
25977
+ if (channelMention) {
25978
+ return true;
25979
+ }
25980
+ const userMention = (_b = model === null || model === void 0 ? void 0 : model.mentionees) === null || _b === void 0 ? void 0 : _b.find(x => x.type === 'user');
25981
+ if (userMention) {
25982
+ return userMention.userIds.includes(userId);
25983
+ }
25984
+ return false;
25985
+ }
25986
+ function isCollectionOutdated(collection, newItem, action) {
25987
+ const key = identifyModelKey(newItem);
25988
+ // @ts-ignore
25989
+ const item = collection.find(x => x[key] === newItem[key]);
25990
+ if (item) {
25991
+ return hasUpdates(item, newItem);
25992
+ }
25993
+ return action === 'onCreate';
25994
+ }
25995
+ function merge(collection1, collection2) {
25996
+ const temp = [...collection1, ...collection2];
25997
+ if (temp.length === 0) {
25998
+ return [];
25999
+ }
26000
+ const key = identifyModelKey(temp[0]);
26001
+ const map = new Map();
26002
+ // @ts-ignore
26003
+ temp.forEach(x => map.set(x[key], x));
26004
+ return Array.from(map.values());
26005
+ }
26006
+
25251
26007
  /**
25252
26008
  * ```js
25253
- * import { liveChannels } from '@amityco/ts-sdk'
25254
- *
25255
- * let channels = []
25256
- * const unsub = liveChannels({
25257
- * displayName: Amity.Channel['displayName'],
25258
- * }, response => merge(channels, response.data))
26009
+ * import { onMessageCreated } from '@amityco/ts-sdk'
26010
+ * const dispose = onMessageCreated(message => {
26011
+ * // ...
26012
+ * })
25259
26013
  * ```
25260
26014
  *
25261
- * Observe all mutations on a list of {@link Amity.Channel}s
26015
+ * Fired when an {@link Amity.Message} has been created
25262
26016
  *
25263
- * @param params for querying channels
25264
- * @param callback the function to call when new data are available
25265
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channels
26017
+ * @param callback The function to call when the event was fired
26018
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
25266
26019
  *
25267
- * @category Channel Live Collection
26020
+ * @category Message Events
25268
26021
  */
25269
- const liveChannels = (params, callback, config) => {
25270
- const { log, cache, userId } = getActiveClient();
25271
- if (!cache) {
25272
- console.log(ENABLE_CACHE_MESSAGE);
25273
- }
25274
- const timestamp = Date.now();
25275
- log(`liveChannels(tmpid: ${timestamp}) > listen`);
25276
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
25277
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
25278
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
25279
- const disposers = [];
25280
- const cacheKey = ['channel', 'collection', {}];
25281
- const responder = (data) => {
26022
+ const onMessageCreated = (callback) => {
26023
+ const client = getActiveClient();
26024
+ const filter = (rawPayload) => {
26025
+ const payload = prepareMessagePayload(rawPayload);
26026
+ const message = payload.messages[0];
26027
+ const cached = pullFromCache(['channel', 'get', message.channelId]);
26028
+ if (cached && cached.data.defaultSubChannelId === message.subChannelId) {
26029
+ let update;
26030
+ // @ts-ignore
26031
+ if (cached.data.localReading) {
26032
+ update = Object.assign(Object.assign({}, cached.data), { localReadToSegment: message.channelSegment, localLastMentionSegment: hasMention(message, client.userId)
26033
+ ? message.channelSegment
26034
+ : cached.data.localLastMentionSegment, messageCount: message.channelSegment, lastActivity: message.createdAt, updatedAt: message.createdAt });
26035
+ }
26036
+ else {
26037
+ 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 });
26038
+ }
26039
+ pushToCache(['channel', 'get', message.channelId], update);
26040
+ client.emitter.emit('local.channel.updated', { channels: [update] });
26041
+ }
26042
+ ingestInCache(payload);
26043
+ callback(message);
26044
+ };
26045
+ const disposers = [
26046
+ createEventSubscriber(client, 'message/onMessageCreated', 'message.created', filter),
26047
+ createEventSubscriber(client, 'local.message.created', 'local.message.created', payload => callback(payload.messages[0])),
26048
+ ];
26049
+ return () => {
26050
+ disposers.forEach(fn => fn());
26051
+ };
26052
+ };
26053
+
26054
+ /**
26055
+ * ```js
26056
+ * import { onMessageUpdated } from '@amityco/ts-sdk'
26057
+ * const dispose = onMessageUpdated(message => {
26058
+ * // ...
26059
+ * })
26060
+ * ```
26061
+ *
26062
+ * Fired when an {@link Amity.Message} has been updated
26063
+ *
26064
+ * @param callback The function to call when the event was fired
26065
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
26066
+ *
26067
+ * @category Message Events
26068
+ */
26069
+ const onMessageUpdated = (callback) => {
26070
+ const client = getActiveClient();
26071
+ const filter = (rawPayload) => {
26072
+ const payload = prepareMessagePayload(rawPayload);
26073
+ ingestInCache(payload);
26074
+ callback(payload.messages[0]);
26075
+ };
26076
+ const disposers = [
26077
+ createEventSubscriber(client, 'message/onMessageUpdated', 'message.updated', filter),
26078
+ createEventSubscriber(client, 'local.message.updated', 'local.message.updated', payload => callback(payload.messages[0])),
26079
+ ];
26080
+ return () => {
26081
+ disposers.forEach(fn => fn());
26082
+ };
26083
+ };
26084
+
26085
+ /**
26086
+ * ```js
26087
+ * import { onMessageDeleted } from '@amityco/ts-sdk'
26088
+ * const dispose = onMessageDeleted(message => {
26089
+ * // ...
26090
+ * })
26091
+ * ```
26092
+ *
26093
+ * Fired when an {@link Amity.Message} was deleted
26094
+ *
26095
+ * @param callback The function to call when the event was fired
26096
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
26097
+ *
26098
+ * @category Message Events
26099
+ */
26100
+ const onMessageDeleted = (callback) => {
26101
+ const client = getActiveClient();
26102
+ const filter = (rawPayload) => {
26103
+ const payload = prepareMessagePayload(rawPayload);
26104
+ ingestInCache(payload);
26105
+ callback(payload.messages[0]);
26106
+ };
26107
+ const disposers = [
26108
+ createEventSubscriber(client, 'message/onMessageDeleted', 'message.deleted', filter),
26109
+ createEventSubscriber(client, 'local.message.deleted', 'local.message.deleted', payload => callback(payload.messages[0])),
26110
+ ];
26111
+ return () => {
26112
+ disposers.forEach(fn => fn());
26113
+ };
26114
+ };
26115
+
26116
+ /**
26117
+ * ```js
26118
+ * import { onMessageFlagged } from '@amityco/ts-sdk'
26119
+ * const dispose = onMessageFlagged(message => {
26120
+ * // ...
26121
+ * })
26122
+ * ```
26123
+ *
26124
+ * Fired when a {@link Amity.Message} has been flagged
26125
+ *
26126
+ * @param callback The function to call when the event was fired
26127
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
26128
+ *
26129
+ * @category Message Events
26130
+ */
26131
+ const onMessageFlagged = (callback) => {
26132
+ const client = getActiveClient();
26133
+ const filter = (rawPayload) => {
26134
+ const payload = prepareMessagePayload(rawPayload);
26135
+ ingestInCache(payload);
26136
+ callback(payload.messages[0]);
26137
+ };
26138
+ return createEventSubscriber(client, 'onMessageFlagged', 'message.flagged', filter);
26139
+ };
26140
+
26141
+ /**
26142
+ * ```js
26143
+ * import { onMessageUnflagged } from '@amityco/ts-sdk'
26144
+ * const dispose = onMessageUnflagged(message => {
26145
+ * // ...
26146
+ * })
26147
+ * ```
26148
+ *
26149
+ * Fired when a flag has been removed from a {@link Amity.Message}
26150
+ *
26151
+ * @param callback The function to call when the event was fired
26152
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
26153
+ *
26154
+ * @category Message Events
26155
+ */
26156
+ const onMessageUnflagged = (callback) => {
26157
+ const client = getActiveClient();
26158
+ const filter = (rawPayload) => {
26159
+ const payload = prepareMessagePayload(rawPayload);
26160
+ ingestInCache(payload);
26161
+ callback(payload.messages[0]);
26162
+ };
26163
+ return createEventSubscriber(client, 'onMessageUnflagged', 'message.unflagged', filter);
26164
+ };
26165
+
26166
+ /**
26167
+ * ```js
26168
+ * import { onMessageFlagCleared } from '@amityco/ts-sdk'
26169
+ * const dispose = onMessageFlagCleared(message => {
26170
+ * // ...
26171
+ * })
26172
+ * ```
26173
+ *
26174
+ * Fired when flags have been cleared for a {@link Amity.Message}
26175
+ *
26176
+ * @param callback The function to call when the event was fired
26177
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
26178
+ *
26179
+ * @category Message Events
26180
+ */
26181
+ const onMessageFlagCleared = (callback) => {
26182
+ const client = getActiveClient();
26183
+ const filter = (rawPayload) => {
26184
+ const payload = prepareMessagePayload(rawPayload);
26185
+ ingestInCache(payload);
26186
+ callback(payload.messages[0]);
26187
+ };
26188
+ return createEventSubscriber(client, 'onMessageFlagCleared', 'message.flagCleared', filter);
26189
+ };
26190
+
26191
+ /**
26192
+ * ```js
26193
+ * import { onMessageReactionAdded } from '@amityco/ts-sdk';
26194
+ *
26195
+ * const unsubscribe = onMessageReactionAdded(message => {
26196
+ * // ...
26197
+ * });
26198
+ * ```
26199
+ *
26200
+ * Fired when a {@link Amity.Message} has been reacted
26201
+ *
26202
+ * @param callback The function to call when the event was fired
26203
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
26204
+ *
26205
+ * @category Post Events
26206
+ */
26207
+ const onMessageReactionAdded = (callback) => {
26208
+ const client = getActiveClient();
26209
+ const filter = (rawPayload) => {
26210
+ const payload = prepareMessagePayload(rawPayload);
26211
+ ingestInCache(payload);
26212
+ callback(payload.messages[0]);
26213
+ };
26214
+ return createEventSubscriber(client, 'onMessageReactionAdded', 'message.reactionAdded', filter);
26215
+ };
26216
+
26217
+ /**
26218
+ * ```js
26219
+ * import { onMessageReactionRemoved } from '@amityco/ts-sdk';
26220
+ *
26221
+ * const unsubscribe = onMessageReactionRemoved(message => {
26222
+ * // ...
26223
+ * });
26224
+ * ```
26225
+ *
26226
+ * Fired when a reaction has been removed from a {@link Amity.Message}
26227
+ *
26228
+ * @param callback The function to call when the event was fired
26229
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
26230
+ *
26231
+ * @category Post Events
26232
+ */
26233
+ const onMessageReactionRemoved = (callback) => {
26234
+ const client = getActiveClient();
26235
+ const filter = (rawPayload) => {
26236
+ const payload = prepareMessagePayload(rawPayload);
26237
+ ingestInCache(payload);
26238
+ callback(payload.messages[0]);
26239
+ };
26240
+ return createEventSubscriber(client, 'onMessageReactionRemoved', 'message.reactionRemoved', filter);
26241
+ };
26242
+
26243
+ /**
26244
+ * ```js
26245
+ * import { liveChannel } from '@amityco/ts-sdk';
26246
+ *
26247
+ * let channel;
26248
+ *
26249
+ * const unsubscribe = liveChannel(channelId, response => {
26250
+ * channel = response.data;
26251
+ * });
26252
+ * ```
26253
+ *
26254
+ * Observe all mutation on a given {@link Amity.Channel}
26255
+ *
26256
+ * @param channelId the ID of the channel to observe
26257
+ * @param callback the function to call when new data are available
26258
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channel
26259
+ *
26260
+ * @category Message Live Object
26261
+ */
26262
+ const liveChannel = (channelId, callback) => {
26263
+ const { log, cache } = getActiveClient();
26264
+ const timestamp = Date.now();
26265
+ log(`liveChannel(tmpid: ${timestamp}) > listen`);
26266
+ if (!cache) {
26267
+ console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
26268
+ }
26269
+ let channel;
26270
+ let isUnsyncedObject = false;
26271
+ const disposers = [];
26272
+ const dispatcher = (data) => {
26273
+ channel = data.data;
26274
+ callback(data);
26275
+ };
26276
+ const realtimeRouter = (eventChannel) => {
26277
+ if (channelId !== eventChannel.channelId) {
26278
+ return;
26279
+ }
26280
+ if (channel && !hasUpdates(channel, eventChannel)) {
26281
+ return;
26282
+ }
26283
+ dispatcher({ loading: false, data: eventChannel, origin: 'event' });
26284
+ };
26285
+ const onFetch = () => {
26286
+ const query = createQuery(getChannel, channelId);
26287
+ runQuery(query, ({ loading, data, error, origin, cachedAt }) => {
26288
+ if (cachedAt === UNSYNCED_OBJECT_CACHED_AT_VALUE) {
26289
+ dispatcher({
26290
+ data,
26291
+ origin,
26292
+ loading: false,
26293
+ error: new ASCApiError(UNSYNCED_OBJECT_CACHED_AT_MESSAGE, 800800 /* Amity.ClientError.DISALOOW_UNSYNCED_OBJECT */, "error" /* Amity.ErrorLevel.ERROR */),
26294
+ });
26295
+ isUnsyncedObject = true;
26296
+ disposers.forEach(fn => fn());
26297
+ }
26298
+ else if (!isUnsyncedObject) {
26299
+ dispatcher({ loading, data, origin, error });
26300
+ }
26301
+ if (error) {
26302
+ disposers.forEach(fn => fn());
26303
+ }
26304
+ });
26305
+ };
26306
+ disposers.push(onChannelUpdated(realtimeRouter), onChannelDeleted(realtimeRouter), onChannelJoined(realtimeRouter), onChannelMuted(realtimeRouter), onMessageCreated(() => null));
26307
+ onFetch();
26308
+ return () => {
26309
+ log(`liveChannel(tmpid: ${timestamp}) > dispose`);
26310
+ disposers.forEach(fn => fn());
26311
+ };
26312
+ };
26313
+
26314
+ /**
26315
+ * ```js
26316
+ * import { liveChannels } from '@amityco/ts-sdk'
26317
+ *
26318
+ * let channels = []
26319
+ * const unsub = liveChannels({
26320
+ * displayName: Amity.Channel['displayName'],
26321
+ * }, response => merge(channels, response.data))
26322
+ * ```
26323
+ *
26324
+ * Observe all mutations on a list of {@link Amity.Channel}s
26325
+ *
26326
+ * @param params for querying channels
26327
+ * @param callback the function to call when new data are available
26328
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channels
26329
+ *
26330
+ * @category Channel Live Collection
26331
+ */
26332
+ const liveChannels = (params, callback, config) => {
26333
+ const { log, cache, userId } = getActiveClient();
26334
+ if (!cache) {
26335
+ console.log(ENABLE_CACHE_MESSAGE);
26336
+ }
26337
+ const timestamp = Date.now();
26338
+ log(`liveChannels(tmpid: ${timestamp}) > listen`);
26339
+ const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
26340
+ const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
26341
+ const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
26342
+ const disposers = [];
26343
+ const cacheKey = ['channel', 'collection', {}];
26344
+ const responder = (data) => {
25282
26345
  var _a, _b;
25283
26346
  let channels = (_a = data.data
25284
26347
  .map(channelId => pullFromCache(['channel', 'get', channelId]))
@@ -25324,21 +26387,17 @@ const liveChannels = (params, callback, config) => {
25324
26387
  error: data.error,
25325
26388
  });
25326
26389
  };
25327
- const realtimeRouter = (channel, action) => {
26390
+ const realtimeRouter = (action) => (channel) => {
25328
26391
  var _a;
25329
26392
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25330
26393
  if (!collection)
25331
26394
  return;
25332
- if (action === 'onCreate') {
25333
- collection.data = [...new Set([channel.channelId, ...collection.data])];
25334
- /*
25335
- * if the filter isDeleted is set, only collection item must be updated and not
25336
- * the collection
25337
- */
25338
- }
25339
- else if (action === 'onDelete' && !params.isDeleted) {
26395
+ if (action === 'onDelete' && params.isDeleted === false) {
25340
26396
  collection.data = collection.data.filter(c => c !== channel.channelId);
25341
26397
  }
26398
+ else {
26399
+ collection.data = [...new Set([channel.channelId, ...collection.data])];
26400
+ }
25342
26401
  pushToCache(cacheKey, collection);
25343
26402
  responder(collection);
25344
26403
  };
@@ -25363,7 +26422,7 @@ const liveChannels = (params, callback, config) => {
25363
26422
  responder(data);
25364
26423
  }, queryOptions(policy));
25365
26424
  };
25366
- disposers.push(onChannelCreated(channel => realtimeRouter(channel, 'onCreate')), onChannelDeleted(channel => realtimeRouter(channel, 'onDelete')), onChannelUpdated(channel => realtimeRouter(channel, 'onUpdate')));
26425
+ 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));
25367
26426
  onFetch();
25368
26427
  return () => {
25369
26428
  log(`liveChannels(tmpid: ${timestamp}) > dispose`);
@@ -25381,184 +26440,655 @@ const liveChannels = (params, callback, config) => {
25381
26440
  * }, response => merge(channelMembers, response.data))
25382
26441
  * ```
25383
26442
  *
25384
- * Observe all mutations on a list of {@link Amity.ChannelUser}s
26443
+ * Observe all mutations on a list of {@link Amity.ChannelUser}s
26444
+ *
26445
+ * @param params for querying channel users
26446
+ * @param callback the function to call when new data are available
26447
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channel users
26448
+ *
26449
+ * @category Channel Live Collection
26450
+ */
26451
+ const liveChannelMembers = (params, callback, config) => {
26452
+ const { log, cache } = getActiveClient();
26453
+ if (!cache) {
26454
+ console.log(ENABLE_CACHE_MESSAGE);
26455
+ }
26456
+ const timestamp = Date.now();
26457
+ log(`liveChannelMembers(tmpid: ${timestamp}) > listen`);
26458
+ const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
26459
+ const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
26460
+ const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
26461
+ const disposers = [];
26462
+ const cacheKey = ['channelUsers', 'collection', { channelId: params.channelId }];
26463
+ const responder = (data) => {
26464
+ var _a, _b;
26465
+ let channelMembers = (_a = data.data
26466
+ .map(id => pullFromCache(['channelUsers', 'get', id]))
26467
+ .filter(Boolean)
26468
+ .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
26469
+ channelMembers = filterByPropEquality(channelMembers, 'roles', params.roles);
26470
+ if (params.memberships) {
26471
+ /*
26472
+ * even though membership includes muted as a possible value
26473
+ * when querying the server.
26474
+ * Muted is specified under seperarte property namely isMuted
26475
+ * Hence why I've seperately checked for it's equality
26476
+ */
26477
+ channelMembers = channelMembers.filter(member => {
26478
+ // @ts-ignore
26479
+ if (params.memberships.includes('muted') && member.isMuted) {
26480
+ return true;
26481
+ }
26482
+ // @ts-ignore
26483
+ return params.memberships.includes(member.membership);
26484
+ });
26485
+ }
26486
+ if (params.search) {
26487
+ const containsMatcher = new RegExp(params.search);
26488
+ channelMembers = channelMembers.filter(m => m.userId.match(containsMatcher));
26489
+ }
26490
+ // sort, 'lastCreated' is the default sort order
26491
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
26492
+ channelMembers = channelMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
26493
+ callback({
26494
+ onNextPage: onFetch,
26495
+ data: channelMembers,
26496
+ hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
26497
+ loading: data.loading,
26498
+ error: data.error,
26499
+ });
26500
+ };
26501
+ const realtimeRouter = (action) => (channel, channelMember) => {
26502
+ var _a;
26503
+ if (params.channelId !== channelMember.channelId) {
26504
+ return;
26505
+ }
26506
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26507
+ if (!collection)
26508
+ return;
26509
+ const channelMemberCacheId = getResolver('channelUsers')({
26510
+ channelId: params.channelId,
26511
+ userId: channelMember.userId,
26512
+ });
26513
+ if (channelMember.membership === 'none') {
26514
+ collection.data = collection.data.filter(m => m !== channelMemberCacheId);
26515
+ }
26516
+ else if (!collection.data.includes(channelMemberCacheId)) {
26517
+ collection.data = [channelMemberCacheId, ...collection.data];
26518
+ }
26519
+ pushToCache(cacheKey, collection);
26520
+ responder(collection);
26521
+ };
26522
+ const onFetch = () => {
26523
+ var _a, _b, _c;
26524
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26525
+ const channelMembers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
26526
+ if (channelMembers.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
26527
+ return;
26528
+ 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 } }));
26529
+ runQuery(query, ({ data: result, error, loading, nextPage: page }) => {
26530
+ const data = {
26531
+ loading,
26532
+ error,
26533
+ params: { page },
26534
+ data: channelMembers,
26535
+ };
26536
+ if (result) {
26537
+ data.data = [...new Set([...channelMembers, ...result.map(getResolver('channelUsers'))])];
26538
+ }
26539
+ pushToCache(cacheKey, data);
26540
+ responder(data);
26541
+ }, queryOptions(policy));
26542
+ };
26543
+ disposers.push(onChannelJoined(realtimeRouter()), onChannelLeft(realtimeRouter()), onChannelMemberAdded(realtimeRouter()), onChannelMemberRemoved(realtimeRouter()), onChannelMemberBanned(realtimeRouter()), onChannelMemberUnbanned(realtimeRouter()));
26544
+ onFetch();
26545
+ return () => {
26546
+ log(`liveChannelMembers(tmpid: ${timestamp}) > dispose`);
26547
+ disposers.forEach(fn => fn());
26548
+ };
26549
+ };
26550
+
26551
+ function convertFromRaw(_a) {
26552
+ 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"]);
26553
+ return Object.assign(Object.assign({}, rest), { channelId: channelPublicId, creatorId: creatorPublicId, displayName: name, lastActivity: lastMessageTimestamp, latestMessageId: lastMessageId, messageCount: childCount, subChannelId: messageFeedId });
26554
+ }
26555
+ const prepareSubChannelPayload = (payload) => {
26556
+ return Object.assign(Object.assign({}, payload), { messageFeeds: payload.messageFeeds.map(convertFromRaw) });
26557
+ };
26558
+ function convertQueryParams(_a) {
26559
+ var { excludeDefaultSubChannel } = _a, rest = __rest(_a, ["excludeDefaultSubChannel"]);
26560
+ const out = Object.assign({}, rest);
26561
+ if (excludeDefaultSubChannel !== undefined) {
26562
+ out.excludeDefaultMessageFeed = excludeDefaultSubChannel;
26563
+ }
26564
+ return out;
26565
+ }
26566
+
26567
+ /**
26568
+ * ```js
26569
+ * import { querySubChannels } from '@amityco/ts-sdk'
26570
+ * const subChannels = await querySubChannels({ channelId: 'channelId' })
26571
+ * ```
26572
+ *
26573
+ * Queries a paginable list of {@link Amity.SubChannel} objects
26574
+ *
26575
+ * @param query The query parameters
26576
+ * @returns A page of {@link Amity.SubChannel} objects
26577
+ *
26578
+ * @category Channel API
26579
+ * @async
26580
+ */
26581
+ const querySubChannels = async (query) => {
26582
+ const client = getActiveClient();
26583
+ client.log('channel/querySubChannels', query);
26584
+ const _a = convertQueryParams(query), { page = { limit: 10 }, channelId } = _a, params = __rest(_a, ["page", "channelId"]);
26585
+ const response = await client.http.get(`/api/v5/message-feeds/channel/${channelId}`, {
26586
+ params: Object.assign(Object.assign({}, params), { options: {
26587
+ token: toToken(page, 'skiplimit'),
26588
+ } }),
26589
+ });
26590
+ const _b = response.data, { paging } = _b, payload = __rest(_b, ["paging"]);
26591
+ const data = prepareSubChannelPayload(payload);
26592
+ const subChannels = data.messageFeeds;
26593
+ const cachedAt = client.cache && Date.now();
26594
+ if (client.cache) {
26595
+ ingestInCache(data, { cachedAt });
26596
+ const cacheKey = [
26597
+ 'subChannel',
26598
+ 'query',
26599
+ Object.assign(Object.assign({ channelId }, params), { options: Object.assign({}, page) }),
26600
+ ];
26601
+ pushToCache(cacheKey, { subChannels: subChannels.map(getResolver('subChannel')), paging });
26602
+ }
26603
+ fireEvent('local.message-feed.fetched', data);
26604
+ const nextPage = toPage(paging.next);
26605
+ const prevPage = toPage(paging.previous);
26606
+ return { data: subChannels, cachedAt, prevPage, nextPage };
26607
+ };
26608
+ /**
26609
+ * ```js
26610
+ * import { querySubChannels } from '@amityco/ts-sdk'
26611
+ * const subChannels = querySubChannels.locally({ channelId: 'channelId' })
26612
+ * ```
26613
+ *
26614
+ * Queries a paginable list of {@link Amity.SubChannel} objects from cache
26615
+ *
26616
+ * @param query The query parameters
26617
+ * @returns sub channels
26618
+ *
26619
+ * @category Channel API
26620
+ */
26621
+ querySubChannels.locally = (query) => {
26622
+ var _a, _b, _c;
26623
+ const client = getActiveClient();
26624
+ client.log('channel/querySubChannels.locally', query);
26625
+ // @ts-ignore
26626
+ const _d = (_a = convertQueryParams(query)) !== null && _a !== void 0 ? _a : {}, { page = { limit: 10 }, channelId } = _d, params = __rest(_d, ["page", "channelId"]);
26627
+ const cacheKey = [
26628
+ 'subChannel',
26629
+ 'query',
26630
+ Object.assign(Object.assign({ channelId }, params), { options: Object.assign({}, page) }),
26631
+ ];
26632
+ const { data, cachedAt } = (_b = pullFromCache(cacheKey)) !== null && _b !== void 0 ? _b : {};
26633
+ if (!(data === null || data === void 0 ? void 0 : data.subChannels.length))
26634
+ return;
26635
+ const subChannels = data.subChannels
26636
+ .map(ck => pullFromCache(['subChannel', 'get', ck]))
26637
+ .filter(Boolean)
26638
+ .map(({ data }) => data);
26639
+ const prevPage = toPage(data === null || data === void 0 ? void 0 : data.paging.previous);
26640
+ const nextPage = toPage(data === null || data === void 0 ? void 0 : data.paging.next);
26641
+ return subChannels.length === ((_c = data === null || data === void 0 ? void 0 : data.subChannels) === null || _c === void 0 ? void 0 : _c.length)
26642
+ ? { data: subChannels, cachedAt, prevPage, nextPage }
26643
+ : undefined;
26644
+ };
26645
+
26646
+ /**
26647
+ * ```js
26648
+ * import { getSubChannels } from '@amityco/ts-sdk'
26649
+ * const subChannels = await getSubChannels(['foo', 'bar'])
26650
+ * ```
26651
+ *
26652
+ * Fetches a collection of {@link Amity.SubChannel} objects
26653
+ *
26654
+ * @param subChannelIds the IDs of the {@link Amity.SubChannel} to fetch
26655
+ * @returns the associated collection of {@link Amity.SubChannel} objects
26656
+ *
26657
+ * @category Channel API
26658
+ * @async
26659
+ */
26660
+ const getSubChannels = async (subChannelIds) => {
26661
+ const client = getActiveClient();
26662
+ client.log('channel/getSubChannels', subChannelIds);
26663
+ const response = await client.http.get('/api/v5/message-feeds/list', {
26664
+ params: { messageFeedIds: subChannelIds.map(encodeURIComponent) },
26665
+ });
26666
+ const data = prepareSubChannelPayload(response.data);
26667
+ const cachedAt = client.cache && Date.now();
26668
+ if (client.cache)
26669
+ ingestInCache(data, { cachedAt });
26670
+ fireEvent('local.message-feed.fetched', data);
26671
+ return {
26672
+ data: data.messageFeeds,
26673
+ cachedAt,
26674
+ };
26675
+ };
26676
+ /**
26677
+ * ```js
26678
+ * import { getSubChannels } from '@amityco/ts-sdk'
26679
+ * const subChannels = getSubChannels.locally(['foo', 'bar']) ?? []
26680
+ * ```
26681
+ *
26682
+ * Fetches a collection of {@link Amity.SubChannel} objects from cache
26683
+ *
26684
+ * @param subChannelIds the IDs of the {@link Amity.SubChannel} to fetch
26685
+ * @returns the associated collection of {@link Amity.SubChannel} objects
26686
+ *
26687
+ * @category Channel API
26688
+ */
26689
+ getSubChannels.locally = (subChannelIds) => {
26690
+ var _a;
26691
+ const client = getActiveClient();
26692
+ client.log('channel/getSubChannels.locally', subChannelIds);
26693
+ if (!client.cache)
26694
+ return;
26695
+ const cached = subChannelIds
26696
+ .map(channelId => pullFromCache(['subChannel', 'get', channelId]))
26697
+ .filter(Boolean);
26698
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) < subChannelIds.length)
26699
+ return;
26700
+ const subChannels = cached.map(({ data }) => data);
26701
+ const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
26702
+ return {
26703
+ data: subChannels,
26704
+ cachedAt: oldest.cachedAt,
26705
+ };
26706
+ };
26707
+
26708
+ /**
26709
+ * ```js
26710
+ * import { getSubChannel } from '@amityco/ts-sdk'
26711
+ * const subChannel = await getSubChannel('foobar')
26712
+ * ```
26713
+ *
26714
+ * Fetches a {@link Amity.SubChannel} object
26715
+ *
26716
+ * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
26717
+ * @returns the associated {@link Amity.SubChannel} object
26718
+ *
26719
+ * @category Channel API
26720
+ * @async
26721
+ */
26722
+ const getSubChannel = async (subChannelId) => {
26723
+ const client = getActiveClient();
26724
+ client.log('channel/getSubChannel', subChannelId);
26725
+ isInTombstone('subChannel', subChannelId);
26726
+ try {
26727
+ const response = await client.http.get(`/api/v5/message-feeds/${encodeURIComponent(subChannelId)}`);
26728
+ const data = prepareSubChannelPayload(response.data);
26729
+ const cachedAt = client.cache && Date.now();
26730
+ if (client.cache)
26731
+ ingestInCache(data, { cachedAt });
26732
+ fireEvent('local.message-feed.fetched', data);
26733
+ return {
26734
+ data: data.messageFeeds[0],
26735
+ cachedAt,
26736
+ };
26737
+ }
26738
+ catch (error) {
26739
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
26740
+ pushToTombstone('subChannel', subChannelId);
26741
+ }
26742
+ throw error;
26743
+ }
26744
+ };
26745
+ /**
26746
+ * ```js
26747
+ * import { getSubChannel } from '@amityco/ts-sdk'
26748
+ * const subChannel = getSubChannel.locally('foobar')
26749
+ * ```
26750
+ *
26751
+ * Fetches a {@link Amity.SubChannel} object from cache
26752
+ *
26753
+ * @param subChannelId the ID of the {@link Amity.SubChannel} to fetch
26754
+ * @returns the associated {@link Amity.SubChannel} object
26755
+ *
26756
+ * @category Channel API
26757
+ */
26758
+ getSubChannel.locally = (subChannelId) => {
26759
+ const client = getActiveClient();
26760
+ client.log('channel/getSubChannel.locally', subChannelId);
26761
+ if (!client.cache)
26762
+ return;
26763
+ const cached = pullFromCache(['subChannel', 'get', subChannelId]);
26764
+ if (!cached)
26765
+ return;
26766
+ return {
26767
+ data: cached.data,
26768
+ cachedAt: cached.cachedAt,
26769
+ };
26770
+ };
26771
+
26772
+ /**
26773
+ * ```js
26774
+ * import { createSubChannel } from '@amityco/ts-sdk'
26775
+ * const created = await createSubChannel({ channelId: 'foobar', name: 'foobar' })
26776
+ * ```
26777
+ *
26778
+ * Creates an {@link Amity.SubChannel}
26779
+ *
26780
+ * @param bundle The data necessary to create a new {@link Amity.SubChannel}
26781
+ * @returns The newly created {@link Amity.SubChannel}
26782
+ *
26783
+ * @category Channel API
26784
+ * @async
26785
+ */
26786
+ const createSubChannel = async (bundle) => {
26787
+ const client = getActiveClient();
26788
+ client.log('user/createSubChannel', bundle);
26789
+ const response = await client.http.post('/api/v5/message-feeds', {
26790
+ channelId: bundle.channelId,
26791
+ name: bundle.displayName,
26792
+ });
26793
+ const data = prepareSubChannelPayload(response.data);
26794
+ const cachedAt = client.cache && Date.now();
26795
+ if (client.cache)
26796
+ ingestInCache(data, { cachedAt });
26797
+ fireEvent('message-feed.created', response.data);
26798
+ return {
26799
+ data: data.messageFeeds[0],
26800
+ cachedAt,
26801
+ };
26802
+ };
26803
+
26804
+ /**
26805
+ * ```js
26806
+ * import { updateSubChannel } from '@amityco/ts-sdk'
26807
+ * const updated = await updateSubChannel(subChannelId, { name: 'foobar' })
26808
+ * ```
26809
+ *
26810
+ * Updates an {@link Amity.SubChannel}
26811
+ *
26812
+ * @param subChannelId The ID of the {@link Amity.SubChannel} to edit
26813
+ * @param patch The patch data to apply
26814
+ * @returns the updated {@link Amity.SubChannel} object
26815
+ *
26816
+ * @category Channel API
26817
+ * @async
26818
+ */
26819
+ const updateSubChannel = async (subChannelId, patch) => {
26820
+ const client = getActiveClient();
26821
+ client.log('channel/updateSubChannel', subChannelId, patch);
26822
+ const response = await client.http.put(`/api/v5/message-feeds/${encodeURIComponent(subChannelId)}`, { name: patch.displayName });
26823
+ const data = prepareSubChannelPayload(response.data);
26824
+ const cachedAt = client.cache && Date.now();
26825
+ if (client.cache)
26826
+ ingestInCache(data, { cachedAt });
26827
+ fireEvent('message-feed.updated', response.data);
26828
+ return {
26829
+ data: data.messageFeeds[0],
26830
+ cachedAt,
26831
+ };
26832
+ };
26833
+
26834
+ /**
26835
+ * ```js
26836
+ * import { deleteSubChannel } from '@amityco/ts-sdk'
26837
+ * const success = await deleteSubChannel('foobar')
26838
+ * ```
26839
+ *
26840
+ * Deletes a {@link Amity.SubChannel}
25385
26841
  *
25386
- * @param params for querying channel users
25387
- * @param callback the function to call when new data are available
25388
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channel users
26842
+ * @param subChannelId The {@link Amity.SubChannel} ID to delete
26843
+ * @return A success boolean if the {@link Amity.SubChannel} was deleted
25389
26844
  *
25390
- * @category Channel Live Collection
26845
+ * @category Channel API
26846
+ * @async
25391
26847
  */
25392
- const liveChannelMembers = (params, callback, config) => {
25393
- const { log, cache } = getActiveClient();
25394
- if (!cache) {
25395
- console.log(ENABLE_CACHE_MESSAGE);
26848
+ const deleteSubChannel = async (subChannelId, permanent = false) => {
26849
+ const client = getActiveClient();
26850
+ client.log('channel/deleteSubChannel', subChannelId);
26851
+ const subChannel = await getSubChannel(subChannelId);
26852
+ await client.http.delete(`/api/v5/message-feeds/${encodeURIComponent(subChannelId)}`, { params: { permanent } });
26853
+ const deleted = Object.assign(Object.assign({}, subChannel.data), { isDeleted: true, updatedAt: getFutureDate(subChannel.data.updatedAt) });
26854
+ if (permanent) {
26855
+ setTimeout(() => {
26856
+ pushToTombstone('subChannel', subChannelId);
26857
+ }, 0);
25396
26858
  }
25397
- const timestamp = Date.now();
25398
- log(`liveChannelMembers(tmpid: ${timestamp}) > listen`);
25399
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
25400
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
25401
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
25402
- const disposers = [];
25403
- const cacheKey = ['channelUsers', 'collection', { channelId: params.channelId }];
25404
- const responder = (data) => {
25405
- var _a, _b;
25406
- let channelMembers = (_a = data.data
25407
- .map(id => pullFromCache(['channelUsers', 'get', id]))
25408
- .filter(Boolean)
25409
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
25410
- channelMembers = filterByPropEquality(channelMembers, 'roles', params.roles);
25411
- if (params.memberships) {
25412
- /*
25413
- * even though membership includes muted as a possible value
25414
- * when querying the server.
25415
- * Muted is specified under seperarte property namely isMuted
25416
- * Hence why I've seperately checked for it's equality
25417
- */
25418
- if (params.memberships.some(m => ['member', 'banned'].includes(m))) {
25419
- channelMembers = filterByPropInclusion(channelMembers, 'membership', params.memberships);
25420
- }
25421
- if (params.memberships.includes('muted')) {
25422
- channelMembers = filterByPropEquality(channelMembers, 'isMuted', true);
25423
- }
25424
- }
25425
- if (params.search) {
25426
- const containsMatcher = new RegExp(params.search);
25427
- channelMembers = channelMembers.filter(m => m.userId.match(containsMatcher));
25428
- }
25429
- // sort, 'lastCreated' is the default sort order
25430
- const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
25431
- channelMembers = channelMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
25432
- callback({
25433
- onNextPage: onFetch,
25434
- data: channelMembers,
25435
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
25436
- loading: data.loading,
25437
- error: data.error,
25438
- });
25439
- };
25440
- const realtimeRouter = (channelMember, action) => {
25441
- var _a;
25442
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25443
- if (!collection)
25444
- return;
25445
- const channelMemberCacheId = getResolver('channelUsers')({
25446
- channelId: params.channelId,
25447
- userId: channelMember.userId,
25448
- });
25449
- if (action === 'onMemberAdded') {
25450
- collection.data = [...new Set([channelMemberCacheId, ...collection.data])];
25451
- }
25452
- if (action === 'onMemberRemoved') {
25453
- collection.data = collection.data.filter(m => m !== channelMemberCacheId);
25454
- }
25455
- pushToCache(cacheKey, collection);
25456
- responder(collection);
25457
- };
25458
- const onFetch = () => {
25459
- var _a, _b, _c;
25460
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25461
- const channelMembers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
25462
- if (channelMembers.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
25463
- return;
25464
- 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 } }));
25465
- runQuery(query, ({ data: result, error, loading, nextPage: page }) => {
25466
- const data = {
25467
- loading,
25468
- error,
25469
- params: { page },
25470
- data: channelMembers,
25471
- };
25472
- if (result) {
25473
- data.data = [...new Set([...channelMembers, ...result.map(getResolver('channelUsers'))])];
25474
- }
25475
- pushToCache(cacheKey, data);
25476
- responder(data);
25477
- }, queryOptions(policy));
25478
- };
25479
- disposers.push(onChannelMemberAdded((_, member) => realtimeRouter(member, 'onMemberAdded')), onChannelMemberRemoved((_, member) => realtimeRouter(member, 'onMemberRemoved')), onChannelMemberBanned((_, member) => realtimeRouter(member, 'onChannelMemberBanned')), onChannelMemberUnbanned((_, member) => realtimeRouter(member, 'onChannelMemberUnbanned')));
25480
- onFetch();
25481
- return () => {
25482
- log(`liveChannelMembers(tmpid: ${timestamp}) > dispose`);
25483
- disposers.forEach(fn => fn());
25484
- };
26859
+ else {
26860
+ upsertInCache(['subChannel', 'get', subChannelId], deleted);
26861
+ }
26862
+ fireEvent('local.message-feed.deleted', { messageFeeds: [deleted] });
26863
+ return deleted;
25485
26864
  };
25486
26865
 
25487
26866
  /**
25488
26867
  * ```js
25489
- * import { onMessageCreated } from '@amityco/ts-sdk'
25490
- * const dispose = onMessageCreated(message => {
26868
+ * import { onChannelSubCreated } from '@amityco/ts-sdk'
26869
+ * const dispose = onSubChannelCreated(subChannel => {
25491
26870
  * // ...
25492
26871
  * })
25493
26872
  * ```
25494
26873
  *
25495
- * Fired when an {@link Amity.Message} has been created
26874
+ * Fired when any {@link Amity.SubChannel} have been created
25496
26875
  *
25497
26876
  * @param callback The function to call when the event was fired
25498
26877
  * @returns an {@link Amity.Unsubscriber} function to stop listening
25499
26878
  *
25500
- * @category Message Events
26879
+ * @category Channel Events
25501
26880
  */
25502
- const onMessageCreated = (callback) => {
26881
+ const onSubChannelCreated = (callback) => {
25503
26882
  const client = getActiveClient();
25504
- const filter = (payload) => {
26883
+ const filter = (rawPayload) => {
26884
+ const payload = prepareSubChannelPayload(rawPayload);
25505
26885
  ingestInCache(payload);
25506
- callback(payload.messages[0]);
26886
+ callback(payload.messageFeeds[0]);
25507
26887
  };
25508
- return createEventSubscriber(client, 'message/onMessageCreated', 'v3.message.didCreate', filter);
26888
+ return createEventSubscriber(client, 'onSubChannelCreated', 'message-feed.created', filter);
25509
26889
  };
25510
26890
 
25511
26891
  /**
25512
26892
  * ```js
25513
- * import { onMessageUpdated } from '@amityco/ts-sdk'
25514
- * const dispose = onMessageUpdated(message => {
26893
+ * import { onSubChannelUpdated } from '@amityco/ts-sdk'
26894
+ * const dispose = onSubChannelUpdated(subChannel => {
25515
26895
  * // ...
25516
26896
  * })
25517
26897
  * ```
25518
26898
  *
25519
- * Fired when an {@link Amity.Message} has been updated
26899
+ * Fired when any {@link Amity.SubChannel} have been updated
25520
26900
  *
25521
26901
  * @param callback The function to call when the event was fired
25522
26902
  * @returns an {@link Amity.Unsubscriber} function to stop listening
25523
26903
  *
25524
- * @category Message Events
26904
+ * @category Channel Events
25525
26905
  */
25526
- const onMessageUpdated = (callback) => {
26906
+ const onSubChannelUpdated = (callback) => {
25527
26907
  const client = getActiveClient();
25528
- const filter = (payload) => {
26908
+ const filter = (rawPayload) => {
26909
+ const payload = prepareSubChannelPayload(rawPayload);
25529
26910
  ingestInCache(payload);
25530
- const message = payload.messages[0];
25531
- // if payload does not have myReactions
25532
- if (!(message === null || message === void 0 ? void 0 : message.myReactions)) {
25533
- prepareMessagePayloadForCache(message);
25534
- }
25535
- callback(message);
26911
+ callback(payload.messageFeeds[0]);
25536
26912
  };
25537
- return createEventSubscriber(client, 'message/onMessageUpdated', 'v3.message.didUpdate', filter);
26913
+ return createEventSubscriber(client, 'onSubChannelUpdated', 'message-feed.updated', filter);
25538
26914
  };
25539
26915
 
25540
26916
  /**
25541
26917
  * ```js
25542
- * import { onMessageDeleted } from '@amityco/ts-sdk'
25543
- * const dispose = onMessageDeleted(message => {
26918
+ * import { onSubChannelDeleted } from '@amityco/ts-sdk'
26919
+ * const dispose = onSubChannelDeleted(subChannel => {
25544
26920
  * // ...
25545
26921
  * })
25546
26922
  * ```
25547
26923
  *
25548
- * Fired when an {@link Amity.Message} was deleted
26924
+ * Fired when any {@link Amity.SubChannel} have been deleted
25549
26925
  *
25550
26926
  * @param callback The function to call when the event was fired
25551
26927
  * @returns an {@link Amity.Unsubscriber} function to stop listening
25552
26928
  *
25553
- * @category Message Events
26929
+ * @category Channel Events
25554
26930
  */
25555
- const onMessageDeleted = (callback) => {
26931
+ const onSubChannelDeleted = (callback) => {
25556
26932
  const client = getActiveClient();
25557
- const filter = (payload) => {
26933
+ const filter = (rawPayload) => {
26934
+ const payload = prepareSubChannelPayload(rawPayload);
25558
26935
  ingestInCache(payload);
25559
- callback(payload.messages[0]);
26936
+ callback(payload.messageFeeds[0]);
26937
+ };
26938
+ const disposers = [
26939
+ createEventSubscriber(client, 'onSubChannelDeleted', 'message-feed.deleted', filter),
26940
+ createEventSubscriber(client, 'local.message-feed.deleted', 'local.message-feed.deleted', payload => callback(payload.messageFeeds[0])),
26941
+ ];
26942
+ return () => {
26943
+ disposers.forEach(fn => fn());
26944
+ };
26945
+ };
26946
+
26947
+ /** @hidden */
26948
+ const onSubChannelFetched = (callback) => {
26949
+ return createEventSubscriber(getActiveClient(), 'onSubChannelFetched', 'local.message-feed.fetched', payload => callback(payload.messageFeeds[0]));
26950
+ };
26951
+
26952
+ /**
26953
+ * ```js
26954
+ * import { liveSubChannel } from '@amityco/ts-sdk';
26955
+ *
26956
+ * let subChannel;
26957
+ *
26958
+ * const unsubscribe = liveSubChannel(subChannelId, response => {
26959
+ * subChannel = response.data;
26960
+ * });
26961
+ * ```
26962
+ *
26963
+ * Observe all mutation on a given {@link Amity.SubChannel}
26964
+ *
26965
+ * @param subChannelId the ID of the message to observe
26966
+ * @param callback the function to call when new data are available
26967
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the sub channel
26968
+ *
26969
+ * @category SubChannel Live Object
26970
+ */
26971
+ const liveSubChannel = (subChannelId, callback) => {
26972
+ const { log, cache } = getActiveClient();
26973
+ const timestamp = Date.now();
26974
+ log(`liveSubChannel(tmpid: ${timestamp}) > listen`);
26975
+ if (!cache) {
26976
+ console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
26977
+ }
26978
+ let subChannel;
26979
+ const disposers = [];
26980
+ const dispatcher = (data) => {
26981
+ subChannel = data.data;
26982
+ callback(data);
26983
+ };
26984
+ const realtimeRouter = (eventSubChannel) => {
26985
+ if (subChannelId !== eventSubChannel.subChannelId) {
26986
+ return;
26987
+ }
26988
+ if (subChannel && !hasUpdates(subChannel, eventSubChannel)) {
26989
+ return;
26990
+ }
26991
+ dispatcher({ loading: false, data: eventSubChannel, origin: 'event' });
26992
+ };
26993
+ const onFetch = () => {
26994
+ const query = createQuery(getSubChannel, subChannelId);
26995
+ runQuery(query, ({ error, data, loading, origin }) => {
26996
+ dispatcher({ error, data, loading, origin });
26997
+ if (error) {
26998
+ disposers.forEach(fn => fn());
26999
+ }
27000
+ });
27001
+ };
27002
+ disposers.push(onSubChannelFetched(realtimeRouter), onSubChannelUpdated(realtimeRouter), onSubChannelDeleted(realtimeRouter));
27003
+ onFetch();
27004
+ return () => {
27005
+ log(`liveSubChannel(tmpid: ${timestamp}) > dispose`);
27006
+ disposers.forEach(fn => fn());
27007
+ };
27008
+ };
27009
+
27010
+ /**
27011
+ * ```js
27012
+ * import { liveSubChannels } from '@amityco/ts-sdk';
27013
+ *
27014
+ * let subChannels = [];
27015
+ *
27016
+ * const unsubscribe = liveSubChannels({ channelId }, response => {
27017
+ * merge(subChannels, response.data);
27018
+ * });
27019
+ * ```
27020
+ *
27021
+ * Observe all mutations on a list of {@link Amity.SubChannel}s
27022
+ *
27023
+ * @param params for querying sub channels
27024
+ * @param callback the function to call when new data are available
27025
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the sub channels
27026
+ *
27027
+ * @category SubChannel Live Collection
27028
+ */
27029
+ const liveSubChannels = (params, callback, config) => {
27030
+ const { log, cache } = getActiveClient();
27031
+ const timestamp = Date.now();
27032
+ log(`liveSubChannels(tmpid: ${timestamp}) > listen`);
27033
+ if (!cache) {
27034
+ console.log(ENABLE_CACHE_MESSAGE);
27035
+ }
27036
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = params, queryParams = __rest(params, ["limit"]);
27037
+ const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
27038
+ let snapshot;
27039
+ const disposers = [];
27040
+ const responder = (data) => {
27041
+ var _a;
27042
+ let subChannels = data.data;
27043
+ if (params.isDeleted !== undefined) {
27044
+ subChannels = filterByPropEquality(subChannels, 'isDeleted', params.isDeleted);
27045
+ }
27046
+ subChannels.sort(sortByLastActivity);
27047
+ callback({
27048
+ onNextPage: onFetch,
27049
+ data: subChannels,
27050
+ hasNextPage: !!((_a = data.params) === null || _a === void 0 ? void 0 : _a.page),
27051
+ loading: data.loading,
27052
+ error: data.error,
27053
+ });
27054
+ };
27055
+ const realtimeRouter = (action) => (subChannel) => {
27056
+ if (params.channelId !== subChannel.channelId ||
27057
+ !snapshot ||
27058
+ !isCollectionOutdated(snapshot.data, subChannel, action)) {
27059
+ return;
27060
+ }
27061
+ if (action === 'onCreate') {
27062
+ snapshot.data = [subChannel, ...snapshot.data];
27063
+ }
27064
+ else {
27065
+ snapshot.data = snapshot.data.map(x => x.subChannelId === subChannel.subChannelId ? subChannel : x);
27066
+ }
27067
+ responder(snapshot);
27068
+ };
27069
+ const onFetch = () => {
27070
+ var _a;
27071
+ const subChannels = snapshot ? snapshot.data : [];
27072
+ if (subChannels.length > 0 && !(snapshot === null || snapshot === void 0 ? void 0 : snapshot.params.page)) {
27073
+ return;
27074
+ }
27075
+ 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 } }));
27076
+ runQuery(query, ({ data: result, error, loading, nextPage: page }) => {
27077
+ snapshot = {
27078
+ loading,
27079
+ error,
27080
+ params: { page },
27081
+ data: result ? merge(subChannels, result) : subChannels,
27082
+ };
27083
+ responder(snapshot);
27084
+ }, queryOptions(policy));
27085
+ };
27086
+ disposers.push(onSubChannelCreated(realtimeRouter('onCreate')), onSubChannelDeleted(realtimeRouter('onDelete')), onSubChannelFetched(realtimeRouter('onFetch')), onSubChannelUpdated(realtimeRouter('onUpdate')));
27087
+ onFetch();
27088
+ return () => {
27089
+ log(`liveSubChannels(tmpid: ${timestamp}) > dispose`);
27090
+ disposers.forEach(fn => fn());
25560
27091
  };
25561
- return createEventSubscriber(client, 'message/onMessageDeleted', 'v3.message.didDelete', filter);
25562
27092
  };
25563
27093
 
25564
27094
  /**
@@ -25582,46 +27112,50 @@ const onMessageFetched = (callback) => {
25582
27112
  ingestInCache(payload);
25583
27113
  callback(payload.messages[0]);
25584
27114
  };
25585
- return createEventSubscriber(client, 'message/onMessageFetched', 'v3.message.didFetch', filter);
27115
+ return createEventSubscriber(client, 'message/onMessageFetched', 'local.message.fetched', filter);
25586
27116
  };
25587
27117
 
25588
27118
  /**
25589
27119
  * ```js
25590
- * import { liveMessage } from '@amityco/ts-sdk'
27120
+ * import { liveMessage } from '@amityco/ts-sdk';
25591
27121
  *
25592
- * let messages = []
25593
- * const unsub = liveMessage(messageId, response => merge(messages, response.data))
27122
+ * let message;
27123
+ *
27124
+ * const unsubscribe = liveMessage(messageId, response => {
27125
+ * message = response.data;
27126
+ * });
25594
27127
  * ```
25595
27128
  *
25596
27129
  * Observe all mutation on a given {@link Amity.Message}
25597
27130
  *
25598
27131
  * @param messageId the ID of the message to observe
25599
27132
  * @param callback the function to call when new data are available
25600
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
27133
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the message
25601
27134
  *
25602
27135
  * @category Message Live Object
25603
27136
  */
25604
27137
  const liveMessage = (messageId, callback) => {
25605
27138
  const { log, cache } = getActiveClient();
25606
- let message;
25607
- let isUnsyncedObject = false;
27139
+ const timestamp = Date.now();
27140
+ log(`liveMessage(tmpid: ${timestamp}) > listen`);
25608
27141
  if (!cache) {
25609
27142
  console.log(LIVE_OBJECT_ENABLE_CACHE_MESSAGE);
25610
27143
  }
25611
- const timestamp = Date.now();
25612
- log(`liveMessage(tmpid: ${timestamp}) > listen`);
27144
+ let message;
27145
+ let isUnsyncedObject = false;
25613
27146
  const disposers = [];
25614
27147
  const dispatcher = (data) => {
25615
- var _a;
25616
- // we check updatedAt to see if the current snapshot is new so
25617
- // we won't send old data back, only fresh new data
25618
- 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')
25619
- return;
25620
- callback(data);
25621
27148
  message = data.data;
27149
+ callback(data);
25622
27150
  };
25623
- const realtimeRouter = (message, action) => {
25624
- dispatcher({ loading: false, data: message, origin: 'event' });
27151
+ const realtimeRouter = (eventMessage) => {
27152
+ if (messageId !== eventMessage.messageId) {
27153
+ return;
27154
+ }
27155
+ if (message && !hasUpdates(message, eventMessage)) {
27156
+ return;
27157
+ }
27158
+ dispatcher({ loading: false, data: eventMessage, origin: 'event' });
25625
27159
  };
25626
27160
  const onFetch = () => {
25627
27161
  const query = createQuery(getMessage, messageId, true);
@@ -25640,12 +27174,11 @@ const liveMessage = (messageId, callback) => {
25640
27174
  dispatcher({ loading, data, origin, error });
25641
27175
  }
25642
27176
  if (error) {
25643
- // Terminate observe functionality on error
25644
27177
  disposers.forEach(fn => fn());
25645
27178
  }
25646
27179
  });
25647
27180
  };
25648
- disposers.push(onMessageFetched(message => realtimeRouter(message)), onMessageUpdated(message => realtimeRouter(message)), onMessageDeleted(message => realtimeRouter(message)));
27181
+ disposers.push(onMessageFetched(realtimeRouter), onMessageUpdated(realtimeRouter), onMessageDeleted(realtimeRouter), onMessageFlagged(realtimeRouter), onMessageUnflagged(realtimeRouter), onMessageFlagCleared(realtimeRouter), onMessageReactionAdded(realtimeRouter), onMessageReactionRemoved(realtimeRouter));
25649
27182
  onFetch();
25650
27183
  return () => {
25651
27184
  log(`liveMessage(tmpid: ${timestamp}) > dispose`);
@@ -25655,17 +27188,18 @@ const liveMessage = (messageId, callback) => {
25655
27188
 
25656
27189
  /**
25657
27190
  * ```js
25658
- * import { liveMessages } from '@amityco/ts-sdk'
27191
+ * import { liveMessages } from '@amityco/ts-sdk';
25659
27192
  *
25660
- * let messages = []
25661
- * const unsub = liveMessages({
25662
- * channelId: Amity.Channel['channelId'];
25663
- * }, response => merge(messages, response.data))
27193
+ * let messages = [];
27194
+ *
27195
+ * const unsubscribe = liveMessages({
27196
+ * subChannelId: Amity.SubChannel['subChannelId'];
27197
+ * }, response => merge(messages, response.data));
25664
27198
  * ```
25665
27199
  *
25666
27200
  * Observe all mutations on a list of {@link Amity.Message} for a given target object
25667
27201
  *
25668
- * @param params for querying memssages from a channel
27202
+ * @param params for querying messages from a sub channel
25669
27203
  * @param callback the function to call when new data are available
25670
27204
  * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
25671
27205
  *
@@ -25682,7 +27216,7 @@ const liveMessages = (params, callback, config) => {
25682
27216
  const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
25683
27217
  const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
25684
27218
  const disposers = [];
25685
- const cacheKey = ['message', 'collection', { channelId: params.channelId }];
27219
+ const cacheKey = ['message', 'collection', { subChannelId: params.subChannelId }];
25686
27220
  const responder = (data) => {
25687
27221
  var _a, _b;
25688
27222
  let messages = (_a = data.data
@@ -25702,10 +27236,10 @@ const liveMessages = (params, callback, config) => {
25702
27236
  error: data.error,
25703
27237
  });
25704
27238
  };
25705
- const realtimeRouter = (message, action) => {
27239
+ const realtimeRouter = (action) => (message) => {
25706
27240
  var _a;
25707
27241
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25708
- if (params.channelId !== message.channelId || !collection)
27242
+ if (params.subChannelId !== message.subChannelId || !collection)
25709
27243
  return;
25710
27244
  if (action === 'onCreate') {
25711
27245
  collection.data = [...new Set([message.messageId, ...collection.data])];
@@ -25737,7 +27271,7 @@ const liveMessages = (params, callback, config) => {
25737
27271
  responder(data);
25738
27272
  }, queryOptions(policy));
25739
27273
  };
25740
- disposers.push(onMessageFetched(message => realtimeRouter(message, 'onFetch')), onMessageCreated(message => realtimeRouter(message, 'onCreate')), onMessageDeleted(message => realtimeRouter(message, 'onDelete')), onMessageUpdated(message => realtimeRouter(message, 'onUpdate')));
27274
+ 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')));
25741
27275
  onFetch();
25742
27276
  return () => {
25743
27277
  log(`liveMessages(tmpid: ${timestamp}) > dispose`);
@@ -25750,6 +27284,7 @@ const liveMessages = (params, callback, config) => {
25750
27284
  * import { observeMessage } from '@amityco/ts-sdk'
25751
27285
  *
25752
27286
  * let message = {}
27287
+ *
25753
27288
  * const unsub = observeMessage(messageId, updated => message = updated)
25754
27289
  * ```
25755
27290
  *
@@ -25796,25 +27331,26 @@ const observeMessage = (messageId, callback, policy = 'cache_then_server') => {
25796
27331
  * import { observeMessages } from '@amityco/ts-sdk'
25797
27332
  *
25798
27333
  * let messages = []
25799
- * const unsub = observeMessages(channelId, message => merge(messages, message))
27334
+ *
27335
+ * const unsubscribe = observeMessages(channelId, message => merge(messages, message))
25800
27336
  * ```
25801
27337
  *
25802
- * Observe all mutations on a list of {@link Amity.Message} for a given {@link Amity.Channel} object
27338
+ * Observe all mutations on a list of {@link Amity.Message} for a given {@link Amity.SubChannel} object
25803
27339
  *
25804
- * @param channelId the ID of the channel where to observe the messages
27340
+ * @param subChannelId the ID of the channel where to observe the messages
25805
27341
  * @param callback the function to call when new data are available
25806
27342
  * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
25807
27343
  *
25808
27344
  * @category Message Observer
25809
27345
  */
25810
- const observeMessages = (channelId, callback) => {
27346
+ const observeMessages = (subChannelId, callback) => {
25811
27347
  const { log } = getActiveClient();
25812
27348
  const timestamp = Date.now();
25813
27349
  log(`observeMessages(tmpid: ${timestamp}) > listen`);
25814
27350
  const disposers = [];
25815
27351
  const router = (message, action) => {
25816
27352
  var _a, _b, _c;
25817
- if (((_a = message.data) === null || _a === void 0 ? void 0 : _a.channelId) !== channelId)
27353
+ if (((_a = message.data) === null || _a === void 0 ? void 0 : _a.subChannelId) !== subChannelId)
25818
27354
  return;
25819
27355
  if (callback instanceof Function)
25820
27356
  return callback(message);
@@ -25877,22 +27413,23 @@ function getEventRelatedMember(event, payload) {
25877
27413
  const createCommunityMemberEventSubscriber = (event, callback) => {
25878
27414
  const client = getActiveClient();
25879
27415
  const filter = (payload) => {
25880
- const unpackedPayload = unpackCommunityPayload(payload);
27416
+ const communityPayload = unpackCommunityPayload(payload);
27417
+ const preparedPayload = prepareMembershipPayload(communityPayload, 'communityUsers');
25881
27418
  if (!client.cache) {
25882
27419
  // TODO: here we are missing specific properties here!
25883
- callback(unpackedPayload.communities[0], getEventRelatedMember(event, unpackedPayload));
27420
+ callback(preparedPayload.communities[0], getEventRelatedMember(event, preparedPayload));
25884
27421
  }
25885
27422
  else {
25886
- ingestInCache(unpackedPayload);
27423
+ ingestInCache(preparedPayload);
25887
27424
  const community = pullFromCache([
25888
27425
  'community',
25889
27426
  'get',
25890
- unpackedPayload.communities[0].communityId,
27427
+ preparedPayload.communities[0].communityId,
25891
27428
  ]);
25892
27429
  const member = pullFromCache([
25893
27430
  'communityUsers',
25894
27431
  'get',
25895
- getResolver('communityUsers')(getEventRelatedMember(event, unpackedPayload)),
27432
+ getResolver('communityUsers')(getEventRelatedMember(event, preparedPayload)),
25896
27433
  ]);
25897
27434
  callback(community.data, member.data);
25898
27435
  }
@@ -26931,7 +28468,7 @@ const liveFollowers = (params, callback, config) => {
26931
28468
  error: data.error,
26932
28469
  });
26933
28470
  };
26934
- const realtimeRouter = (followStatus, action) => {
28471
+ const realtimeRouter = (action) => (followStatus) => {
26935
28472
  var _a;
26936
28473
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26937
28474
  if (params.userId !== followStatus.to || !collection)
@@ -26966,7 +28503,7 @@ const liveFollowers = (params, callback, config) => {
26966
28503
  responder(data);
26967
28504
  }, queryOptions(policy));
26968
28505
  };
26969
- 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')));
28506
+ disposers.push(onFollowerRequested(realtimeRouter('onRequested')), onFollowRequestAccepted(realtimeRouter('onAccepted')), onFollowRequestDeclined(realtimeRouter('onDeclined')), onFollowRequestCanceled(realtimeRouter('onCanceled')), onUserFollowed(realtimeRouter('onFollowed')), onUserUnfollowed(realtimeRouter('onUnfollowed')), onFollowerDeleted(realtimeRouter('onDeleted')));
26970
28507
  onFetch();
26971
28508
  return () => {
26972
28509
  log(`liveFollowers(tmpid: ${timestamp}) > dispose`);
@@ -27021,7 +28558,7 @@ const liveFollowings = (params, callback, config) => {
27021
28558
  error: data.error,
27022
28559
  });
27023
28560
  };
27024
- const realtimeRouter = (followStatus, action) => {
28561
+ const realtimeRouter = (action) => (followStatus) => {
27025
28562
  var _a;
27026
28563
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27027
28564
  if (params.userId !== followStatus.from || !collection)
@@ -27056,7 +28593,7 @@ const liveFollowings = (params, callback, config) => {
27056
28593
  responder(data);
27057
28594
  }, queryOptions(policy));
27058
28595
  };
27059
- 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')));
28596
+ disposers.push(onFollowerRequested(realtimeRouter('onRequested')), onFollowRequestAccepted(realtimeRouter('onAccepted')), onFollowRequestDeclined(realtimeRouter('onDeclined')), onFollowRequestCanceled(realtimeRouter('onCanceled')), onUserFollowed(realtimeRouter('onFollowed')), onUserUnfollowed(realtimeRouter('onUnfollowed')), onFollowerDeleted(realtimeRouter('onDeleted')));
27060
28597
  onFetch();
27061
28598
  return () => {
27062
28599
  log(`liveFollowings(tmpid: ${timestamp}) > dispose`);
@@ -27194,6 +28731,9 @@ const livePosts = (params, callback, config) => {
27194
28731
  posts = filterByPropEquality(posts, 'isDeleted', params.isDeleted);
27195
28732
  const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
27196
28733
  posts = posts.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
28734
+ if (params.tags) {
28735
+ 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); }); });
28736
+ }
27197
28737
  callback({
27198
28738
  onNextPage: onFetch,
27199
28739
  data: posts,
@@ -27202,17 +28742,32 @@ const livePosts = (params, callback, config) => {
27202
28742
  error: data.error,
27203
28743
  });
27204
28744
  };
27205
- const realtimeRouter = (post, action) => {
28745
+ const realtimeRouter = (action) => (post) => {
27206
28746
  var _a;
27207
28747
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27208
28748
  if (params.targetId !== post.targetId || params.targetType !== post.targetType || !collection)
27209
28749
  return;
27210
- if (action === 'onCreate') {
28750
+ if (['onCreate', 'onApproved'].includes(action)) {
27211
28751
  collection.data = [...new Set([post.postId, ...collection.data])];
27212
28752
  }
27213
28753
  else if (['onDelete', 'onDeclined'].includes(action)) {
27214
28754
  collection.data = collection.data.filter(p => p !== post.postId);
28755
+ /*
28756
+ * if isDeleted is true, collection should add deleted items to the
28757
+ * begining of the collection
28758
+ */
28759
+ if (params.isDeleted)
28760
+ collection.data.unshift(post.postId);
27215
28761
  }
28762
+ /*
28763
+ * FIX-ME
28764
+ * This is a shortcoming as the feed object is not saved to the cache.
28765
+ * The responder should pull the feed from cache once available and should
28766
+ * match the collection to feedType param
28767
+ * https://ekoapp.atlassian.net/browse/ASC-9382
28768
+ */
28769
+ if (params.feedType === 'reviewing' && action === 'onApproved')
28770
+ collection.data = collection.data.filter(p => p !== post.postId);
27216
28771
  pushToCache(cacheKey, collection);
27217
28772
  responder(collection);
27218
28773
  };
@@ -27237,7 +28792,7 @@ const livePosts = (params, callback, config) => {
27237
28792
  responder(data);
27238
28793
  }, queryOptions(policy));
27239
28794
  };
27240
- 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')));
28795
+ 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')));
27241
28796
  onFetch();
27242
28797
  return () => {
27243
28798
  log(`livePosts(tmpid: ${timestamp}) > dispose`);
@@ -27379,7 +28934,7 @@ const liveComments = (params, callback, config) => {
27379
28934
  error: data.error,
27380
28935
  });
27381
28936
  };
27382
- const realtimeRouter = (comment, action) => {
28937
+ const realtimeRouter = (action) => (comment) => {
27383
28938
  var _a;
27384
28939
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
27385
28940
  if (params.referenceId !== comment.referenceId ||
@@ -27418,7 +28973,7 @@ const liveComments = (params, callback, config) => {
27418
28973
  responder(data);
27419
28974
  }, queryOptions(policy));
27420
28975
  };
27421
- 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')));
28976
+ disposers.push(onCommentCreated(realtimeRouter('onCreate')), onCommentUpdated(realtimeRouter('onUpdate')), onCommentDeleted(realtimeRouter('onDelete')), onCommentFlagged(realtimeRouter('onFlagged')), onCommentUnflagged(realtimeRouter('onUnflagged')), onCommentReactionAdded(realtimeRouter('onReactionAdded')), onCommentReactionRemoved(realtimeRouter('onReactionRemoved')));
27422
28977
  onFetch();
27423
28978
  return () => {
27424
28979
  log(`liveComments(tmpid: ${timestamp}) > dispose`);
@@ -28004,9 +29559,9 @@ const onStreamRecorded = (callback) => {
28004
29559
  */
28005
29560
  const createUserToken = async (apiKey, apiRegion, params) => {
28006
29561
  const deviceId = getDeviceId();
28007
- const deviceInfo = await getDeviceInfo();
29562
+ const deviceInfo = getDeviceInfo();
28008
29563
  const http = createHttpTransport(computeUrl('http', apiRegion));
28009
- const { data } = await http.post('/api/v3/sessions', Object.assign(Object.assign({}, params), { deviceId, deviceInfo: Object.assign(Object.assign({}, deviceInfo), { model: 'token management API on TS-SDK' }) }), { headers: { 'X-API-Key': apiKey } });
29564
+ const { data } = await http.post('/api/v4/sessions', Object.assign(Object.assign({}, params), { deviceId, deviceInfo: Object.assign(Object.assign({}, deviceInfo), { model: 'token management API on TS-SDK' }) }), { headers: { 'X-API-Key': apiKey } });
28010
29565
  return { accessToken: data.accessToken };
28011
29566
  };
28012
29567
 
@@ -28045,6 +29600,7 @@ exports.createPost = createPost;
28045
29600
  exports.createQuery = createQuery;
28046
29601
  exports.createReport = createReport;
28047
29602
  exports.createStream = createStream;
29603
+ exports.createSubChannel = createSubChannel;
28048
29604
  exports.createUserToken = createUserToken;
28049
29605
  exports.createVideo = createVideo;
28050
29606
  exports.declineFollower = declineFollower;
@@ -28058,6 +29614,7 @@ exports.deletePoll = deletePoll;
28058
29614
  exports.deletePost = deletePost;
28059
29615
  exports.deleteReport = deleteReport;
28060
29616
  exports.deleteStream = deleteStream;
29617
+ exports.deleteSubChannel = deleteSubChannel;
28061
29618
  exports.disableCache = disableCache;
28062
29619
  exports.disconnectClient = disconnectClient;
28063
29620
  exports.disposeStream = disposeStream;
@@ -28071,6 +29628,7 @@ exports.follow = follow;
28071
29628
  exports.getActiveClient = getActiveClient;
28072
29629
  exports.getCategory = getCategory;
28073
29630
  exports.getChannel = getChannel;
29631
+ exports.getChannelTopic = getChannelTopic;
28074
29632
  exports.getChannels = getChannels;
28075
29633
  exports.getComment = getComment;
28076
29634
  exports.getCommentTopic = getCommentTopic;
@@ -28082,6 +29640,7 @@ exports.getFeedSettings = getFeedSettings;
28082
29640
  exports.getFile = getFile;
28083
29641
  exports.getFollowInfo = getFollowInfo;
28084
29642
  exports.getMessage = getMessage;
29643
+ exports.getMessageTopic = getMessageTopic;
28085
29644
  exports.getMessages = getMessages;
28086
29645
  exports.getMyFollowersTopic = getMyFollowersTopic;
28087
29646
  exports.getMyFollowingsTopic = getMyFollowingsTopic;
@@ -28092,7 +29651,13 @@ exports.getPostTopic = getPostTopic;
28092
29651
  exports.getPosts = getPosts;
28093
29652
  exports.getRecommendedCommunities = getRecommendedCommunities;
28094
29653
  exports.getRole = getRole;
29654
+ exports.getSmartFeedChannelTopic = getSmartFeedChannelTopic;
29655
+ exports.getSmartFeedMessageTopic = getSmartFeedMessageTopic;
29656
+ exports.getSmartFeedSubChannelTopic = getSmartFeedSubChannelTopic;
28095
29657
  exports.getStream = getStream;
29658
+ exports.getSubChannel = getSubChannel;
29659
+ exports.getSubChannelTopic = getSubChannelTopic;
29660
+ exports.getSubChannels = getSubChannels;
28096
29661
  exports.getTopTrendingCommunities = getTopTrendingCommunities;
28097
29662
  exports.getUser = getUser;
28098
29663
  exports.getUserTopic = getUserTopic;
@@ -28113,6 +29678,7 @@ exports.joinChannel = joinChannel;
28113
29678
  exports.joinCommunity = joinCommunity;
28114
29679
  exports.leaveChannel = leaveChannel;
28115
29680
  exports.leaveCommunity = leaveCommunity;
29681
+ exports.liveChannel = liveChannel;
28116
29682
  exports.liveChannelMembers = liveChannelMembers;
28117
29683
  exports.liveChannels = liveChannels;
28118
29684
  exports.liveComments = liveComments;
@@ -28122,6 +29688,8 @@ exports.liveMessage = liveMessage;
28122
29688
  exports.liveMessages = liveMessages;
28123
29689
  exports.livePosts = livePosts;
28124
29690
  exports.liveReactions = liveReactions;
29691
+ exports.liveSubChannel = liveSubChannel;
29692
+ exports.liveSubChannels = liveSubChannels;
28125
29693
  exports.liveUser = liveUser;
28126
29694
  exports.mergeInCache = mergeInCache;
28127
29695
  exports.observeChannel = observeChannel;
@@ -28147,6 +29715,7 @@ exports.onChannelMemberAdded = onChannelMemberAdded;
28147
29715
  exports.onChannelMemberBanned = onChannelMemberBanned;
28148
29716
  exports.onChannelMemberRemoved = onChannelMemberRemoved;
28149
29717
  exports.onChannelMemberUnbanned = onChannelMemberUnbanned;
29718
+ exports.onChannelMuted = onChannelMuted;
28150
29719
  exports.onChannelUpdated = onChannelUpdated;
28151
29720
  exports.onClientBanned = onClientBanned;
28152
29721
  exports.onClientDisconnected = onClientDisconnected;
@@ -28175,7 +29744,11 @@ exports.onFollowerDeleted = onFollowerDeleted;
28175
29744
  exports.onFollowerRequested = onFollowerRequested;
28176
29745
  exports.onMessageCreated = onMessageCreated;
28177
29746
  exports.onMessageDeleted = onMessageDeleted;
28178
- exports.onMessageFetched = onMessageFetched;
29747
+ exports.onMessageFlagCleared = onMessageFlagCleared;
29748
+ exports.onMessageFlagged = onMessageFlagged;
29749
+ exports.onMessageReactionAdded = onMessageReactionAdded;
29750
+ exports.onMessageReactionRemoved = onMessageReactionRemoved;
29751
+ exports.onMessageUnflagged = onMessageUnflagged;
28179
29752
  exports.onMessageUpdated = onMessageUpdated;
28180
29753
  exports.onPollDeleted = onPollDeleted;
28181
29754
  exports.onPollUpdated = onPollUpdated;
@@ -28192,11 +29765,14 @@ exports.onReactionAdded = onReactionAdded;
28192
29765
  exports.onReactionRemoved = onReactionRemoved;
28193
29766
  exports.onReactorAdded = onReactorAdded;
28194
29767
  exports.onReactorRemoved = onReactorRemoved;
29768
+ exports.onSessionStateChange = onSessionStateChange;
28195
29769
  exports.onStreamRecorded = onStreamRecorded;
28196
29770
  exports.onStreamStarted = onStreamStarted;
28197
29771
  exports.onStreamStopped = onStreamStopped;
29772
+ exports.onSubChannelCreated = onSubChannelCreated;
29773
+ exports.onSubChannelDeleted = onSubChannelDeleted;
29774
+ exports.onSubChannelUpdated = onSubChannelUpdated;
28198
29775
  exports.onUserDeleted = onUserDeleted;
28199
- exports.onUserFetched = onUserFetched;
28200
29776
  exports.onUserFlagCleared = onUserFlagCleared;
28201
29777
  exports.onUserFlagged = onUserFlagged;
28202
29778
  exports.onUserFollowed = onUserFollowed;
@@ -28221,12 +29797,14 @@ exports.queryPosts = queryPosts;
28221
29797
  exports.queryReactions = queryReactions;
28222
29798
  exports.queryRoles = queryRoles;
28223
29799
  exports.queryStreams = queryStreams;
29800
+ exports.querySubChannels = querySubChannels;
28224
29801
  exports.queryUsers = queryUsers;
28225
29802
  exports.removeChannelMembers = removeChannelMembers;
28226
29803
  exports.removeChannelMembersRole = removeChannelMembersRole;
28227
29804
  exports.removeCommunityMembers = removeCommunityMembers;
28228
29805
  exports.removeCommunityMembersRoles = removeCommunityMembersRoles;
28229
29806
  exports.removeReaction = removeReaction;
29807
+ exports.renewal = renewal;
28230
29808
  exports.restoreCache = restoreCache;
28231
29809
  exports.runQuery = runQuery;
28232
29810
  exports.sortByChannelSegment = sortByChannelSegment;
@@ -28235,6 +29813,8 @@ exports.sortByFirstCreated = sortByFirstCreated;
28235
29813
  exports.sortByLastActivity = sortByLastActivity;
28236
29814
  exports.sortByLastCreated = sortByLastCreated;
28237
29815
  exports.sortBySegmentNumber = sortBySegmentNumber;
29816
+ exports.startReading = startReading;
29817
+ exports.stopReading = stopReading;
28238
29818
  exports.subscribeTopic = subscribeTopic;
28239
29819
  exports.toPage = toPage;
28240
29820
  exports.toPageRaw = toPageRaw;
@@ -28247,6 +29827,7 @@ exports.updateCommunity = updateCommunity;
28247
29827
  exports.updateMessage = updateMessage;
28248
29828
  exports.updatePost = updatePost;
28249
29829
  exports.updateStream = updateStream;
29830
+ exports.updateSubChannel = updateSubChannel;
28250
29831
  exports.updateUser = updateUser;
28251
29832
  exports.upsertInCache = upsertInCache;
28252
29833
  exports.votePoll = votePoll;