@amityco/ts-sdk 0.0.1-02f0fa3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (611) hide show
  1. package/LICENSE +390 -0
  2. package/README.md +137 -0
  3. package/dist/@types/core/cache.d.ts +21 -0
  4. package/dist/@types/core/cache.d.ts.map +1 -0
  5. package/dist/@types/core/errors.d.ts +32 -0
  6. package/dist/@types/core/errors.d.ts.map +1 -0
  7. package/dist/@types/core/events.d.ts +46 -0
  8. package/dist/@types/core/events.d.ts.map +1 -0
  9. package/dist/@types/core/model.d.ts +41 -0
  10. package/dist/@types/core/model.d.ts.map +1 -0
  11. package/dist/@types/core/payload.d.ts +88 -0
  12. package/dist/@types/core/payload.d.ts.map +1 -0
  13. package/dist/@types/core/permissions.d.ts +71 -0
  14. package/dist/@types/core/permissions.d.ts.map +1 -0
  15. package/dist/@types/core/query.d.ts +72 -0
  16. package/dist/@types/core/query.d.ts.map +1 -0
  17. package/dist/@types/core/store.d.ts +46 -0
  18. package/dist/@types/core/store.d.ts.map +1 -0
  19. package/dist/@types/core/transport.d.ts +27 -0
  20. package/dist/@types/core/transport.d.ts.map +1 -0
  21. package/dist/@types/domains/category.d.ts +11 -0
  22. package/dist/@types/domains/category.d.ts.map +1 -0
  23. package/dist/@types/domains/channel.d.ts +26 -0
  24. package/dist/@types/domains/channel.d.ts.map +1 -0
  25. package/dist/@types/domains/client.d.ts +31 -0
  26. package/dist/@types/domains/client.d.ts.map +1 -0
  27. package/dist/@types/domains/comment.d.ts +17 -0
  28. package/dist/@types/domains/comment.d.ts.map +1 -0
  29. package/dist/@types/domains/community.d.ts +24 -0
  30. package/dist/@types/domains/community.d.ts.map +1 -0
  31. package/dist/@types/domains/content.d.ts +26 -0
  32. package/dist/@types/domains/content.d.ts.map +1 -0
  33. package/dist/@types/domains/feed.d.ts +14 -0
  34. package/dist/@types/domains/feed.d.ts.map +1 -0
  35. package/dist/@types/domains/file.d.ts +29 -0
  36. package/dist/@types/domains/file.d.ts.map +1 -0
  37. package/dist/@types/domains/group.d.ts +26 -0
  38. package/dist/@types/domains/group.d.ts.map +1 -0
  39. package/dist/@types/domains/message.d.ts +16 -0
  40. package/dist/@types/domains/message.d.ts.map +1 -0
  41. package/dist/@types/domains/partials.d.ts +42 -0
  42. package/dist/@types/domains/partials.d.ts.map +1 -0
  43. package/dist/@types/domains/post.d.ts +22 -0
  44. package/dist/@types/domains/post.d.ts.map +1 -0
  45. package/dist/@types/domains/reaction.d.ts +24 -0
  46. package/dist/@types/domains/reaction.d.ts.map +1 -0
  47. package/dist/@types/domains/stream.d.ts +47 -0
  48. package/dist/@types/domains/stream.d.ts.map +1 -0
  49. package/dist/@types/domains/user.d.ts +12 -0
  50. package/dist/@types/domains/user.d.ts.map +1 -0
  51. package/dist/@types/global.d.ts +13 -0
  52. package/dist/@types/global.d.ts.map +1 -0
  53. package/dist/@types/index.d.ts +23 -0
  54. package/dist/@types/index.d.ts.map +1 -0
  55. package/dist/category/api/getCategory.d.ts +16 -0
  56. package/dist/category/api/getCategory.d.ts.map +1 -0
  57. package/dist/category/api/index.d.ts +3 -0
  58. package/dist/category/api/index.d.ts.map +1 -0
  59. package/dist/category/api/queryCategories.d.ts +23 -0
  60. package/dist/category/api/queryCategories.d.ts.map +1 -0
  61. package/dist/channel/api/addChannelMembers.d.ts +17 -0
  62. package/dist/channel/api/addChannelMembers.d.ts.map +1 -0
  63. package/dist/channel/api/addChannelMembersRole.d.ts +18 -0
  64. package/dist/channel/api/addChannelMembersRole.d.ts.map +1 -0
  65. package/dist/channel/api/createChannel.d.ts +19 -0
  66. package/dist/channel/api/createChannel.d.ts.map +1 -0
  67. package/dist/channel/api/deleteChannel.d.ts +16 -0
  68. package/dist/channel/api/deleteChannel.d.ts.map +1 -0
  69. package/dist/channel/api/getChannel.d.ts +32 -0
  70. package/dist/channel/api/getChannel.d.ts.map +1 -0
  71. package/dist/channel/api/getChannels.d.ts +32 -0
  72. package/dist/channel/api/getChannels.d.ts.map +1 -0
  73. package/dist/channel/api/index.d.ts +14 -0
  74. package/dist/channel/api/index.d.ts.map +1 -0
  75. package/dist/channel/api/joinChannel.d.ts +16 -0
  76. package/dist/channel/api/joinChannel.d.ts.map +1 -0
  77. package/dist/channel/api/leaveChannel.d.ts +16 -0
  78. package/dist/channel/api/leaveChannel.d.ts.map +1 -0
  79. package/dist/channel/api/queryChannelMembers.d.ts +42 -0
  80. package/dist/channel/api/queryChannelMembers.d.ts.map +1 -0
  81. package/dist/channel/api/queryChannels.d.ts +43 -0
  82. package/dist/channel/api/queryChannels.d.ts.map +1 -0
  83. package/dist/channel/api/removeChannelMembers.d.ts +17 -0
  84. package/dist/channel/api/removeChannelMembers.d.ts.map +1 -0
  85. package/dist/channel/api/removeChannelMembersRole.d.ts +18 -0
  86. package/dist/channel/api/removeChannelMembersRole.d.ts.map +1 -0
  87. package/dist/channel/api/updateChannel.d.ts +17 -0
  88. package/dist/channel/api/updateChannel.d.ts.map +1 -0
  89. package/dist/channel/events/index.d.ts +7 -0
  90. package/dist/channel/events/index.d.ts.map +1 -0
  91. package/dist/channel/events/onChannelCreated.d.ts +17 -0
  92. package/dist/channel/events/onChannelCreated.d.ts.map +1 -0
  93. package/dist/channel/events/onChannelDeleted.d.ts +17 -0
  94. package/dist/channel/events/onChannelDeleted.d.ts.map +1 -0
  95. package/dist/channel/events/onChannelJoined.d.ts +17 -0
  96. package/dist/channel/events/onChannelJoined.d.ts.map +1 -0
  97. package/dist/channel/events/onChannelLeft.d.ts +17 -0
  98. package/dist/channel/events/onChannelLeft.d.ts.map +1 -0
  99. package/dist/channel/events/onChannelUpdated.d.ts +17 -0
  100. package/dist/channel/events/onChannelUpdated.d.ts.map +1 -0
  101. package/dist/channel/events/onMemberAdded.d.ts +17 -0
  102. package/dist/channel/events/onMemberAdded.d.ts.map +1 -0
  103. package/dist/channel/events/onMemberRemoved.d.ts +17 -0
  104. package/dist/channel/events/onMemberRemoved.d.ts.map +1 -0
  105. package/dist/channel/observers/index.d.ts +2 -0
  106. package/dist/channel/observers/index.d.ts.map +1 -0
  107. package/dist/channel/observers/observeChannel.d.ts +20 -0
  108. package/dist/channel/observers/observeChannel.d.ts.map +1 -0
  109. package/dist/client/api/activeClient.d.ts +17 -0
  110. package/dist/client/api/activeClient.d.ts.map +1 -0
  111. package/dist/client/api/clearCache.d.ts +15 -0
  112. package/dist/client/api/clearCache.d.ts.map +1 -0
  113. package/dist/client/api/connectClient.d.ts +26 -0
  114. package/dist/client/api/connectClient.d.ts.map +1 -0
  115. package/dist/client/api/createClient.d.ts +17 -0
  116. package/dist/client/api/createClient.d.ts.map +1 -0
  117. package/dist/client/api/disconnectClient.d.ts +16 -0
  118. package/dist/client/api/disconnectClient.d.ts.map +1 -0
  119. package/dist/client/api/enableCache.d.ts +15 -0
  120. package/dist/client/api/enableCache.d.ts.map +1 -0
  121. package/dist/client/api/getToken.d.ts +19 -0
  122. package/dist/client/api/getToken.d.ts.map +1 -0
  123. package/dist/client/api/index.d.ts +8 -0
  124. package/dist/client/api/index.d.ts.map +1 -0
  125. package/dist/client/api/isConnected.d.ts +14 -0
  126. package/dist/client/api/isConnected.d.ts.map +1 -0
  127. package/dist/client/events/index.d.ts +2 -0
  128. package/dist/client/events/index.d.ts.map +1 -0
  129. package/dist/client/events/onClientDisconnected.d.ts +17 -0
  130. package/dist/client/events/onClientDisconnected.d.ts.map +1 -0
  131. package/dist/comment/api/createComment.d.ts +16 -0
  132. package/dist/comment/api/createComment.d.ts.map +1 -0
  133. package/dist/comment/api/deleteComment.d.ts +16 -0
  134. package/dist/comment/api/deleteComment.d.ts.map +1 -0
  135. package/dist/comment/api/getComment.d.ts +32 -0
  136. package/dist/comment/api/getComment.d.ts.map +1 -0
  137. package/dist/comment/api/getComments.d.ts +32 -0
  138. package/dist/comment/api/getComments.d.ts.map +1 -0
  139. package/dist/comment/api/index.d.ts +7 -0
  140. package/dist/comment/api/index.d.ts.map +1 -0
  141. package/dist/comment/api/queryComments.d.ts +53 -0
  142. package/dist/comment/api/queryComments.d.ts.map +1 -0
  143. package/dist/comment/api/updateComment.d.ts +19 -0
  144. package/dist/comment/api/updateComment.d.ts.map +1 -0
  145. package/dist/comment/events/index.d.ts +4 -0
  146. package/dist/comment/events/index.d.ts.map +1 -0
  147. package/dist/comment/events/onCommentCreated.d.ts +17 -0
  148. package/dist/comment/events/onCommentCreated.d.ts.map +1 -0
  149. package/dist/comment/events/onCommentDeleted.d.ts +17 -0
  150. package/dist/comment/events/onCommentDeleted.d.ts.map +1 -0
  151. package/dist/comment/events/onCommentUpdated.d.ts +17 -0
  152. package/dist/comment/events/onCommentUpdated.d.ts.map +1 -0
  153. package/dist/comment/observers/index.d.ts +3 -0
  154. package/dist/comment/observers/index.d.ts.map +1 -0
  155. package/dist/comment/observers/observeComment.d.ts +20 -0
  156. package/dist/comment/observers/observeComment.d.ts.map +1 -0
  157. package/dist/comment/observers/observeComments.d.ts +22 -0
  158. package/dist/comment/observers/observeComments.d.ts.map +1 -0
  159. package/dist/community/api/addCommunityMembers.d.ts +17 -0
  160. package/dist/community/api/addCommunityMembers.d.ts.map +1 -0
  161. package/dist/community/api/addCommunityMembersRole.d.ts +18 -0
  162. package/dist/community/api/addCommunityMembersRole.d.ts.map +1 -0
  163. package/dist/community/api/createCommunity.d.ts +20 -0
  164. package/dist/community/api/createCommunity.d.ts.map +1 -0
  165. package/dist/community/api/deleteCommunity.d.ts +16 -0
  166. package/dist/community/api/deleteCommunity.d.ts.map +1 -0
  167. package/dist/community/api/getCommunities.d.ts +32 -0
  168. package/dist/community/api/getCommunities.d.ts.map +1 -0
  169. package/dist/community/api/getCommunity.d.ts +32 -0
  170. package/dist/community/api/getCommunity.d.ts.map +1 -0
  171. package/dist/community/api/index.d.ts +14 -0
  172. package/dist/community/api/index.d.ts.map +1 -0
  173. package/dist/community/api/joinCommunity.d.ts +16 -0
  174. package/dist/community/api/joinCommunity.d.ts.map +1 -0
  175. package/dist/community/api/leaveCommunity.d.ts +16 -0
  176. package/dist/community/api/leaveCommunity.d.ts.map +1 -0
  177. package/dist/community/api/queryCommunities.d.ts +46 -0
  178. package/dist/community/api/queryCommunities.d.ts.map +1 -0
  179. package/dist/community/api/queryCommunityMembers.d.ts +42 -0
  180. package/dist/community/api/queryCommunityMembers.d.ts.map +1 -0
  181. package/dist/community/api/removeCommunityMembers.d.ts +17 -0
  182. package/dist/community/api/removeCommunityMembers.d.ts.map +1 -0
  183. package/dist/community/api/removeCommunityMembersRole.d.ts +18 -0
  184. package/dist/community/api/removeCommunityMembersRole.d.ts.map +1 -0
  185. package/dist/community/api/updateCommunity.d.ts +17 -0
  186. package/dist/community/api/updateCommunity.d.ts.map +1 -0
  187. package/dist/community/events/index.d.ts +6 -0
  188. package/dist/community/events/index.d.ts.map +1 -0
  189. package/dist/community/events/onCommunityCreated.d.ts +17 -0
  190. package/dist/community/events/onCommunityCreated.d.ts.map +1 -0
  191. package/dist/community/events/onCommunityDeleted.d.ts +17 -0
  192. package/dist/community/events/onCommunityDeleted.d.ts.map +1 -0
  193. package/dist/community/events/onCommunityJoined.d.ts +17 -0
  194. package/dist/community/events/onCommunityJoined.d.ts.map +1 -0
  195. package/dist/community/events/onCommunityLeft.d.ts +17 -0
  196. package/dist/community/events/onCommunityLeft.d.ts.map +1 -0
  197. package/dist/community/events/onCommunityUpdated.d.ts +17 -0
  198. package/dist/community/events/onCommunityUpdated.d.ts.map +1 -0
  199. package/dist/community/observers/index.d.ts +2 -0
  200. package/dist/community/observers/index.d.ts.map +1 -0
  201. package/dist/community/observers/observeCommunity.d.ts +20 -0
  202. package/dist/community/observers/observeCommunity.d.ts.map +1 -0
  203. package/dist/core/cache/drop.d.ts +11 -0
  204. package/dist/core/cache/drop.d.ts.map +1 -0
  205. package/dist/core/cache/index.d.ts +19 -0
  206. package/dist/core/cache/index.d.ts.map +1 -0
  207. package/dist/core/cache/ingest.d.ts +10 -0
  208. package/dist/core/cache/ingest.d.ts.map +1 -0
  209. package/dist/core/cache/merge.d.ts +10 -0
  210. package/dist/core/cache/merge.d.ts.map +1 -0
  211. package/dist/core/cache/mutate.d.ts +10 -0
  212. package/dist/core/cache/mutate.d.ts.map +1 -0
  213. package/dist/core/cache/pull.d.ts +11 -0
  214. package/dist/core/cache/pull.d.ts.map +1 -0
  215. package/dist/core/cache/push.d.ts +10 -0
  216. package/dist/core/cache/push.d.ts.map +1 -0
  217. package/dist/core/cache/sync.d.ts +10 -0
  218. package/dist/core/cache/sync.d.ts.map +1 -0
  219. package/dist/core/debug.d.ts +15 -0
  220. package/dist/core/debug.d.ts.map +1 -0
  221. package/dist/core/device.d.ts +7 -0
  222. package/dist/core/device.d.ts.map +1 -0
  223. package/dist/core/errors.d.ts +59 -0
  224. package/dist/core/errors.d.ts.map +1 -0
  225. package/dist/core/events.d.ts +33 -0
  226. package/dist/core/events.d.ts.map +1 -0
  227. package/dist/core/model/idResolvers.d.ts +20 -0
  228. package/dist/core/model/idResolvers.d.ts.map +1 -0
  229. package/dist/core/model/identifyModel.d.ts +8 -0
  230. package/dist/core/model/identifyModel.d.ts.map +1 -0
  231. package/dist/core/model/index.d.ts +4 -0
  232. package/dist/core/model/index.d.ts.map +1 -0
  233. package/dist/core/model/toRecord.d.ts +10 -0
  234. package/dist/core/model/toRecord.d.ts.map +1 -0
  235. package/dist/core/query/decorate.d.ts +23 -0
  236. package/dist/core/query/decorate.d.ts.map +1 -0
  237. package/dist/core/query/filtering.d.ts +12 -0
  238. package/dist/core/query/filtering.d.ts.map +1 -0
  239. package/dist/core/query/index.d.ts +6 -0
  240. package/dist/core/query/index.d.ts.map +1 -0
  241. package/dist/core/query/paging.d.ts +58 -0
  242. package/dist/core/query/paging.d.ts.map +1 -0
  243. package/dist/core/query/query.d.ts +121 -0
  244. package/dist/core/query/query.d.ts.map +1 -0
  245. package/dist/core/query/sorting.d.ts +39 -0
  246. package/dist/core/query/sorting.d.ts.map +1 -0
  247. package/dist/core/stores/index.d.ts +3 -0
  248. package/dist/core/stores/index.d.ts.map +1 -0
  249. package/dist/core/stores/memory.d.ts +30 -0
  250. package/dist/core/stores/memory.d.ts.map +1 -0
  251. package/dist/core/stores/persistent.d.ts +13 -0
  252. package/dist/core/stores/persistent.d.ts.map +1 -0
  253. package/dist/core/transports.d.ts +49 -0
  254. package/dist/core/transports.d.ts.map +1 -0
  255. package/dist/core/uuid.d.ts +2 -0
  256. package/dist/core/uuid.d.ts.map +1 -0
  257. package/dist/feed/api/index.d.ts +2 -0
  258. package/dist/feed/api/index.d.ts.map +1 -0
  259. package/dist/feed/api/queryGlobalFeed.d.ts +23 -0
  260. package/dist/feed/api/queryGlobalFeed.d.ts.map +1 -0
  261. package/dist/file/api/createFile.d.ts +16 -0
  262. package/dist/file/api/createFile.d.ts.map +1 -0
  263. package/dist/file/api/deleteFile.d.ts +16 -0
  264. package/dist/file/api/deleteFile.d.ts.map +1 -0
  265. package/dist/file/api/fileUrlWithSize.d.ts +9 -0
  266. package/dist/file/api/fileUrlWithSize.d.ts.map +1 -0
  267. package/dist/file/api/getFile.d.ts +32 -0
  268. package/dist/file/api/getFile.d.ts.map +1 -0
  269. package/dist/file/api/index.d.ts +5 -0
  270. package/dist/file/api/index.d.ts.map +1 -0
  271. package/dist/file/observers/index.d.ts +2 -0
  272. package/dist/file/observers/index.d.ts.map +1 -0
  273. package/dist/file/observers/observeFile.d.ts +20 -0
  274. package/dist/file/observers/observeFile.d.ts.map +1 -0
  275. package/dist/index.cjs.js +4884 -0
  276. package/dist/index.d.ts +32 -0
  277. package/dist/index.d.ts.map +1 -0
  278. package/dist/index.esm.js +4734 -0
  279. package/dist/index.umd.js +4880 -0
  280. package/dist/message/api/createMessage.d.ts +38 -0
  281. package/dist/message/api/createMessage.d.ts.map +1 -0
  282. package/dist/message/api/deleteMessage.d.ts +32 -0
  283. package/dist/message/api/deleteMessage.d.ts.map +1 -0
  284. package/dist/message/api/getMessage.d.ts +32 -0
  285. package/dist/message/api/getMessage.d.ts.map +1 -0
  286. package/dist/message/api/getMessages.d.ts +32 -0
  287. package/dist/message/api/getMessages.d.ts.map +1 -0
  288. package/dist/message/api/index.d.ts +7 -0
  289. package/dist/message/api/index.d.ts.map +1 -0
  290. package/dist/message/api/queryMessages.d.ts +55 -0
  291. package/dist/message/api/queryMessages.d.ts.map +1 -0
  292. package/dist/message/api/updateMessage.d.ts +38 -0
  293. package/dist/message/api/updateMessage.d.ts.map +1 -0
  294. package/dist/message/events/index.d.ts +4 -0
  295. package/dist/message/events/index.d.ts.map +1 -0
  296. package/dist/message/events/onMessageCreated.d.ts +17 -0
  297. package/dist/message/events/onMessageCreated.d.ts.map +1 -0
  298. package/dist/message/events/onMessageDeleted.d.ts +17 -0
  299. package/dist/message/events/onMessageDeleted.d.ts.map +1 -0
  300. package/dist/message/events/onMessageUpdated.d.ts +17 -0
  301. package/dist/message/events/onMessageUpdated.d.ts.map +1 -0
  302. package/dist/message/observers/index.d.ts +3 -0
  303. package/dist/message/observers/index.d.ts.map +1 -0
  304. package/dist/message/observers/observeMessage.d.ts +22 -0
  305. package/dist/message/observers/observeMessage.d.ts.map +1 -0
  306. package/dist/message/observers/observeMessages.d.ts +19 -0
  307. package/dist/message/observers/observeMessages.d.ts.map +1 -0
  308. package/dist/post/api/createPost.d.ts +21 -0
  309. package/dist/post/api/createPost.d.ts.map +1 -0
  310. package/dist/post/api/deletePost.d.ts +16 -0
  311. package/dist/post/api/deletePost.d.ts.map +1 -0
  312. package/dist/post/api/getPost.d.ts +32 -0
  313. package/dist/post/api/getPost.d.ts.map +1 -0
  314. package/dist/post/api/getPosts.d.ts +32 -0
  315. package/dist/post/api/getPosts.d.ts.map +1 -0
  316. package/dist/post/api/index.d.ts +7 -0
  317. package/dist/post/api/index.d.ts.map +1 -0
  318. package/dist/post/api/queryPosts.d.ts +45 -0
  319. package/dist/post/api/queryPosts.d.ts.map +1 -0
  320. package/dist/post/api/updatePost.d.ts +19 -0
  321. package/dist/post/api/updatePost.d.ts.map +1 -0
  322. package/dist/post/events/index.d.ts +4 -0
  323. package/dist/post/events/index.d.ts.map +1 -0
  324. package/dist/post/events/onPostCreated.d.ts +17 -0
  325. package/dist/post/events/onPostCreated.d.ts.map +1 -0
  326. package/dist/post/events/onPostDeleted.d.ts +17 -0
  327. package/dist/post/events/onPostDeleted.d.ts.map +1 -0
  328. package/dist/post/events/onPostUpdated.d.ts +17 -0
  329. package/dist/post/events/onPostUpdated.d.ts.map +1 -0
  330. package/dist/post/observers/index.d.ts +3 -0
  331. package/dist/post/observers/index.d.ts.map +1 -0
  332. package/dist/post/observers/observePost.d.ts +20 -0
  333. package/dist/post/observers/observePost.d.ts.map +1 -0
  334. package/dist/post/observers/observePosts.d.ts +25 -0
  335. package/dist/post/observers/observePosts.d.ts.map +1 -0
  336. package/dist/reaction/api/addReaction.d.ts +36 -0
  337. package/dist/reaction/api/addReaction.d.ts.map +1 -0
  338. package/dist/reaction/api/index.d.ts +3 -0
  339. package/dist/reaction/api/index.d.ts.map +1 -0
  340. package/dist/reaction/api/removeReaction.d.ts +36 -0
  341. package/dist/reaction/api/removeReaction.d.ts.map +1 -0
  342. package/dist/reaction/events/index.d.ts +2 -0
  343. package/dist/reaction/events/index.d.ts.map +1 -0
  344. package/dist/reaction/events/onReactionAdded.d.ts +17 -0
  345. package/dist/reaction/events/onReactionAdded.d.ts.map +1 -0
  346. package/dist/reaction/events/onReactionRemoved.d.ts +17 -0
  347. package/dist/reaction/events/onReactionRemoved.d.ts.map +1 -0
  348. package/dist/reaction/utils/dispatchReactable.d.ts +3 -0
  349. package/dist/reaction/utils/dispatchReactable.d.ts.map +1 -0
  350. package/dist/reaction/utils/fetchReference.d.ts +3 -0
  351. package/dist/reaction/utils/fetchReference.d.ts.map +1 -0
  352. package/dist/reaction/utils/index.d.ts +3 -0
  353. package/dist/reaction/utils/index.d.ts.map +1 -0
  354. package/dist/report/api/createReport.d.ts +16 -0
  355. package/dist/report/api/createReport.d.ts.map +1 -0
  356. package/dist/report/api/deleteReport.d.ts +16 -0
  357. package/dist/report/api/deleteReport.d.ts.map +1 -0
  358. package/dist/report/api/index.d.ts +4 -0
  359. package/dist/report/api/index.d.ts.map +1 -0
  360. package/dist/report/api/isReportedByMe.d.ts +16 -0
  361. package/dist/report/api/isReportedByMe.d.ts.map +1 -0
  362. package/dist/report/constants/referenceTypes.d.ts +24 -0
  363. package/dist/report/constants/referenceTypes.d.ts.map +1 -0
  364. package/dist/role/api/getRole.d.ts +32 -0
  365. package/dist/role/api/getRole.d.ts.map +1 -0
  366. package/dist/role/api/index.d.ts +3 -0
  367. package/dist/role/api/index.d.ts.map +1 -0
  368. package/dist/role/api/queryRoles.d.ts +42 -0
  369. package/dist/role/api/queryRoles.d.ts.map +1 -0
  370. package/dist/stream/api/createStream.d.ts +18 -0
  371. package/dist/stream/api/createStream.d.ts.map +1 -0
  372. package/dist/stream/api/deleteStream.d.ts +16 -0
  373. package/dist/stream/api/deleteStream.d.ts.map +1 -0
  374. package/dist/stream/api/getStream.d.ts +12 -0
  375. package/dist/stream/api/getStream.d.ts.map +1 -0
  376. package/dist/stream/api/index.d.ts +6 -0
  377. package/dist/stream/api/index.d.ts.map +1 -0
  378. package/dist/stream/api/queryStreams.d.ts +23 -0
  379. package/dist/stream/api/queryStreams.d.ts.map +1 -0
  380. package/dist/stream/api/updateStream.d.ts +17 -0
  381. package/dist/stream/api/updateStream.d.ts.map +1 -0
  382. package/dist/stream/events/index.d.ts +4 -0
  383. package/dist/stream/events/index.d.ts.map +1 -0
  384. package/dist/stream/events/onStreamRecorded.d.ts +17 -0
  385. package/dist/stream/events/onStreamRecorded.d.ts.map +1 -0
  386. package/dist/stream/events/onStreamStarted.d.ts +17 -0
  387. package/dist/stream/events/onStreamStarted.d.ts.map +1 -0
  388. package/dist/stream/events/onStreamStopped.d.ts +17 -0
  389. package/dist/stream/events/onStreamStopped.d.ts.map +1 -0
  390. package/dist/user/api/getUser.d.ts +32 -0
  391. package/dist/user/api/getUser.d.ts.map +1 -0
  392. package/dist/user/api/getUsers.d.ts +32 -0
  393. package/dist/user/api/getUsers.d.ts.map +1 -0
  394. package/dist/user/api/index.d.ts +5 -0
  395. package/dist/user/api/index.d.ts.map +1 -0
  396. package/dist/user/api/queryUsers.d.ts +43 -0
  397. package/dist/user/api/queryUsers.d.ts.map +1 -0
  398. package/dist/user/api/updateUser.d.ts +17 -0
  399. package/dist/user/api/updateUser.d.ts.map +1 -0
  400. package/dist/user/events/index.d.ts +2 -0
  401. package/dist/user/events/index.d.ts.map +1 -0
  402. package/dist/user/events/onUserUpdated.d.ts +17 -0
  403. package/dist/user/events/onUserUpdated.d.ts.map +1 -0
  404. package/dist/user/observers/index.d.ts +2 -0
  405. package/dist/user/observers/index.d.ts.map +1 -0
  406. package/dist/user/observers/observeUser.d.ts +19 -0
  407. package/dist/user/observers/observeUser.d.ts.map +1 -0
  408. package/package.json +59 -0
  409. package/rollup.config.js +41 -0
  410. package/src/@types/core/cache.ts +22 -0
  411. package/src/@types/core/errors.ts +34 -0
  412. package/src/@types/core/events.ts +60 -0
  413. package/src/@types/core/model.ts +51 -0
  414. package/src/@types/core/payload.ts +102 -0
  415. package/src/@types/core/permissions.ts +76 -0
  416. package/src/@types/core/query.ts +95 -0
  417. package/src/@types/core/store.ts +52 -0
  418. package/src/@types/core/transport.ts +32 -0
  419. package/src/@types/domains/category.ts +15 -0
  420. package/src/@types/domains/channel.ts +38 -0
  421. package/src/@types/domains/client.ts +36 -0
  422. package/src/@types/domains/comment.ts +26 -0
  423. package/src/@types/domains/community.ts +35 -0
  424. package/src/@types/domains/content.ts +35 -0
  425. package/src/@types/domains/feed.ts +16 -0
  426. package/src/@types/domains/file.ts +41 -0
  427. package/src/@types/domains/group.ts +38 -0
  428. package/src/@types/domains/message.ts +27 -0
  429. package/src/@types/domains/partials.ts +52 -0
  430. package/src/@types/domains/post.ts +31 -0
  431. package/src/@types/domains/reaction.ts +30 -0
  432. package/src/@types/domains/stream.ts +57 -0
  433. package/src/@types/domains/user.ts +18 -0
  434. package/src/@types/global.ts +25 -0
  435. package/src/@types/index.ts +31 -0
  436. package/src/category/api/getCategory.ts +35 -0
  437. package/src/category/api/index.ts +2 -0
  438. package/src/category/api/queryCategories.ts +49 -0
  439. package/src/channel/api/addChannelMembers.ts +45 -0
  440. package/src/channel/api/addChannelMembersRole.ts +43 -0
  441. package/src/channel/api/createChannel.ts +37 -0
  442. package/src/channel/api/deleteChannel.ts +34 -0
  443. package/src/channel/api/getChannel.ts +59 -0
  444. package/src/channel/api/getChannels.ts +63 -0
  445. package/src/channel/api/index.ts +18 -0
  446. package/src/channel/api/joinChannel.ts +38 -0
  447. package/src/channel/api/leaveChannel.ts +38 -0
  448. package/src/channel/api/queryChannelMembers.ts +79 -0
  449. package/src/channel/api/queryChannels.ts +89 -0
  450. package/src/channel/api/removeChannelMembers.ts +45 -0
  451. package/src/channel/api/removeChannelMembersRole.ts +43 -0
  452. package/src/channel/api/updateChannel.ts +38 -0
  453. package/src/channel/events/index.ts +6 -0
  454. package/src/channel/events/onChannelCreated.ts +37 -0
  455. package/src/channel/events/onChannelDeleted.ts +37 -0
  456. package/src/channel/events/onChannelJoined.ts +37 -0
  457. package/src/channel/events/onChannelLeft.ts +37 -0
  458. package/src/channel/events/onChannelUpdated.ts +37 -0
  459. package/src/channel/events/onMemberAdded.ts +37 -0
  460. package/src/channel/events/onMemberRemoved.ts +37 -0
  461. package/src/channel/observers/index.ts +1 -0
  462. package/src/channel/observers/observeChannel.ts +80 -0
  463. package/src/client/api/activeClient.ts +33 -0
  464. package/src/client/api/clearCache.ts +23 -0
  465. package/src/client/api/connectClient.ts +63 -0
  466. package/src/client/api/createClient.ts +56 -0
  467. package/src/client/api/disconnectClient.ts +31 -0
  468. package/src/client/api/enableCache.ts +35 -0
  469. package/src/client/api/getToken.ts +35 -0
  470. package/src/client/api/index.ts +7 -0
  471. package/src/client/api/isConnected.ts +24 -0
  472. package/src/client/events/index.ts +1 -0
  473. package/src/client/events/onClientDisconnected.ts +29 -0
  474. package/src/comment/api/createComment.ts +43 -0
  475. package/src/comment/api/deleteComment.ts +40 -0
  476. package/src/comment/api/getComment.ts +59 -0
  477. package/src/comment/api/getComments.ts +63 -0
  478. package/src/comment/api/index.ts +7 -0
  479. package/src/comment/api/queryComments.ts +169 -0
  480. package/src/comment/api/updateComment.ts +41 -0
  481. package/src/comment/events/index.ts +3 -0
  482. package/src/comment/events/onCommentCreated.ts +39 -0
  483. package/src/comment/events/onCommentDeleted.ts +39 -0
  484. package/src/comment/events/onCommentUpdated.ts +39 -0
  485. package/src/comment/observers/index.ts +2 -0
  486. package/src/comment/observers/observeComment.ts +73 -0
  487. package/src/comment/observers/observeComments.ts +61 -0
  488. package/src/community/api/addCommunityMembers.ts +46 -0
  489. package/src/community/api/addCommunityMembersRole.ts +43 -0
  490. package/src/community/api/createCommunity.ts +43 -0
  491. package/src/community/api/deleteCommunity.ts +35 -0
  492. package/src/community/api/getCommunities.ts +63 -0
  493. package/src/community/api/getCommunity.ts +58 -0
  494. package/src/community/api/index.ts +17 -0
  495. package/src/community/api/joinCommunity.ts +41 -0
  496. package/src/community/api/leaveCommunity.ts +41 -0
  497. package/src/community/api/queryCommunities.ts +92 -0
  498. package/src/community/api/queryCommunityMembers.ts +78 -0
  499. package/src/community/api/removeCommunityMembers.ts +46 -0
  500. package/src/community/api/removeCommunityMembersRole.ts +43 -0
  501. package/src/community/api/updateCommunity.ts +40 -0
  502. package/src/community/events/index.ts +6 -0
  503. package/src/community/events/onCommunityCreated.ts +37 -0
  504. package/src/community/events/onCommunityDeleted.ts +37 -0
  505. package/src/community/events/onCommunityJoined.ts +37 -0
  506. package/src/community/events/onCommunityLeft.ts +37 -0
  507. package/src/community/events/onCommunityUpdated.ts +37 -0
  508. package/src/community/observers/index.ts +1 -0
  509. package/src/community/observers/observeCommunity.ts +74 -0
  510. package/src/core/cache/drop.ts +24 -0
  511. package/src/core/cache/index.ts +24 -0
  512. package/src/core/cache/ingest.ts +24 -0
  513. package/src/core/cache/merge.ts +19 -0
  514. package/src/core/cache/mutate.ts +25 -0
  515. package/src/core/cache/pull.ts +31 -0
  516. package/src/core/cache/push.ts +41 -0
  517. package/src/core/cache/sync.ts +41 -0
  518. package/src/core/debug.ts +26 -0
  519. package/src/core/device.ts +38 -0
  520. package/src/core/errors.ts +85 -0
  521. package/src/core/events.ts +93 -0
  522. package/src/core/model/idResolvers.ts +66 -0
  523. package/src/core/model/identifyModel.ts +32 -0
  524. package/src/core/model/index.ts +3 -0
  525. package/src/core/model/toRecord.ts +11 -0
  526. package/src/core/query/decorate.ts +64 -0
  527. package/src/core/query/filtering.ts +17 -0
  528. package/src/core/query/index.ts +5 -0
  529. package/src/core/query/paging.ts +166 -0
  530. package/src/core/query/query.ts +300 -0
  531. package/src/core/query/sorting.ts +50 -0
  532. package/src/core/stores/index.ts +2 -0
  533. package/src/core/stores/memory.ts +59 -0
  534. package/src/core/stores/persistent.ts +63 -0
  535. package/src/core/transports.ts +157 -0
  536. package/src/core/uuid.ts +2 -0
  537. package/src/feed/api/index.ts +1 -0
  538. package/src/feed/api/queryGlobalFeed.ts +50 -0
  539. package/src/file/api/createFile.ts +51 -0
  540. package/src/file/api/deleteFile.ts +35 -0
  541. package/src/file/api/fileUrlWithSize.ts +13 -0
  542. package/src/file/api/getFile.ts +60 -0
  543. package/src/file/api/index.ts +4 -0
  544. package/src/file/observers/index.ts +1 -0
  545. package/src/file/observers/observeFile.ts +57 -0
  546. package/src/index.ts +55 -0
  547. package/src/message/api/createMessage.ts +90 -0
  548. package/src/message/api/deleteMessage.ts +75 -0
  549. package/src/message/api/getMessage.ts +60 -0
  550. package/src/message/api/getMessages.ts +63 -0
  551. package/src/message/api/index.ts +6 -0
  552. package/src/message/api/queryMessages.ts +145 -0
  553. package/src/message/api/updateMessage.ts +79 -0
  554. package/src/message/events/index.ts +3 -0
  555. package/src/message/events/onMessageCreated.ts +39 -0
  556. package/src/message/events/onMessageDeleted.ts +39 -0
  557. package/src/message/events/onMessageUpdated.ts +39 -0
  558. package/src/message/observers/index.ts +2 -0
  559. package/src/message/observers/observeMessage.ts +76 -0
  560. package/src/message/observers/observeMessages.ts +60 -0
  561. package/src/post/api/createPost.ts +45 -0
  562. package/src/post/api/deletePost.ts +43 -0
  563. package/src/post/api/getPost.ts +60 -0
  564. package/src/post/api/getPosts.ts +63 -0
  565. package/src/post/api/index.ts +7 -0
  566. package/src/post/api/queryPosts.ts +86 -0
  567. package/src/post/api/updatePost.ts +42 -0
  568. package/src/post/events/index.ts +3 -0
  569. package/src/post/events/onPostCreated.ts +39 -0
  570. package/src/post/events/onPostDeleted.ts +39 -0
  571. package/src/post/events/onPostUpdated.ts +39 -0
  572. package/src/post/observers/index.ts +2 -0
  573. package/src/post/observers/observePost.ts +72 -0
  574. package/src/post/observers/observePosts.ts +66 -0
  575. package/src/reaction/api/addReaction.ts +84 -0
  576. package/src/reaction/api/index.ts +2 -0
  577. package/src/reaction/api/removeReaction.ts +84 -0
  578. package/src/reaction/events/index.ts +1 -0
  579. package/src/reaction/events/onReactionAdded.ts +43 -0
  580. package/src/reaction/events/onReactionRemoved.ts +41 -0
  581. package/src/reaction/utils/dispatchReactable.ts +19 -0
  582. package/src/reaction/utils/fetchReference.ts +18 -0
  583. package/src/reaction/utils/index.ts +2 -0
  584. package/src/report/api/createReport.ts +40 -0
  585. package/src/report/api/deleteReport.ts +40 -0
  586. package/src/report/api/index.ts +4 -0
  587. package/src/report/api/isReportedByMe.ts +37 -0
  588. package/src/report/constants/referenceTypes.ts +22 -0
  589. package/src/role/api/getRole.ts +53 -0
  590. package/src/role/api/index.ts +2 -0
  591. package/src/role/api/queryRoles.ts +79 -0
  592. package/src/stream/api/createStream.ts +33 -0
  593. package/src/stream/api/deleteStream.ts +38 -0
  594. package/src/stream/api/getStream.ts +29 -0
  595. package/src/stream/api/index.ts +7 -0
  596. package/src/stream/api/queryStreams.ts +44 -0
  597. package/src/stream/api/updateStream.ts +36 -0
  598. package/src/stream/events/index.ts +3 -0
  599. package/src/stream/events/onStreamRecorded.ts +39 -0
  600. package/src/stream/events/onStreamStarted.ts +39 -0
  601. package/src/stream/events/onStreamStopped.ts +39 -0
  602. package/src/user/api/getUser.ts +59 -0
  603. package/src/user/api/getUsers.ts +60 -0
  604. package/src/user/api/index.ts +5 -0
  605. package/src/user/api/queryUsers.ts +88 -0
  606. package/src/user/api/updateUser.ts +44 -0
  607. package/src/user/events/index.ts +1 -0
  608. package/src/user/events/onUserUpdated.ts +39 -0
  609. package/src/user/observers/index.ts +1 -0
  610. package/src/user/observers/observeUser.ts +64 -0
  611. package/tsconfig.json +28 -0
@@ -0,0 +1,4884 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var jsBase64 = require('js-base64');
6
+ var nativeIdGenerator = require('react-native-uuid');
7
+ var debug = require('debug');
8
+ var axios = require('axios');
9
+ var HttpAgent = require('agentkeepalive');
10
+ var io = require('socket.io-client');
11
+ var mitt = require('mitt');
12
+ var AsyncStorage = require('@react-native-async-storage/async-storage');
13
+
14
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
15
+
16
+ var nativeIdGenerator__default = /*#__PURE__*/_interopDefaultLegacy(nativeIdGenerator);
17
+ var debug__default = /*#__PURE__*/_interopDefaultLegacy(debug);
18
+ var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
19
+ var HttpAgent__default = /*#__PURE__*/_interopDefaultLegacy(HttpAgent);
20
+ var io__default = /*#__PURE__*/_interopDefaultLegacy(io);
21
+ var mitt__default = /*#__PURE__*/_interopDefaultLegacy(mitt);
22
+ var AsyncStorage__default = /*#__PURE__*/_interopDefaultLegacy(AsyncStorage);
23
+
24
+ /**
25
+ * Generic ASC error
26
+ * @category Errors
27
+ */
28
+ class ASCError extends Error {
29
+ /**
30
+ * @param message A custom error message
31
+ * @param code A normalized error code
32
+ * @param level A normalized failure level descriptor
33
+ */
34
+ constructor(message, code, level) {
35
+ super(`Amity SDK (${code}): ${message}`);
36
+ this.code = code;
37
+ this.level = level;
38
+ this.type = 'ASC';
39
+ this.timestamp = Date.now();
40
+ if (Error.captureStackTrace)
41
+ Error.captureStackTrace(this, ASCError);
42
+ }
43
+ }
44
+ /**
45
+ * API level error
46
+ * @category Errors
47
+ */
48
+ class ASCApiError extends ASCError {
49
+ /**
50
+ * @param code A normalized error code
51
+ * @param level A normalized failure level descriptor
52
+ */
53
+ constructor(message, code, level) {
54
+ super(message, code, level);
55
+ }
56
+ }
57
+ /**
58
+ * Unexpected error
59
+ * @category Errors
60
+ */
61
+ class ASCUnknownError extends ASCError {
62
+ /**
63
+ * @param code A normalized error code
64
+ * @param level A normalized failure level descriptor
65
+ */
66
+ constructor(code = 800000 /* UNKNOWN_ERROR */, level = "fatal" /* FATAL */) {
67
+ super('Unexpected error', code, level);
68
+ }
69
+ }
70
+ /**
71
+ * Network related error
72
+ * @category Errors
73
+ */
74
+ class ASCConnectionError extends ASCError {
75
+ /**
76
+ * @param message A custom error message
77
+ */
78
+ constructor(message = 'SDK client is having connection issues') {
79
+ super(message, 800210 /* CONNECTION_ERROR */, "error" /* ERROR */);
80
+ }
81
+ }
82
+
83
+ let activeClient = null;
84
+ /**
85
+ * Get the active client
86
+ *
87
+ * @returns the active client instance
88
+ *
89
+ * @hidden
90
+ */
91
+ const getActiveClient = () => {
92
+ if (!activeClient) {
93
+ throw new ASCError('There is no active client', 800000 /* UNKNOWN_ERROR */, "fatal" /* FATAL */);
94
+ }
95
+ return activeClient;
96
+ };
97
+ /**
98
+ * Sets the active client
99
+ *
100
+ * @param client the client to assume as currently active client
101
+ *
102
+ * @hidden
103
+ */
104
+ const setActiveClient = (client) => {
105
+ activeClient = client;
106
+ };
107
+
108
+ /**
109
+ * Pull objects from the cache layer
110
+ *
111
+ * @param name The name of the store to query
112
+ * @param keys A collection of unique keys for the store
113
+ * @returns The collection of objects matching the keys. Keys which don't match object will be omitted
114
+ *
115
+ * @category Cache
116
+ */
117
+ const pullFromCache = (name, ...keys) => {
118
+ var _a;
119
+ const { cache } = getActiveClient();
120
+ const store = cache === null || cache === void 0 ? void 0 : cache[name];
121
+ if (!cache || !store)
122
+ return;
123
+ const state = (_a = store.read()) !== null && _a !== void 0 ? _a : {};
124
+ // return all
125
+ if (!(keys === null || keys === void 0 ? void 0 : keys.length))
126
+ return Object.values(state);
127
+ // return some
128
+ return keys
129
+ .map(key => {
130
+ const localId = cache.lookup[`${name}#${key}`];
131
+ return state[localId];
132
+ })
133
+ .filter(Boolean);
134
+ };
135
+
136
+ /**
137
+ * Dictionary of resolver functions for each model
138
+ * @hidden
139
+ */
140
+ const idResolvers = {
141
+ user: ({ userId }) => userId,
142
+ file: ({ fileId }) => fileId,
143
+ role: ({ roleId }) => roleId,
144
+ channel: ({ channelId }) => channelId,
145
+ channelUsers: ({ channelId, userId }) => `${channelId}#${userId}`,
146
+ message: ({ messageId }) => messageId,
147
+ community: ({ communityId }) => communityId,
148
+ communityUsers: ({ communityId, userId }) => `${communityId}#${userId}`,
149
+ post: ({ postId }) => postId,
150
+ comment: ({ commentId }) => commentId,
151
+ stream: ({ streamId }) => streamId,
152
+ };
153
+ /**
154
+ * Retrieve the id resolver matching a domain name
155
+ *
156
+ * @param name the domain name for the resolve
157
+ * @returns an idResolver for the given domain name
158
+ */
159
+ const getResolver = (name) => idResolvers[name];
160
+ /**
161
+ * A map of v3 response keys to a store name.
162
+ * @hidden
163
+ */
164
+ const storeInterests = {
165
+ users: 'user',
166
+ files: 'file',
167
+ roles: 'role',
168
+ channels: 'channel',
169
+ channelUsers: 'channelUsers',
170
+ messages: 'message',
171
+ communities: 'community',
172
+ communityUsers: 'communityUsers',
173
+ posts: 'post',
174
+ postChildren: 'post',
175
+ comments: 'comment',
176
+ };
177
+
178
+ /**
179
+ * Pull objects from the cache layer
180
+ *
181
+ * @param name The name of the store to query
182
+ * @param models A collection of models t store
183
+ *
184
+ * @category Cache
185
+ */
186
+ const pushToCache = (name, ...models) => {
187
+ const { cache } = getActiveClient();
188
+ const store = cache === null || cache === void 0 ? void 0 : cache[name];
189
+ if (!cache || !store)
190
+ return;
191
+ const filtered = models.filter(Boolean);
192
+ if (!filtered.length)
193
+ return;
194
+ const synced = Object.fromEntries(filtered.map(model => {
195
+ var _a;
196
+ var _b, _c;
197
+ const modelId = getResolver(name)(model);
198
+ const localId = ((_a = (_b = cache.lookup)[_c = `${name}#${modelId}`]) !== null && _a !== void 0 ? _a : (_b[_c] = model.localId));
199
+ // WARNING: shallow immutable
200
+ return [localId, Object.assign(Object.assign({
201
+ // @ts-ignore: syncedAt is before "...model" so it can be manually overridden
202
+ syncedAt: Date.now() }, model), { localId })];
203
+ }));
204
+ store.write(synced);
205
+ };
206
+
207
+ /**
208
+ * Pull objects from the cache layer
209
+ *
210
+ * @param name The name of the store to query
211
+ * @param keys A collection of unique keys for the store
212
+ * @returns The collection of objects matching the keys. Keys which don't match object will be omitted
213
+ *
214
+ * @category Cache
215
+ */
216
+ const dropFromCache = (name, partial) => {
217
+ const { cache } = getActiveClient();
218
+ const store = cache === null || cache === void 0 ? void 0 : cache[name];
219
+ if (!cache || !store)
220
+ return [];
221
+ const modelId = getResolver(name)(partial);
222
+ const localId = cache.lookup[`${name}#${modelId}`];
223
+ delete cache.lookup[`${name}#${modelId}`];
224
+ store.erase(localId);
225
+ };
226
+
227
+ /** hidden */
228
+ /** @hidden */
229
+ const CRITERIAS = {
230
+ 'file': ['fileId', 'attributes'],
231
+ 'user': ['userId', 'avatarFileId'],
232
+ 'role': ['roleId'],
233
+ 'channel': ['channelId', 'rateLimit'],
234
+ 'channelUsers': ['channelId', 'userId', 'membership'],
235
+ 'message': ['messageId'],
236
+ 'community': ['communityId', 'onlyAdminCanPost'],
237
+ 'communityUsers': ['userId', 'communityId', 'communityMembership'],
238
+ 'post': ['postId', 'feedId'],
239
+ 'comment': ['commentId', 'referenceId'],
240
+ 'stream': ['streamId'],
241
+ };
242
+ /** @hidden */
243
+ const hasKeys = (object, needles) => {
244
+ const haystack = Object.keys(object);
245
+ return needles.every(needle => haystack.includes(needle));
246
+ };
247
+ /**
248
+ * Finds the name of the store for a given unknown model
249
+ *
250
+ * @param model one of the {@link Amity.Model} to identify
251
+ * @returns the name of the corresponding store
252
+ */
253
+ const identifyModel = (model) => {
254
+ var _a;
255
+ const criterias = Object.entries(CRITERIAS);
256
+ return (_a = criterias.find(([_, keys]) => hasKeys(model, keys))) === null || _a === void 0 ? void 0 : _a[0];
257
+ };
258
+
259
+ /**
260
+ * Sync-up local ids of objects in the cache
261
+ *
262
+ * @param original The object holding the localId to keep
263
+ * @param replacement The object holding the localId to discard
264
+ *
265
+ * @category Cache
266
+ */
267
+ const syncInCache = (original, replacement) => {
268
+ var _a;
269
+ const { cache, log } = getActiveClient();
270
+ const name = (_a = identifyModel(original)) !== null && _a !== void 0 ? _a : identifyModel(replacement);
271
+ if (!name) {
272
+ log('syncInCache', 'could not identify the models', { original, replacement });
273
+ return;
274
+ }
275
+ const store = cache === null || cache === void 0 ? void 0 : cache[name];
276
+ if (!cache || !store)
277
+ return;
278
+ // remove the object from cache (it's cleaner this way)
279
+ dropFromCache(name, original);
280
+ dropFromCache(name, replacement);
281
+ // glue the localIds together
282
+ replacement.localId = original.localId;
283
+ // put back the replacement after (again, it's cleaner this way)
284
+ pushToCache(name, replacement);
285
+ };
286
+
287
+ /**
288
+ * Ingest a payload (v3) into the cache
289
+ *
290
+ * @param payload a "backend v3" payload object
291
+ * @param order the order of the keys to process (in case of need)
292
+ *
293
+ * @category Cache
294
+ */
295
+ const ingestInCache = (payload = {}, order = Object.keys(payload)) => {
296
+ order
297
+ .forEach(key => {
298
+ const name = storeInterests[key];
299
+ if (!name)
300
+ return;
301
+ pushToCache(name, ...payload[key]);
302
+ });
303
+ };
304
+
305
+ /**
306
+ * Apply partial mutation to objects in the cache
307
+ *
308
+ * @param name The name of the store to query
309
+ * @param mutation A partial view of the object to update
310
+ *
311
+ * @category Cache
312
+ */
313
+ const mutateCache = (name, key, mutator) => {
314
+ var _a;
315
+ const [model] = (_a = pullFromCache(name, key)) !== null && _a !== void 0 ? _a : [];
316
+ if (!model)
317
+ return;
318
+ const mutation = mutator(model);
319
+ mutation && pushToCache(name, Object.assign(Object.assign({}, model), mutation));
320
+ return mutation;
321
+ };
322
+
323
+ /**
324
+ * Apply partial mutation to objects in the cache
325
+ *
326
+ * @param name The name of the store to query
327
+ * @param mutation A partial view of the object to update
328
+ *
329
+ * @category Cache
330
+ */
331
+ const mergeInCache = (name, mutation) => {
332
+ const key = getResolver(name)(mutation);
333
+ mutateCache(name, key, model => (Object.assign(Object.assign({}, model), mutation)));
334
+ };
335
+
336
+ /**
337
+ * Creates a cache instance. The cache instance will handle stores
338
+ * given to it as input, and will be used as the first source of cached data
339
+ * in the SDK.
340
+ *
341
+ * @param stores A partial collection of stores
342
+ * @returns A cache instance
343
+ *
344
+ * @category Cache
345
+ */
346
+ const createCache = (stores) => {
347
+ const lookup = {};
348
+ return Object.assign({ lookup }, stores);
349
+ };
350
+
351
+ // @ts-ignore
352
+ /**
353
+ * Type guard to find if the a given decoded backend token uses "skip/limit" pagination style
354
+ *
355
+ * @param json any json object as extracted from the backend
356
+ * @returns success boolean if the token has either "skip" or "limit" props
357
+ *
358
+ * @hidden
359
+ */
360
+ const isSkipLimit = (json) => (['skip', 'limit'].some(prop => prop in json));
361
+ /**
362
+ * Type guard to find if the a given decoded backend token uses "after/before" pagination style
363
+ *
364
+ * @param json any json object as extracted from the backend
365
+ * @returns success boolean if the token has either "after" or "before" props
366
+ *
367
+ * @hidden
368
+ */
369
+ const isAfterBefore = (json) => (['after', 'before', 'first', 'last'].some(prop => prop in json));
370
+ /**
371
+ * Type guard to find if the a given object is wrapped around Amity.Paged<>
372
+ *
373
+ * @param payload any object as passed from query functions
374
+ * @returns success boolean if the object is an array shaped as [Record<string, Amity.Syncable>, Amity.Pages]
375
+ *
376
+ * @hidden
377
+ */
378
+ const isPaged = (payload) => {
379
+ return ((payload === null || payload === void 0 ? void 0 : payload.hasOwnProperty('data'))
380
+ && (payload === null || payload === void 0 ? void 0 : payload.hasOwnProperty('nextPage'))
381
+ && (payload === null || payload === void 0 ? void 0 : payload.hasOwnProperty('prevPage')));
382
+ };
383
+ /**
384
+ * Converts a paging object into a b64 string token
385
+ *
386
+ * @param paging the sdk-friendly paging object
387
+ * @param style the style of token to produce
388
+ * @returns a backend's b64 encoded token
389
+ *
390
+ * @hidden
391
+ */
392
+ const toToken = (paging, style) => {
393
+ var _a;
394
+ if (!paging || !Object.keys(paging).length)
395
+ return;
396
+ let payload = {};
397
+ // TODO: refactor this clean
398
+ if (style === 'skiplimit') {
399
+ payload = {
400
+ skip: (_a = paging.after) !== null && _a !== void 0 ? _a : 0,
401
+ limit: paging.limit,
402
+ };
403
+ }
404
+ else if (style === 'afterbefore') {
405
+ /*
406
+ Caution: this testing style is only valid because
407
+ our backend expects nothing else than a number as
408
+ "before" or "after" value. if that would change,
409
+ we'd need to move toward a more simple: `!paging.before`
410
+ */
411
+ if (!isNaN(paging === null || paging === void 0 ? void 0 : paging.before)) {
412
+ payload = {
413
+ before: paging.before,
414
+ last: paging.limit,
415
+ };
416
+ }
417
+ else if (!isNaN(paging === null || paging === void 0 ? void 0 : paging.after)) {
418
+ payload = {
419
+ after: paging.after,
420
+ first: paging.limit,
421
+ };
422
+ }
423
+ }
424
+ // avoid sending {} as it seems backend flips when we do
425
+ if (!Object.keys(payload).length)
426
+ return;
427
+ // don't try catch, let it throw
428
+ return jsBase64.encode(JSON.stringify(payload));
429
+ };
430
+ /**
431
+ * Converts a b64 string token into a paging object
432
+ *
433
+ * @param token the backend's b64 encoded token
434
+ * @returns a sdk-friendly paging object
435
+ *
436
+ * @hidden
437
+ */
438
+ const toPage = (token) => {
439
+ if (!token)
440
+ return null;
441
+ // don't try catch, let it throw
442
+ const json = JSON.parse(jsBase64.decode(token));
443
+ if (isSkipLimit(json)) {
444
+ return {
445
+ after: json.skip,
446
+ limit: json.limit,
447
+ };
448
+ }
449
+ else if (isAfterBefore(json)) {
450
+ if ('before' in json) {
451
+ return {
452
+ before: json.before,
453
+ limit: json.last,
454
+ };
455
+ }
456
+ else if ('after' in json) {
457
+ return {
458
+ after: json.after,
459
+ limit: json.first,
460
+ };
461
+ }
462
+ }
463
+ return null;
464
+ };
465
+ /**
466
+ * Slices a collection according to its paging
467
+ *
468
+ * @param type the type of collection (for unique id identification with after/before)
469
+ * @param collection the collection to slice
470
+ * @param paging the paging object
471
+ * @returns the sliced collection according to the paging definition
472
+ *
473
+ * @hidden
474
+ */
475
+ const sliceByPaging = (type, collection, page) => {
476
+ console.log('slice by paging', page);
477
+ if (!page)
478
+ return collection.slice();
479
+ let start = 0;
480
+ let end = undefined;
481
+ // next page behavior
482
+ if (page.after) {
483
+ start = page.after;
484
+ end = start + page.limit;
485
+ // prev page behavior
486
+ }
487
+ else if (page.before) {
488
+ end = page.before + 1;
489
+ start = end > page.limit ? end - page.limit : 0;
490
+ }
491
+ const paged = collection.slice(start, end);
492
+ return paged.length === page.limit ? paged : undefined;
493
+ };
494
+
495
+ /**
496
+ * Type guard to check and cast that a given async function is has the ".locally" property
497
+ *
498
+ * @param func any SDK APi function
499
+ * @returns success boolean if the function has a 'locally' twin
500
+ *
501
+ * @hidden
502
+ */
503
+ const isFetcher = (func) => ('locally' in func);
504
+ /**
505
+ * Type guard to check and cast that a given async function is has the ".optimistically" property
506
+ *
507
+ * @param func any SDK APi function
508
+ * @returns success boolean if the function has an 'optimistically' twin
509
+ *
510
+ * @hidden
511
+ */
512
+ const isMutator = (func) => ('optimistically' in func);
513
+ /**
514
+ * Type guard to check and cast that a given async function is has
515
+ * the ".locally" or ".optimistically" property
516
+ *
517
+ * @param func any SDK APi function
518
+ * @returns success boolean if the function has an offline twin
519
+ *
520
+ * @hidden
521
+ */
522
+ const isOffline = (func) => isFetcher(func) || isMutator(func);
523
+ /**
524
+ * Type guard to check and cast that a given object has the "syncedAt" property
525
+ *
526
+ * @param model any object to check on
527
+ * @returns success boolean if the object has property "syncedAt"
528
+ *
529
+ * @hidden
530
+ */
531
+ const isSyncable = (model) => (model === null || model === void 0 ? void 0 : model.hasOwnProperty('syncedAt'));
532
+ /**
533
+ * Checks if a model is considered local (syncedAt === -1)
534
+ *
535
+ * @param model any syncable object to check
536
+ * @returns success boolean if the object is marked as local
537
+ *
538
+ * @hidden
539
+ */
540
+ const isLocal = (model) => {
541
+ return isSyncable(model) && (model === null || model === void 0 ? void 0 : model.syncedAt) === -1;
542
+ };
543
+ /**
544
+ * Checks if a model is considered fresh
545
+ *
546
+ * @param model any syncable object to check
547
+ * @param lifeSpan the supposedly duration for which the object is considered synced
548
+ * @returns success boolean if the object is below the given lifespan
549
+ *
550
+ * @hidden
551
+ */
552
+ const isFresh = (model, lifeSpan = 0) => {
553
+ var _a;
554
+ return Date.now() - ((_a = model === null || model === void 0 ? void 0 : model.syncedAt) !== null && _a !== void 0 ? _a : 0) <= lifeSpan;
555
+ };
556
+ /**
557
+ * Checks if a model is considered synced
558
+ *
559
+ * @param model any syncable object to check
560
+ * @param lifeSpan the supposedly duration for which the object is considered synced
561
+ * @returns success boolean if the object is local or below the given lifespan
562
+ *
563
+ * @hidden
564
+ */
565
+ const isSynced = (model, lifeSpan = 0) => {
566
+ return isLocal(model) || isFresh(model, lifeSpan);
567
+ };
568
+ /**
569
+ * ```js
570
+ * import { createQuery, getUser } from '@amityco/ts-sdk'
571
+ * const query = createQuery(getUser, 'foobar')
572
+ * ```
573
+ *
574
+ * Creates a wrapper for the API call you wish to call.
575
+ * This wrapper is necessary to create for optimistically calls
576
+ *
577
+ *
578
+ * @param fn A compatible API function from the ts sdk
579
+ * @param args The arguments to pass to the function passed as `fn`
580
+ * @returns A wrapper containing both the function and its future arguments
581
+ *
582
+ * @category Query
583
+ */
584
+ const createQuery = (func, ...args) => ({ func, args });
585
+ /**
586
+ * ```js
587
+ * import { queryOptions } from '@amityco/ts-sdk'
588
+ * const options = queryOptions('no_fetch', lifeSpan)
589
+ * ```
590
+ *
591
+ * Creates a query options object based on the query policy passed
592
+ *
593
+ * @param policy The policy to apply to a query
594
+ * @returns A properly set query options object
595
+ *
596
+ * @category Query
597
+ */
598
+ const queryOptions = (policy, lifeSpan = 2 * 60 * 1000) => {
599
+ if (policy === 'cache_only')
600
+ return { lifeSpan: Infinity };
601
+ else if (policy === 'server_only')
602
+ return { lifeSpan: 0 };
603
+ return { lifeSpan };
604
+ };
605
+ /**
606
+ * Checks if an unknown shaped payload is considered empty or not.
607
+ * Since the payload can be wrapped around [] or {} (query or get many),
608
+ * we need a smarter definition of what's considered "empty".
609
+ *
610
+ * @param local the unknown object to check for emptiness
611
+ * @returns true if the mixed-shape "local" content is considered empty
612
+ *
613
+ * @hidden
614
+ */
615
+ const isEmpty = (local) => {
616
+ // if it's supposed to be a single object, it'd be undefined
617
+ if (!local)
618
+ return true;
619
+ // it's a paged query, the 1st cell of the array would be empty
620
+ else if (isPaged(local) && isEmpty(local.data)) {
621
+ return true;
622
+ }
623
+ // if it's a item collection, it'd have no keys
624
+ else if (!Object.keys(local).length)
625
+ return true;
626
+ return false;
627
+ };
628
+ /**
629
+ * Checks if an unknown shaped payload is considered synced or not.
630
+ * The object will first be identified by 3 types of shapes:
631
+ *
632
+ * 1. Amity.Paged<Amity.Syncable>
633
+ * 2. Amity.Syncable
634
+ * 3. Record<string, Amity.Syncable>
635
+ *
636
+ * then the "Syncable" component will be extracted and evaluated against
637
+ * the query options' lifeSpan value.
638
+ *
639
+ * @param local the unknown object to check for freshness
640
+ * @param options query options (for lifeSpan checking)
641
+ * @returns true if the mixed-shape "local" content is considered fresh
642
+ *
643
+ * @hidden
644
+ */
645
+ const shouldAbort = (local, options) => {
646
+ // it's a paged query
647
+ if (isPaged(local) && shouldAbort(local.data, options)) {
648
+ return true;
649
+ }
650
+ // if it's object let's try to see if it's Amity.Syncable first
651
+ else if (isSynced(local, options.lifeSpan)) {
652
+ return true;
653
+ }
654
+ // otherwise consider as Record<string, Amity.Syncable>
655
+ else if (Object.values(local).length > 0 &&
656
+ Object.values(local).every(item => isSynced(item, options.lifeSpan))) {
657
+ return true;
658
+ }
659
+ return false;
660
+ };
661
+ /**
662
+ * ```js
663
+ * import { createQuery, getUser, runQuery } from '@amityco/ts-sdk'
664
+ * const query = createQuery(getUser, client, 'foobar')
665
+ * runQuery(query, user => console.log(user))
666
+ * ```
667
+ *
668
+ * Calls an API function wrapped around a Amity.Query, and executes the callback whenever
669
+ * a value is available. The value can be picked either from the local cache and/or
670
+ * from the server afterwards depending on the query options passed
671
+ *
672
+ * @param query A query object wrapping the call to be made
673
+ * @param callback A function to execute when a value is available
674
+ * @param options the query options
675
+ *
676
+ * @category Query
677
+ */
678
+ const runQuery = ({ func, args }, callback, options = queryOptions('cache_then_server')) => {
679
+ if (!isOffline(func) || options.lifeSpan === 0) {
680
+ callback === null || callback === void 0 ? void 0 : callback(wrap(undefined, {
681
+ origin: 'server',
682
+ loading: true
683
+ }));
684
+ func(...args)
685
+ .then(fresh => {
686
+ callback === null || callback === void 0 ? void 0 : callback(wrap(fresh, {
687
+ origin: 'server',
688
+ loading: false,
689
+ }));
690
+ })
691
+ .catch(error => {
692
+ callback === null || callback === void 0 ? void 0 : callback(wrap(undefined, {
693
+ error,
694
+ loading: false,
695
+ }));
696
+ });
697
+ return;
698
+ }
699
+ const local = isMutator(func)
700
+ ? func.optimistically(...args)
701
+ : func.locally(...args);
702
+ if (!isEmpty(local)) {
703
+ callback === null || callback === void 0 ? void 0 : callback(wrap(local, { origin: 'local' }));
704
+ }
705
+ if (local && isFetcher(func) && shouldAbort(local, options))
706
+ return;
707
+ callback === null || callback === void 0 ? void 0 : callback(wrap(local, {
708
+ origin: 'local',
709
+ loading: true,
710
+ }));
711
+ func(...args)
712
+ .then(fresh => {
713
+ // @ts-ignore i know.
714
+ isLocal(local) && syncInCache(local, fresh);
715
+ callback === null || callback === void 0 ? void 0 : callback(wrap(fresh, {
716
+ origin: 'server',
717
+ loading: false
718
+ }));
719
+ })
720
+ .catch(error => {
721
+ callback === null || callback === void 0 ? void 0 : callback(wrap(local, {
722
+ error,
723
+ loading: false,
724
+ }));
725
+ });
726
+ };
727
+ /**
728
+ *
729
+ * @param data
730
+ * @param meta
731
+ * @returns
732
+ */
733
+ const wrap = (data, meta = {}) => {
734
+ if (isPaged(data))
735
+ return Object.assign(Object.assign({}, meta), data);
736
+ return Object.assign(Object.assign({}, meta), { data });
737
+ };
738
+
739
+ const uuid = () => nativeIdGenerator__default['default'].v4().toString();
740
+
741
+ /**
742
+ * Creates a pre-configured logger instance
743
+ *
744
+ * @param session The name of the debug session
745
+ * @returns A pre-configured logger function
746
+ *
747
+ * @category Debug
748
+ * @hidden
749
+ */
750
+ const createLogger = (session) => {
751
+ const active = (`${session === null || session === void 0 ? void 0 : session.trim()}`.length > 0
752
+ && process.env.NODE_ENV !== 'production');
753
+ const logger = debug__default['default'](session);
754
+ const print = (topic, ...args) => {
755
+ active && logger(topic, args);
756
+ };
757
+ print.__instance__ = logger;
758
+ return print;
759
+ };
760
+
761
+ /**
762
+ * Axios param serializer (for querystring)
763
+ * @hidden
764
+ */
765
+ const stringify = (params, prefix) => {
766
+ return Object.entries(params)
767
+ .filter(([, value]) => value !== undefined)
768
+ .map(([name, value]) => {
769
+ const key = prefix ? `${prefix}[${name}]` : name;
770
+ if (Array.isArray(value)) {
771
+ return value.map(item => `${key}[]=${item}`).join('&');
772
+ }
773
+ else if (typeof value !== 'object') {
774
+ return `${key}=${value}`;
775
+ }
776
+ return stringify(value, prefix !== null && prefix !== void 0 ? prefix : name);
777
+ })
778
+ .join('&');
779
+ };
780
+ /**
781
+ * Creates a pre-configured axios instance
782
+ *
783
+ * @param endpoint The ASC rest api server's URL
784
+ * @returns A pre-configured axios instance
785
+ *
786
+ * @category Transport
787
+ * @hidden
788
+ */
789
+ const createHttpTransport = (endpoint = 'https://api.amity.co') => {
790
+ const options = {
791
+ maxSockets: 100,
792
+ maxFreeSockets: 10,
793
+ timeout: 60000,
794
+ freeSocketTimeout: 30000,
795
+ };
796
+ const instance = axios__default['default'].create({
797
+ baseURL: endpoint,
798
+ httpAgent: new HttpAgent__default['default'](options),
799
+ httpsAgent: new HttpAgent.HttpsAgent(options),
800
+ paramsSerializer: stringify,
801
+ });
802
+ instance.interceptors.response.use((response) => response, (error) => {
803
+ var _a;
804
+ const { response } = error;
805
+ console.error((_a = response === null || response === void 0 ? void 0 : response.data) !== null && _a !== void 0 ? _a : error);
806
+ if (response)
807
+ unwrapPayload(response.data);
808
+ });
809
+ return instance;
810
+ };
811
+ /**
812
+ * Creates a pre-configured socket.io instance
813
+ *
814
+ * @param endpoint The socket.io server's URL
815
+ * @returns A pre-configured (non-connected) socket.io client instance
816
+ *
817
+ * @category Transport
818
+ * @hidden
819
+ */
820
+ const createWebsocketTransport = (endpoint = 'https://api.ekomedia.technology') => {
821
+ const socket = io__default['default'](endpoint, {
822
+ autoConnect: false,
823
+ reconnectionDelay: 2000,
824
+ transports: ['websocket'],
825
+ });
826
+ socket.on('disconnect', (reason) => {
827
+ if (reason === 'io server disconnect')
828
+ socket.connect();
829
+ });
830
+ ['error', 'connect_error', 'connect_timeout', 'reconnect_error', 'reconnect_failed'].forEach(event => {
831
+ socket.on(event, (error) => {
832
+ throw new ASCConnectionError(`socket.io(${event}): ${error.message}`);
833
+ });
834
+ });
835
+ return socket;
836
+ };
837
+ /**
838
+ * Unwraps v3 server payload (for error handling and type extraction)
839
+ *
840
+ * @param response A typical "v3" response (related to backend's service strategy)
841
+ *
842
+ * @returns The data returned by the backend
843
+ * @throws An error related to backend's rejection
844
+ *
845
+ * @category Transport
846
+ * @hidden
847
+ */
848
+ const unwrapPayload = (response) => {
849
+ if (response.status === 'success') {
850
+ return response.data;
851
+ }
852
+ else if (response.status === 'fail') {
853
+ throw new ASCUnknownError(response.code);
854
+ }
855
+ else if (response.status === 'error') {
856
+ throw new ASCApiError(response.message, response.code, "error" /* ERROR */);
857
+ }
858
+ // unjust, but helps force uncast "T | undefined" to allow deconstruction without warnings
859
+ return undefined;
860
+ };
861
+ /**
862
+ * Promisify a websocket event emission - resulting in a synchronous http-like XHR (ws legacy)
863
+ *
864
+ * @param client The current client for which to send the event with
865
+ * @param event The websocket event name
866
+ * @param data The event's payload
867
+ *
868
+ * @returns The data returned by the backend
869
+ * @throws An error related to backend's rejection
870
+ *
871
+ * @category Transport
872
+ * @async
873
+ * @hidden
874
+ */
875
+ const synchronousWSCall = async (client, event, data) => {
876
+ const { ws } = client;
877
+ const value = await new Promise((resolve, reject) => {
878
+ ws.emit(event, data, (response) => {
879
+ try {
880
+ resolve(unwrapPayload(response));
881
+ }
882
+ catch (error) {
883
+ reject(error);
884
+ }
885
+ });
886
+ });
887
+ return value;
888
+ };
889
+
890
+ // need to sync up the list
891
+ const EVENTS = [
892
+ 'disconnected',
893
+ 'v3.user.didUpdate',
894
+ 'v3.channel.didUpdate',
895
+ 'v3.channel.didUpdate',
896
+ 'v3.channel.didJoin',
897
+ 'v3.channel.didLeave',
898
+ 'v3.channel.didAddUsers',
899
+ 'v3.channel.didRemoveUsers',
900
+ 'v3.channel.didBan',
901
+ 'v3.channel.didUnban',
902
+ 'v3.message.didCreate',
903
+ 'v3.message.didUpdate',
904
+ 'v3.message.didDelete',
905
+ ];
906
+ /** @hidden */
907
+ const createEventEmitter = () => {
908
+ return mitt__default['default']();
909
+ };
910
+ /**
911
+ * Wraps the websocket events into the client's event emitter for
912
+ * abstraction of transport.
913
+ *
914
+ * @param ws A websocket connection to listen from
915
+ * @param emitter An event emitter to wire the events to
916
+ *
917
+ * @category Transport
918
+ * @hidden
919
+ */
920
+ const proxyWebsocketEvents = (ws, emitter) => {
921
+ EVENTS.forEach(event => {
922
+ ws.on(event, (param) => emitter.emit(event, param));
923
+ });
924
+ };
925
+ /**
926
+ * Standardize the subscription of SSE through web sockets
927
+ *
928
+ * @param client The current client for which to subscribe the event to
929
+ * @param namespace A unique name for the logger
930
+ * @param event The websocket event name
931
+ * @param fn A wrapper for the callback.
932
+ * @returns A dispose function to unsubscribe to the event
933
+ *
934
+ * @category Transport
935
+ * @hidden
936
+ */
937
+ const createEventSubscriber = (client, namespace, event, fn) => {
938
+ const { log, emitter } = client;
939
+ const timestamp = Date.now();
940
+ log(`${namespace}(tmpid: ${timestamp}) > listen`);
941
+ const handler = (...payload) => {
942
+ log(`${namespace}(tmpid: ${timestamp}) > trigger`, payload);
943
+ fn(...payload);
944
+ };
945
+ emitter.on(event, handler);
946
+ return () => {
947
+ log(`${namespace}(tmpid: ${timestamp}) > dispose`);
948
+ emitter.off(event, handler);
949
+ };
950
+ };
951
+ /**
952
+ * Wrapper around dispatch event
953
+ *
954
+ * @hidden
955
+ */
956
+ const fireEvent = (event, payload) => {
957
+ const { emitter } = getActiveClient();
958
+ setTimeout(() => { emitter.emit(event, payload); }, 0);
959
+ };
960
+
961
+ /**
962
+ * ```js
963
+ * import { createClient } from '@amityco/ts-sdk'
964
+ * const client = createClient(apiKey, 'https://asc.server/', 'myClient')
965
+ * ```
966
+ *
967
+ * Creates a new {@link Amity.Client} instance
968
+ *
969
+ * @param apiKey for the {@link Amity.Client} instance
970
+ * @param apiEndpoint endpoint to connect to
971
+ * @param debugSession session's identifier for the client's logger instance
972
+ * @returns A {@link Amity.Client} instance
973
+ *
974
+ * @category Client API
975
+ **/
976
+ const createClient = (apiKey, apiEndpoint = 'https://api.amity.co', debugSession = 'amity') => {
977
+ const log = createLogger(debugSession);
978
+ log('client/api/createClient', {
979
+ apiKey: apiKey.replace(/.{5}$/g, 'xxxxx'),
980
+ apiEndpoint,
981
+ });
982
+ const http = createHttpTransport(apiEndpoint);
983
+ const ws = createWebsocketTransport(apiEndpoint);
984
+ const emitter = createEventEmitter();
985
+ const client = {
986
+ apiKey, log, http, ws, emitter,
987
+ use: () => setActiveClient(client),
988
+ };
989
+ try {
990
+ getActiveClient();
991
+ }
992
+ catch (_a) {
993
+ setActiveClient(client);
994
+ }
995
+ return client;
996
+ };
997
+
998
+ // TODO: find a way to uniquely identify the device
999
+ // import { getStorage } from './storage'
1000
+ /** @hidden */
1001
+ const VERSION = '11.0.0';
1002
+ /** @hidden */
1003
+ const getDeviceId = () => {
1004
+ // here maybe put some auto detection of the device id based on if it's react or not?
1005
+ // anyhow we let consumer branch out if they want, but it doesn't mean we shouldn't try to be nice
1006
+ // and do things automatically
1007
+ // https://www.npmjs.com/package/react-native-device-info#getuniqueid
1008
+ // how to make sure that the react native package will not be included when build is for web
1009
+ return `ascWebSdk#${Math.random().toString(16)}`;
1010
+ };
1011
+ /** @hidden */
1012
+ const getDeviceModel = () => {
1013
+ var _a, _b;
1014
+ if ((_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node)
1015
+ return process.versions.node;
1016
+ if (navigator)
1017
+ return `${navigator.product.toLowerCase()}#${(_b = navigator.userAgent) !== null && _b !== void 0 ? _b : 'unknown_agent'}`;
1018
+ return 'unknown_model';
1019
+ };
1020
+ /** @hidden */
1021
+ const getDeviceInfo = () => {
1022
+ const model = getDeviceModel();
1023
+ return {
1024
+ version: VERSION,
1025
+ // TODO: replace with: kind: process.versions ? 'node' : 'web', when backend has fixed this
1026
+ kind: 'web',
1027
+ model,
1028
+ };
1029
+ };
1030
+
1031
+ /**
1032
+ * Retrieves a pair of {@link Amity.Tokens} necessary for connection
1033
+ *
1034
+ * @param userId The userId to use to issue a token
1035
+ * @param displayName The user's displayName
1036
+ * @param deviceId The user's device Id (can be manually set for native users)
1037
+ * @param authToken The authentication token - necessary when network option is set to secure
1038
+ * @return The accessToken for the given userId
1039
+ *
1040
+ * @category Client API
1041
+ * @hidden
1042
+ */
1043
+ const getToken = async (params) => {
1044
+ const client = getActiveClient();
1045
+ client.log('client/api/getToken', params);
1046
+ const deviceInfo = await getDeviceInfo();
1047
+ const { data } = await client.http.post('/v1/device', Object.assign(Object.assign({}, params), { deviceInfo }), {
1048
+ headers: { 'X-API-Key': client.apiKey }
1049
+ });
1050
+ return data;
1051
+ };
1052
+
1053
+ /**
1054
+ * ```js
1055
+ * import { connectClient } from '@amityco/ts-sdk/client/api'
1056
+ * const success = await connectClient({
1057
+ * userId: 'XYZ123456789',
1058
+ * })
1059
+ * ```
1060
+ *
1061
+ * Connects an {@link Amity.Client} instance to ASC servers
1062
+ *
1063
+ * @param userId the user ID for the current session
1064
+ * @param displayName the user's displayName for the current session
1065
+ * @param deviceId Manual override of the user's device id (for device management)
1066
+ * @param authToken The authentication token - necessary when network option is set to secure
1067
+ * @returns a success boolean if connected
1068
+ *
1069
+ * @category Client API
1070
+ * @async
1071
+ */
1072
+ const connectClient = async (params) => {
1073
+ var _a, _b;
1074
+ const client = getActiveClient();
1075
+ client.log('client/api/connectClient', Object.assign({ apiKey: client.apiKey }, params));
1076
+ // default values
1077
+ (_a = params.displayName) !== null && _a !== void 0 ? _a : (params.displayName = params.userId);
1078
+ (_b = params.deviceId) !== null && _b !== void 0 ? _b : (params.deviceId = getDeviceId());
1079
+ // @ts-ignore: in that particular case, typing can be
1080
+ // ignored since we enforce default values just before.
1081
+ const { accessToken } = await getToken(params);
1082
+ // manually setup the token for http transport
1083
+ client.http.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
1084
+ // manually setup the token for ws transport
1085
+ client.ws.io.opts.query = { token: accessToken };
1086
+ // wire websocket events to our event emitter
1087
+ proxyWebsocketEvents(client.ws, client.emitter);
1088
+ // TODO: in phase 2, this should not be necessary. we should have WS
1089
+ // to be connected "on demand" rather than "by default"
1090
+ await new Promise(resolve => {
1091
+ client.ws.once('connect', resolve);
1092
+ client.ws.open();
1093
+ });
1094
+ client.userId = params.userId;
1095
+ return client.ws.connected;
1096
+ };
1097
+
1098
+ /**
1099
+ * ```js
1100
+ * import { disconnectClient } from '@amityco/ts-sdk'
1101
+ * const success = await disconnectClient()
1102
+ * ```
1103
+ *
1104
+ * Disconnects an {@link Amity.Client} instance from ASC servers
1105
+ *
1106
+ * @param client The {@link Amity.Client} instance to disconnect
1107
+ * @returns a success boolean if disconnected
1108
+ *
1109
+ * @category Client API
1110
+ * @async
1111
+ */
1112
+ const disconnectClient = async () => {
1113
+ const client = getActiveClient();
1114
+ client.log('client/api/disconnectClient');
1115
+ await new Promise(resolve => {
1116
+ client.ws.once('disconnect', resolve);
1117
+ client.ws.disconnect();
1118
+ });
1119
+ client.emitter.all.clear();
1120
+ client.ws.removeAllListeners();
1121
+ client.userId = undefined;
1122
+ return !client.ws.connected;
1123
+ };
1124
+
1125
+ /**
1126
+ * ```js
1127
+ * import { isConnected } from '@amityco/ts-sdk'
1128
+ * const connected = isConnected()
1129
+ * ```
1130
+ *
1131
+ * Checks if a {@link Amity.Client} instance is connected to ASC servers
1132
+ *
1133
+ * @returns a success boolean if connected
1134
+ *
1135
+ * @category Client API
1136
+ */
1137
+ const isConnected = () => {
1138
+ var _a, _b;
1139
+ const client = getActiveClient();
1140
+ client.log('client/api/isConnected', client);
1141
+ return !!(client.userId
1142
+ && ((_b = (_a = client.http.defaults.headers.common) === null || _a === void 0 ? void 0 : _a['Authorization']) === null || _b === void 0 ? void 0 : _b.length)
1143
+ && client.ws.connected);
1144
+ };
1145
+
1146
+ /**
1147
+ * Minimal store implementation.
1148
+ *
1149
+ * Beware, the state is mutable! it is your responsibility
1150
+ * handle the state's mutations correctly. We do so in
1151
+ * order for users with mutable/observable stacks to be able
1152
+ * to decorate the state with their favorite libraries.
1153
+ *
1154
+ * @param defaultValue the hydration state value of the store
1155
+ * @returns A store instance with an "in memory" storage strategy
1156
+ *
1157
+ * @category Storage
1158
+ * @hidden
1159
+ */
1160
+ const memoryStore = (defaultValue = {}) => {
1161
+ const state = defaultValue;
1162
+ /* default read operation is just to return the state */
1163
+ const read = () => state;
1164
+ /* default write operation is just to mutate the state */
1165
+ const write = (payload) => {
1166
+ Object.assign(state, payload);
1167
+ };
1168
+ /* default write operation is just to mutate the state */
1169
+ const erase = (...keys) => {
1170
+ if (!keys.length)
1171
+ keys = Object.keys(state);
1172
+ keys.forEach(key => delete state[key]);
1173
+ };
1174
+ return { read, write, erase };
1175
+ };
1176
+ /**
1177
+ * ```js
1178
+ * import { memoryStores } from '@amityco/core/cache/store/volatile'
1179
+ * const stores = imemoryStores('user', 'file')
1180
+ * ```
1181
+ *
1182
+ * Builds a collection of in memory stores based on the available store names
1183
+ *
1184
+ * @param names collection of store names
1185
+ * @returns a dictionary of { storeName: storeInstance } according to the given names
1186
+ *
1187
+ * @category Storage
1188
+ */
1189
+ const memoryStores = (...names) => {
1190
+ return names.reduce((acc, name) => {
1191
+ const store = memoryStore();
1192
+ return Object.assign(Object.assign({}, acc), { [name]: store });
1193
+ }, {});
1194
+ };
1195
+
1196
+ const DEFAULT_DEBOUNCE_TIME = 250;
1197
+ /**
1198
+ * Persistent store implementation.
1199
+ *
1200
+ * @param persistentKey the name of the store in persistent storage
1201
+ * @param defaultValue the hydration state value of the store
1202
+ * @param debounceTime a delay to avoid spamming the persistent storage while writing,
1203
+ * @returns A store instance with an "persistent" storage strategy
1204
+ *
1205
+ * @category Storage
1206
+ * @hidden
1207
+ */
1208
+ const persistentStore = async (persistentKey, defaultValue = {}, debounceTime = DEFAULT_DEBOUNCE_TIME) => {
1209
+ let initialValue = defaultValue;
1210
+ const serializedBackup = await AsyncStorage__default['default'].getItem(persistentKey);
1211
+ if (serializedBackup) {
1212
+ try {
1213
+ initialValue = JSON.parse(serializedBackup);
1214
+ }
1215
+ catch (err) { }
1216
+ }
1217
+ // create a store
1218
+ const store = memoryStore(initialValue);
1219
+ let timer;
1220
+ let job = null;
1221
+ const backup = () => {
1222
+ if (job) {
1223
+ job.then(() => backup());
1224
+ return;
1225
+ }
1226
+ clearTimeout(timer);
1227
+ setTimeout(async () => {
1228
+ job = Promise.resolve()
1229
+ .then(() => AsyncStorage__default['default'].setItem(persistentKey, JSON.stringify(store.read())))
1230
+ .then(() => job = null);
1231
+ }, debounceTime);
1232
+ };
1233
+ const write = (payload) => {
1234
+ store.write(payload);
1235
+ backup();
1236
+ };
1237
+ const erase = (...keys) => {
1238
+ store.erase(...keys);
1239
+ backup();
1240
+ };
1241
+ return { read: store.read, write, erase };
1242
+ };
1243
+
1244
+ /**
1245
+ * ```js
1246
+ * import { enableCache } from '@amityco/ts-sdk'
1247
+ * enableCache()
1248
+ * ```
1249
+ *
1250
+ * Adds a new {@link Amity.Cache} object to an {@link Amity.Client} instance
1251
+ *
1252
+ * @param stores a partial dictionary of stores to be used for caching
1253
+ *
1254
+ * @category Client API
1255
+ */
1256
+ const enableCache = (stores = memoryStores('user', 'file', 'channel', 'message', 'community', 'post', 'comment', 'communityUsers', 'channelUsers')) => {
1257
+ const client = getActiveClient();
1258
+ client.log('client/api/enableCache');
1259
+ client.cache = createCache(stores);
1260
+ };
1261
+
1262
+ /**
1263
+ * ```js
1264
+ * import { clearCache } from '@amityco/ts-sdk'
1265
+ * clearCache()
1266
+ * ```
1267
+ *
1268
+ * Resets the state of the given {@link Amity.Store} names within
1269
+ * the {@link Amity.Cache} object of a {@link Amity.Client} instance
1270
+ *
1271
+ * @param stores an array of the stores names to be wiped
1272
+ *
1273
+ * @category Client API
1274
+ */
1275
+ const clearCache = (stores = ['user', 'file', 'channel', 'message', 'community', 'post', 'comment']) => {
1276
+ const client = getActiveClient();
1277
+ client.log('client/api/enableCache');
1278
+ stores.forEach(store => { var _a, _b; return (_b = (_a = client.cache) === null || _a === void 0 ? void 0 : _a[store]) === null || _b === void 0 ? void 0 : _b.erase(); });
1279
+ };
1280
+
1281
+ /**
1282
+ * converts an array looking collection to an object collection, grouped by localId
1283
+ *
1284
+ * @param array array of {@link Amity.Syncable}
1285
+ * @returns array converted to object, grouped by localId
1286
+ *
1287
+ * @hidden
1288
+ */
1289
+ const toRecord = (array) => (array.reduce((acc, item) => (Object.assign(Object.assign({}, acc), { [item.localId]: item })), {}));
1290
+
1291
+ /**
1292
+ * Set the model's syncedAt property and localId
1293
+ *
1294
+ * @param model the model to decorate
1295
+ * @param timestamp the given timestamp
1296
+ */
1297
+ const decoratePayload = (payload, timestamp = Date.now(), keyMapping = storeInterests) => {
1298
+ Object.fromEntries(Object.entries(payload)
1299
+ .map(([key, models]) => ([
1300
+ key, decorateModels(models, timestamp, keyMapping[key])
1301
+ ])));
1302
+ };
1303
+ /**
1304
+ * Set the model's syncedAt property and localId
1305
+ *
1306
+ * @param model the model to decorate
1307
+ * @param timestamp the given timestamp
1308
+ */
1309
+ const decorateModels = (models, timestamp = Date.now(), type) => {
1310
+ models.forEach(model => decorateModel(model, timestamp, type));
1311
+ };
1312
+ /**
1313
+ * Set the model's syncedAt property and localId
1314
+ *
1315
+ * @param model the model to decorate
1316
+ * @param syncedAt the given timestamp
1317
+ * @param type An opportunity to manually pass the type. If undefined, it will be smartly computed
1318
+ */
1319
+ const decorateModel = (model, timestamp = Date.now(), type = identifyModel(model)) => {
1320
+ var _a, _b;
1321
+ (_a = model.syncedAt) !== null && _a !== void 0 ? _a : (model.syncedAt = timestamp);
1322
+ const { cache } = getActiveClient();
1323
+ if (type) {
1324
+ const modelId = getResolver(type)(model);
1325
+ model.localId = (_b = cache === null || cache === void 0 ? void 0 : cache.lookup[`${type}#${modelId}`]) !== null && _b !== void 0 ? _b : uuid();
1326
+ }
1327
+ };
1328
+
1329
+ // Note:
1330
+ // this file should contain a suite of filtering utilities to help the
1331
+ // local version of the query functions.
1332
+ /**
1333
+ * Filter a given collection with strict equality against a param
1334
+ *
1335
+ * @param collection the collection to filter
1336
+ * @param key the key of the collection's items to challenge
1337
+ * @param value the expected value
1338
+ * @returns a filtered collection with items only matching the criteria
1339
+ *
1340
+ * @hidden
1341
+ */
1342
+ const filterByPropEquality = (collection, key, value) => (value !== undefined ? collection.filter(item => item[key] === value) : collection);
1343
+
1344
+ // Note:
1345
+ // this file should contain a suite of sorting utilities to help the
1346
+ // local version of the query functions.
1347
+ /**
1348
+ * Alphabetic sorting of objects having a displayName
1349
+ */
1350
+ const sortByDisplayName = ({ displayName: a }, { displayName: b }) => {
1351
+ if (a === b)
1352
+ return 0;
1353
+ return a < b ? -1 : 1;
1354
+ };
1355
+ /**
1356
+ * Sorting a collection by their apparition order (oldest first)
1357
+ */
1358
+ const sortByChannelSegment = ({ channelSegment: a }, { channelSegment: b }) => a - b;
1359
+ /**
1360
+ * Sorting a collection by their apparition order (oldest first)
1361
+ */
1362
+ const sortBySegmentNumber = ({ segmentNumber: a }, { segmentNumber: b }) => a - b;
1363
+ /**
1364
+ * Sorting a collection by its oldest items
1365
+ */
1366
+ const sortByFirstCreated = ({ createdAt: a }, { createdAt: b }) => new Date(a).valueOf() - new Date(b).valueOf();
1367
+ /**
1368
+ * Sorting a collection by its newest items
1369
+ */
1370
+ const sortByLastCreated = ({ createdAt: a }, { createdAt: b }) => new Date(b).valueOf() - new Date(a).valueOf();
1371
+ /**
1372
+ * Sorting a collection by the items with most recent activity
1373
+ */
1374
+ const sortByLastActivity = ({ lastActivity: a }, { lastActivity: b }) => new Date(b).valueOf() - new Date(a).valueOf();
1375
+
1376
+ /**
1377
+ * ```js
1378
+ * import { onClientDisconnected } from '@amityco/ts-sdk'
1379
+ * const dispose = onClientDisconnected(reason => {
1380
+ * // ...
1381
+ * })
1382
+ * ```
1383
+ *
1384
+ * Fired when any {@link Amity.Client} have been disconnected
1385
+ *
1386
+ * @param callback The function to call when the event was fired
1387
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1388
+ *
1389
+ * @category Client Events
1390
+ */
1391
+ const onClientDisconnected = (callback) => {
1392
+ return createEventSubscriber(getActiveClient(), 'client/onClientDisconnected', 'disconnected', () => callback());
1393
+ };
1394
+
1395
+ /**
1396
+ * ```js
1397
+ * import { getUser } from '@amityco/ts-sdk'
1398
+ * const user = await getUser('foobar')
1399
+ * ```
1400
+ *
1401
+ * Fetches a {@link Amity.User} object
1402
+ *
1403
+ * @param userId the ID of the {@link Amity.User} to fetch
1404
+ * @returns the associated {@link Amity.User} object
1405
+ *
1406
+ * @category User API
1407
+ * @async
1408
+ */
1409
+ const getUser = async (userId) => {
1410
+ const client = getActiveClient();
1411
+ client.log('user/getUser', userId);
1412
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
1413
+ const { data } = await client.http.get(`/api/v3/users/${userId}`);
1414
+ decoratePayload(data);
1415
+ ingestInCache(data);
1416
+ const { users } = data;
1417
+ return users.find(user => user.userId === userId);
1418
+ };
1419
+ /**
1420
+ * ```js
1421
+ * import { getUser } from '@amityco/ts-sdk'
1422
+ * const user = getUser.locally('foobar')
1423
+ * ```
1424
+ *
1425
+ * Fetches a {@link Amity.User} object from cache
1426
+ *
1427
+ * @param userId the ID of the {@link Amity.User} to fetch
1428
+ * @returns the associated {@link Amity.User} object
1429
+ *
1430
+ * @category User API
1431
+ */
1432
+ getUser.locally = (userId) => {
1433
+ var _a;
1434
+ const client = getActiveClient();
1435
+ client.log('user/getUser.locally', userId);
1436
+ const [user] = (_a = pullFromCache('user', userId)) !== null && _a !== void 0 ? _a : [];
1437
+ return user;
1438
+ };
1439
+
1440
+ /**
1441
+ * ```js
1442
+ * import { getUsers } from '@amityco/ts-sdk'
1443
+ * const users = await getUsers(['foo', 'bar'])
1444
+ * ```
1445
+ *
1446
+ * Fetches a collection of {@link Amity.User} objects
1447
+ *
1448
+ * @param userIds the IDs of the {@link Amity.User} to fetch
1449
+ * @returns the associated collection of {@link Amity.User} objects
1450
+ *
1451
+ * @category User API
1452
+ * @async
1453
+ */
1454
+ const getUsers = async (userIds) => {
1455
+ const client = getActiveClient();
1456
+ client.log('user/getUsers', userIds);
1457
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
1458
+ const { data } = await client.http.get(`/api/v3/users/list`, { params: { userIds } });
1459
+ decoratePayload(data);
1460
+ ingestInCache(data);
1461
+ const { users } = data;
1462
+ return toRecord(users);
1463
+ };
1464
+ /**
1465
+ * ```js
1466
+ * import { getUsers } from '@amityco/ts-sdk'
1467
+ * const users = getUsers.locally!(['foo', 'bar'])
1468
+ * ```
1469
+ *
1470
+ * Fetches a collection of {@link Amity.User} objects from cache
1471
+ *
1472
+ * @param userIds the IDs of the {@link Amity.User} to fetch
1473
+ * @returns the associated collection of {@link Amity.User} objects
1474
+ *
1475
+ * @category User API
1476
+ */
1477
+ getUsers.locally = (userIds) => {
1478
+ var _a;
1479
+ const cached = (_a = pullFromCache('user', ...userIds)) !== null && _a !== void 0 ? _a : [];
1480
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) === userIds.length)
1481
+ return toRecord(cached);
1482
+ };
1483
+
1484
+ /*! *****************************************************************************
1485
+ Copyright (c) Microsoft Corporation.
1486
+
1487
+ Permission to use, copy, modify, and/or distribute this software for any
1488
+ purpose with or without fee is hereby granted.
1489
+
1490
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1491
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1492
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1493
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1494
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1495
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1496
+ PERFORMANCE OF THIS SOFTWARE.
1497
+ ***************************************************************************** */
1498
+
1499
+ function __rest(s, e) {
1500
+ var t = {};
1501
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
1502
+ t[p] = s[p];
1503
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
1504
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
1505
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
1506
+ t[p[i]] = s[p[i]];
1507
+ }
1508
+ return t;
1509
+ }
1510
+
1511
+ /**
1512
+ * ```js
1513
+ * import { queryUsers } from '@amityco/ts-sdk'
1514
+ * const { users, previous, next } = await queryUsers({ keyword: 'foo' })
1515
+ * ```
1516
+ *
1517
+ * Queries a paginable list of {@link Amity.User} objects
1518
+ * Search is performed by displayName such as `.startsWith(search)`
1519
+ *
1520
+ * @param query The query parameters
1521
+ * @returns A page of {@link Amity.User} objects
1522
+ *
1523
+ * @category User API
1524
+ * @async
1525
+ */
1526
+ const queryUsers = async (query) => {
1527
+ const client = getActiveClient();
1528
+ client.log('user/queryUsers', query);
1529
+ const _a = query !== null && query !== void 0 ? query : {}, { page, displayName, filter = 'all', sortBy = 'displayName' } = _a, params = __rest(_a, ["page", "displayName", "filter", "sortBy"]);
1530
+ // API-FIX: parameters should be querystring.
1531
+ const { data } = await client.http.get(`/api/v3/users`, { params: Object.assign(Object.assign({}, params), { keyword: displayName, filter,
1532
+ sortBy, options: {
1533
+ token: toToken(page, 'skiplimit'),
1534
+ } }) });
1535
+ // unpacking
1536
+ const { paging } = data, response = __rest(data, ["paging"]);
1537
+ decoratePayload(response);
1538
+ ingestInCache(response);
1539
+ const prevPage = toPage(paging.previous);
1540
+ const nextPage = toPage(paging.next);
1541
+ const { users } = response;
1542
+ return { data: toRecord(users), prevPage, nextPage };
1543
+ };
1544
+ /**
1545
+ * ```js
1546
+ * import { queryUsers } from '@amityco/ts-sdk'
1547
+ * const users = queryUsers.locally({ keyword: 'foo' })
1548
+ * ```
1549
+ *
1550
+ * Queries a paginable list of {@link Amity.User} objects from cache
1551
+ * Search is performed by displayName such as `.startsWith(search)`
1552
+ *
1553
+ * @param query The query parameters
1554
+ * @returns A page of {@link Amity.User} objects
1555
+ *
1556
+ * @category User API
1557
+ */
1558
+ queryUsers.locally = (query) => {
1559
+ const client = getActiveClient();
1560
+ client.log('user/queryUsers.locally', query);
1561
+ // TODO
1562
+ };
1563
+
1564
+ /**
1565
+ * ```js
1566
+ * import { updateUser } from '@amityco/ts-sdk'
1567
+ * const updated = await updateUser(userId, { displayName: 'foobar' })
1568
+ * ```
1569
+ *
1570
+ * Updates an {@link Amity.User}
1571
+ *
1572
+ * @param userId The ID of the {@link Amity.User} to update
1573
+ * @param patch The patch data to apply
1574
+ * @returns the updated {@link Amity.User} object
1575
+ *
1576
+ * @category User API
1577
+ * @async
1578
+ */
1579
+ const updateUser = async (userId, patch) => {
1580
+ const client = getActiveClient();
1581
+ client.log('user/updateUser', userId, patch);
1582
+ // API-FIX: Endpoint is malformed, userId should be a url param.
1583
+ /*
1584
+ const { data } = await client.http.put<Amity.Response<UserPayload>>(
1585
+ `/api/v3/users/${userId}`, patch,
1586
+ )
1587
+ */
1588
+ const { data } = await client.http.put(`/api/v3/users/`, Object.assign(Object.assign({ userId }, patch), { createNewUserWhenNotFound: false }));
1589
+ decoratePayload(data);
1590
+ ingestInCache(data);
1591
+ // no need for event, fired by server
1592
+ return data.users.find(user => user.userId === userId);
1593
+ };
1594
+
1595
+ /**
1596
+ * ```js
1597
+ * import { onUserUpdated } from '@amityco/ts-sdk'
1598
+ * const dispose = onUserUpdated(user => {
1599
+ * // ...
1600
+ * })
1601
+ * ```
1602
+ *
1603
+ * Fired when any {@link Amity.User} have been updated
1604
+ *
1605
+ * @param callback The function to call when the event was fired
1606
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1607
+ *
1608
+ * @category User Events
1609
+ */
1610
+ const onUserUpdated = (callback) => {
1611
+ const client = getActiveClient();
1612
+ const filter = (payload) => {
1613
+ decoratePayload(payload);
1614
+ ingestInCache(payload);
1615
+ callback(payload.users[0]);
1616
+ };
1617
+ return createEventSubscriber(client, 'user/onUserUpdate', 'v3.user.didUpdate', filter);
1618
+ };
1619
+
1620
+ /**
1621
+ * ```js
1622
+ * import { observeUser } from '@amityco/ts-sdk'
1623
+ *
1624
+ * let user = {}
1625
+ * const dispose = observeUser(userId, updated => user = updated)
1626
+ * ```
1627
+ *
1628
+ * @param userId the ID of the user to observe
1629
+ * @param callback the function to call when new data are available
1630
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the user
1631
+ *
1632
+ * Observe all mutation on a given {@link Amity.User}
1633
+ * @category User Observer
1634
+ */
1635
+ const observeUser = (userId, callback) => {
1636
+ const { log } = getActiveClient();
1637
+ const timestamp = Date.now();
1638
+ log(`observeUser(tmpid: ${timestamp}) > listen`);
1639
+ // wrapper function to make sure
1640
+ const router = (result, action) => {
1641
+ var _a, _b, _c;
1642
+ // filter function
1643
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.userId) !== userId)
1644
+ return;
1645
+ if (callback instanceof Function)
1646
+ return callback(result);
1647
+ if (action !== 'onFetch')
1648
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
1649
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
1650
+ };
1651
+ const disposers = [];
1652
+ disposers.push(onUserUpdated(data => router({ data }, 'onUpdate')));
1653
+ runQuery(createQuery(getUser, userId), (result) => result.data && router(result, 'onFetch'));
1654
+ return () => {
1655
+ log(`observeUser(tmpid: ${timestamp}) > dispose`);
1656
+ disposers.forEach(fn => fn());
1657
+ };
1658
+ };
1659
+
1660
+ /**
1661
+ * ```js
1662
+ * import { getFile } from '@amityco/ts-sdk'
1663
+ * const file = await getFile('foo')
1664
+ * ```
1665
+ *
1666
+ * Fetches a {@link Amity.File} object
1667
+ *
1668
+ * @param filelId the ID of the {@link Amity.File} to fetch
1669
+ * @returns the associated {@link Amity.File} object
1670
+ *
1671
+ * @category File API
1672
+ * @async
1673
+ */
1674
+ const getFile = async (fileId) => {
1675
+ const client = getActiveClient();
1676
+ client.log('file/getFile', fileId);
1677
+ const { data } = await client.http.get(`/api/v3/files/${fileId}`);
1678
+ // API-FIX: backend bad serializer issue. it should be:
1679
+ // const { files } = data
1680
+ decorateModel(data);
1681
+ ingestInCache({ files: [data] });
1682
+ return data;
1683
+ };
1684
+ /**
1685
+ * ```js
1686
+ * import { getFile } from '@amityco/ts-sdk'
1687
+ * const file = getFile.locally('foo')
1688
+ * ```
1689
+ *
1690
+ * Fetches a {@link Amity.File} object from cache
1691
+ *
1692
+ * @param fileId the ID of the {@link Amity.File} to fetch
1693
+ * @returns the associated {@link Amity.File} object
1694
+ *
1695
+ * @category File API
1696
+ */
1697
+ getFile.locally = (fileId) => {
1698
+ var _a;
1699
+ const client = getActiveClient();
1700
+ client.log('file/getFile.locally', fileId);
1701
+ const [file] = (_a = pullFromCache('file', fileId)) !== null && _a !== void 0 ? _a : [];
1702
+ return file;
1703
+ };
1704
+
1705
+ /**
1706
+ * ```js
1707
+ * import { createFile } from '@amityco/ts-sdk'
1708
+ * const created = await createFile(formData)
1709
+ * ```
1710
+ *
1711
+ * Creates an {@link Amity.File}
1712
+ *
1713
+ * @param formData The data necessary to create a new {@link Amity.File}
1714
+ * @returns The newly created {@link Amity.File}
1715
+ *
1716
+ * @category File API
1717
+ * @async
1718
+ */
1719
+ const createFile = async (formData, onProgress) => {
1720
+ const client = getActiveClient();
1721
+ client.log('file/createFile', formData);
1722
+ if (!formData.getAll('file').length)
1723
+ throw new Error('The formData object must have a `file` key.');
1724
+ const headers = 'getHeaders' in formData
1725
+ ? formData.getHeaders()
1726
+ : { 'content-type': 'multipart/form-data' };
1727
+ const { data } = await client.http.post('/api/v3/files', formData, {
1728
+ headers, onUploadProgress({ loaded, total }) {
1729
+ onProgress && onProgress(Math.round((loaded * 100) / total));
1730
+ }
1731
+ });
1732
+ // API-FIX: payload should be serialized properly
1733
+ // const { files } = data
1734
+ decorateModels(data);
1735
+ ingestInCache({ files: data });
1736
+ return data[0];
1737
+ };
1738
+ // TODO: consider doing local creation with URL.createObjectURL()
1739
+
1740
+ /**
1741
+ * ```js
1742
+ * import { deleteFile } from '@amityco/ts-sdk'
1743
+ * const success = await deleteFile('foo')
1744
+ * ```
1745
+ *
1746
+ * Deletes a {@link Amity.File}
1747
+ *
1748
+ * @param fileId The {@link Amity.File} ID to delete
1749
+ * @return A success boolean if the {@link Amity.File} was deleted
1750
+ *
1751
+ * @category File API
1752
+ * @async
1753
+ */
1754
+ const deleteFile = async (fileId) => {
1755
+ const client = getActiveClient();
1756
+ client.log('file/deleteFile', fileId);
1757
+ const { data } = await client.http.delete(`/api/v3/files/${fileId}`);
1758
+ const { success } = data;
1759
+ if (success)
1760
+ mergeInCache('file', { fileId, isDeleted: true });
1761
+ return success;
1762
+ };
1763
+
1764
+ /**
1765
+ * Allow to query a file url with a selected size
1766
+ *
1767
+ * @param fileUrl the file Url to decorate
1768
+ * @param size one of the selected sizes
1769
+ * @returns the computed url for the selected size
1770
+ */
1771
+ const fileUrlWithSize = (fileUrl, size) => {
1772
+ return `${fileUrl}?size=${size}`;
1773
+ };
1774
+
1775
+ /**
1776
+ * ```js
1777
+ * import { observeFile } from '@amityco/ts-sdk'
1778
+ *
1779
+ * let file = {}
1780
+ * const dispose = observeFile(fileId, updated => file = updated)
1781
+ * ```
1782
+ *
1783
+ * Observe all mutation on a given {@link Amity.File}
1784
+ *
1785
+ * @param fileId the ID of the file to observe
1786
+ * @param callback the function to call when new data are available
1787
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the file
1788
+ *
1789
+ * @category File Observer
1790
+ */
1791
+ const observeFile = (fileId, callback) => {
1792
+ const { log } = getActiveClient();
1793
+ const timestamp = Date.now();
1794
+ log(`observeFile(tmpid: ${timestamp}) > listen`);
1795
+ // wrapper function to make sure
1796
+ const router = (result, action) => {
1797
+ var _a, _b, _c;
1798
+ // filter function
1799
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.fileId) !== fileId)
1800
+ return;
1801
+ if (callback instanceof Function)
1802
+ return callback(result);
1803
+ if (action !== 'onFetch')
1804
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
1805
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
1806
+ };
1807
+ runQuery(createQuery(getFile, fileId), (result) => result.data && router(result, 'onFetch'));
1808
+ return () => {
1809
+ log(`observeFile(tmpid: ${timestamp}) > dispose`);
1810
+ };
1811
+ };
1812
+
1813
+ /**
1814
+ * ```js
1815
+ * import { queryRoles } from '@amityco/ts-sdk'
1816
+ * const roles = await queryRoles()
1817
+ * ```
1818
+ *
1819
+ * Queries a paginable list of {@link Amity.Role} objects
1820
+ * Search is performed by displayName such as `.startsWith(search)`
1821
+ *
1822
+ * @param query The query parameters
1823
+ * @returns A page of {@link Amity.Role} objects
1824
+ *
1825
+ * @category Role API
1826
+ * @async
1827
+ */
1828
+ const queryRoles = async (query) => {
1829
+ const client = getActiveClient();
1830
+ client.log('role/queryRoles', query);
1831
+ const _a = query !== null && query !== void 0 ? query : {}, { page, displayName, sortBy } = _a, params = __rest(_a, ["page", "displayName", "sortBy"]);
1832
+ // API-FIX: parameters should be querystring.
1833
+ const { data } = await client.http.get(`/api/v3/roles`, {
1834
+ params: Object.assign(Object.assign({}, params), { keyword: displayName, sortBy, options: {
1835
+ token: toToken(page, 'skiplimit'),
1836
+ } }),
1837
+ });
1838
+ // unpacking
1839
+ const { paging } = data, response = __rest(data, ["paging"]);
1840
+ decoratePayload(response);
1841
+ ingestInCache(response);
1842
+ const prevPage = toPage(paging.previous);
1843
+ const nextPage = toPage(paging.next);
1844
+ const { roles } = response;
1845
+ return { data: toRecord(roles), prevPage, nextPage };
1846
+ };
1847
+ /**
1848
+ * ```js
1849
+ * import { queryRoles } from '@amityco/ts-sdk'
1850
+ * const roles = queryRoles.locally({ keyword: 'foo' })
1851
+ * ```
1852
+ *
1853
+ * Queries a paginable list of {@link Amity.Role} objects from cache
1854
+ * Search is performed by displayName such as `.startsWith(search)`
1855
+ *
1856
+ * @param query The query parameters
1857
+ * @returns A page of {@link Amity.Role} objects
1858
+ *
1859
+ * @category Role API
1860
+ */
1861
+ queryRoles.locally = (query) => {
1862
+ const client = getActiveClient();
1863
+ client.log('role/queryRoles.locally', query);
1864
+ // TODO
1865
+ };
1866
+
1867
+ /**
1868
+ * ```js
1869
+ * import { getRole } from '@amityco/ts-sdk'
1870
+ * const role = await getRole('foobar')
1871
+ * ```
1872
+ *
1873
+ * Fetches a {@link Amity.Role} object
1874
+ *
1875
+ * @param roleId the ID of the {@link Amity.Role} to fetch
1876
+ * @returns the associated {@link Amity.Role} object
1877
+ *
1878
+ * @category Role API
1879
+ * @async
1880
+ */
1881
+ const getRole = async (roleId) => {
1882
+ const client = getActiveClient();
1883
+ client.log('role/getRole', roleId);
1884
+ const { data } = await client.http.get(`/api/v3/roles/${roleId}`);
1885
+ decorateModels(data);
1886
+ ingestInCache({ roles: data });
1887
+ return data.find(role => role.roleId === roleId);
1888
+ };
1889
+ /**
1890
+ * ```js
1891
+ * import { getRole } from '@amityco/ts-sdk'
1892
+ * const role = getRole.locally('foobar')
1893
+ * ```
1894
+ *
1895
+ * Fetches a {@link Amity.Role} object from cache
1896
+ *
1897
+ * @param roleId the ID of the {@link Amity.Role} to fetch
1898
+ * @returns the associated {@link Amity.Role} object
1899
+ *
1900
+ * @category Role API
1901
+ */
1902
+ getRole.locally = (roleId) => {
1903
+ var _a;
1904
+ const client = getActiveClient();
1905
+ client.log('role/getRole.locally', roleId);
1906
+ const [role] = (_a = pullFromCache('role', roleId)) !== null && _a !== void 0 ? _a : [];
1907
+ return role;
1908
+ };
1909
+
1910
+ /** @hidden */
1911
+ const dispatchReactable = (referenceType, model) => {
1912
+ if (referenceType === 'message')
1913
+ // @ts-ignore: refactor later
1914
+ fireEvent('v3.message.didUpdate', { messages: [model] });
1915
+ else if (referenceType === 'post')
1916
+ // @ts-ignore: refactor later
1917
+ fireEvent('v3.post.didUpdate', { posts: [model] });
1918
+ else if (referenceType === 'comment')
1919
+ // @ts-ignore: refactor later
1920
+ fireEvent('v3.comment.didUpdate', { comments: [model] });
1921
+ };
1922
+
1923
+ /**
1924
+ * ```js
1925
+ * import { getMessage } from '@amityco/ts-sdk'
1926
+ * const message = await getMessage('foobar')
1927
+ * ```
1928
+ *
1929
+ * Fetches a {@link Amity.Message} object
1930
+ *
1931
+ * @param messageId the ID of the {@link Amity.Message} to fetch
1932
+ * @returns the associated {@link Amity.Message} object
1933
+ *
1934
+ * @category Message API
1935
+ * @async
1936
+ */
1937
+ const getMessage = async (messageId) => {
1938
+ const client = getActiveClient();
1939
+ client.log('message/getMessage', messageId);
1940
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
1941
+ const { data } = await client.http.get(`/api/v3/messages/${messageId}`);
1942
+ decoratePayload(data);
1943
+ ingestInCache(data);
1944
+ const { messages } = data;
1945
+ return messages.find(message => message.messageId === messageId);
1946
+ };
1947
+ /**
1948
+ * ```js
1949
+ * import { getMessage } from '@amityco/ts-sdk'
1950
+ * const message = getMessage.locally('foobar')
1951
+ * ```
1952
+ *
1953
+ * Fetches a {@link Amity.Message} object
1954
+ *
1955
+ * @param messageId the ID of the {@link Amity.Message} to fetch
1956
+ * @returns the associated {@link Amity.Message} object
1957
+ *
1958
+ * @category Message API
1959
+ */
1960
+ getMessage.locally = (messageId) => {
1961
+ var _a;
1962
+ const client = getActiveClient();
1963
+ client.log('message/getMessage.locally', messageId);
1964
+ const [message] = (_a = pullFromCache('message', messageId)) !== null && _a !== void 0 ? _a : [];
1965
+ return message;
1966
+ };
1967
+
1968
+ /**
1969
+ * ```js
1970
+ * import { getMessages } from '@amityco/ts-sdk'
1971
+ * const messages = await getMessages(['foo', 'bar'])
1972
+ * ```
1973
+ *
1974
+ * Fetches a collection of {@link Amity.Message} objects
1975
+ *
1976
+ * @param messageIds the IDs of the {@link Amity.Message} to fetch
1977
+ * @returns the associated collection of {@link Amity.Message} objects
1978
+ *
1979
+ * @category Message API
1980
+ * @async
1981
+ */
1982
+ const getMessages = async (messageIds) => {
1983
+ const client = getActiveClient();
1984
+ client.log('message/getMessages', messageIds);
1985
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
1986
+ const { data } = await client.http.get(`/api/v3/messages/list`, { params: { messageIds } });
1987
+ decoratePayload(data);
1988
+ ingestInCache(data);
1989
+ const { messages } = data;
1990
+ return toRecord(messages);
1991
+ };
1992
+ /**
1993
+ * ```js
1994
+ * import { getMessages } from '@amityco/ts-sdk'
1995
+ * const messages = getMessages.locally(['foo', 'bar']) ?? []
1996
+ * ```
1997
+ *
1998
+ * Fetches a collection of {@link Amity.Message} objects from cache
1999
+ *
2000
+ * @param messageIds the IDs of the {@link Amity.Message} to fetch
2001
+ * @returns the associated collection of {@link Amity.Message} objects
2002
+ *
2003
+ * @category Message API
2004
+ */
2005
+ getMessages.locally = (messageIds) => {
2006
+ var _a;
2007
+ const client = getActiveClient();
2008
+ client.log('message/getMessages.locally', messageIds);
2009
+ const cached = (_a = pullFromCache('message', ...messageIds)) !== null && _a !== void 0 ? _a : [];
2010
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) === messageIds.length)
2011
+ return toRecord(cached);
2012
+ };
2013
+
2014
+ /**
2015
+ * ```js
2016
+ * import { queryMessages } from '@amityco/ts-sdk'
2017
+ * const messages = await queryMessages({ channelId })
2018
+ * ```
2019
+ *
2020
+ * Queries a paginable list of {@link Amity.Message} objects
2021
+ *
2022
+ * @param query The query parameters
2023
+ * @returns A page of {@link Amity.Message} objects
2024
+ *
2025
+ * @category Message API
2026
+ * @async
2027
+ */
2028
+ const queryMessages = async (query) => {
2029
+ const client = getActiveClient();
2030
+ client.log('message/queryMessages', query);
2031
+ const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
2032
+ // API-FIX: parameters should be querystring. (1)
2033
+ // API-FIX: backend should answer Amity.Response (2)
2034
+ // API-FIX: pagination should not be indexed on channelSegment (3)
2035
+ // const { data } = await client.http.get<Amity.Response<Amity.Paged<Amity.MessagePayload>>>(
2036
+ const { data } = await client.http.get(`/api/v3/messages`, { params: Object.assign(Object.assign({}, params), { options: {
2037
+ token: toToken(page, 'afterbefore'),
2038
+ } }), });
2039
+ // API-FIX: backend should answer Amity.Response (2)
2040
+ // const { paging, messages } = unwrapPayload(data)
2041
+ const { paging } = data, response = __rest(data, ["paging"]);
2042
+ decoratePayload(response);
2043
+ ingestInCache(response);
2044
+ const { messages } = response;
2045
+ const nextPage = toPage(paging.next);
2046
+ const prevPage = toPage(paging.previous);
2047
+ return { data: toRecord(messages), nextPage, prevPage };
2048
+ };
2049
+ /**
2050
+ * ```js
2051
+ * import { queryMessages } from '@amityco/ts-sdk'
2052
+ * const messages = queryMessages.locally!({ channelId })
2053
+ * ```
2054
+ *
2055
+ * Queries a paginable list of {@link Amity.Message} objects from cache
2056
+ *
2057
+ * @param query The query parameters
2058
+ * @returns A page of {@link Amity.Message} objects
2059
+ *
2060
+ * @category Message API
2061
+ */
2062
+ queryMessages.locally = (query) => {
2063
+ var _a, _b, _c, _d, _e;
2064
+ const client = getActiveClient();
2065
+ client.log('message/queryMessages.locally', query);
2066
+ const { channelId, page } = query;
2067
+ const [channel] = (_a = pullFromCache('channel', channelId)) !== null && _a !== void 0 ? _a : [];
2068
+ let messages = (_b = pullFromCache('message')) !== null && _b !== void 0 ? _b : [];
2069
+ // filter
2070
+ messages = filterByPropEquality(messages, 'channelId', channelId);
2071
+ // API-FIX filter by isDeleted doesn't work in backend... srsly wtf... how do they test things???
2072
+ // messages = filterByPropEquality(messages, 'isDeleted', query?.isDeleted)
2073
+ // sort
2074
+ messages = messages.sort(sortByChannelSegment);
2075
+ // paging
2076
+ if (page) {
2077
+ // slice
2078
+ // API-FIX we can't reuse proper page because the message page is done
2079
+ // by channelSegment which is sadly unique to the entire platform.
2080
+ // this part is copied and adapted from sliceByPaging function
2081
+ let start = 0;
2082
+ let end = undefined;
2083
+ // next page behavior
2084
+ if ('after' in page) {
2085
+ start = page.after !== 0
2086
+ ? messages.findIndex(message => message.channelSegment === (page === null || page === void 0 ? void 0 : page.after)) + 1
2087
+ : 0;
2088
+ end = start + page.limit;
2089
+ // prev page behavior
2090
+ }
2091
+ else if ('before' in page) {
2092
+ end = page.before !== 0
2093
+ ? messages.findIndex(message => message.channelSegment === (page === null || page === void 0 ? void 0 : page.before)) + 1
2094
+ : messages.length - 1;
2095
+ start = end > page.limit ? end - page.limit : 0;
2096
+ }
2097
+ const paged = messages.slice(start, end);
2098
+ messages = paged.length === page.limit ? paged : [];
2099
+ }
2100
+ const prevPage = ((_c = messages[0]) === null || _c === void 0 ? void 0 : _c.channelSegment) > 0
2101
+ ? { before: messages[0].channelSegment, limit: page === null || page === void 0 ? void 0 : page.limit }
2102
+ : undefined;
2103
+ const nextPage = ((_d = messages[messages.length - 1]) === null || _d === void 0 ? void 0 : _d.channelSegment) < ((_e = channel === null || channel === void 0 ? void 0 : channel.messageCount) !== null && _e !== void 0 ? _e : 0)
2104
+ ? { after: messages[messages.length - 1].channelSegment, limit: page === null || page === void 0 ? void 0 : page.limit }
2105
+ : undefined;
2106
+ return { data: toRecord(messages), nextPage, prevPage };
2107
+ };
2108
+
2109
+ /**
2110
+ * ```js
2111
+ * import { createMessage } from '@amityco/ts-sdk'
2112
+ * const created = await createMessage({
2113
+ * channelId: 'foobar',
2114
+ * data: { text: 'hello world' }
2115
+ * })
2116
+ * ```
2117
+ *
2118
+ * Creates an {@link Amity.Message}
2119
+ *
2120
+ * @param bundle The data necessary to create a new {@link Amity.Message}
2121
+ * @returns The newly created {@link Amity.Message}
2122
+ *
2123
+ * @category Message API
2124
+ * @async
2125
+ */
2126
+ const createMessage = async (bundle) => {
2127
+ const client = getActiveClient();
2128
+ client.log('user/createMessage', bundle);
2129
+ const { data } = await client.http.post('/api/v3/messages', bundle);
2130
+ decoratePayload(data);
2131
+ ingestInCache(data);
2132
+ // no need for event, fired by server
2133
+ const { messages } = data;
2134
+ return messages[0];
2135
+ };
2136
+ /**
2137
+ * ```js
2138
+ * import { createMessage } from '@amityco/ts-sdk'
2139
+ * const created = createMessage.locally({
2140
+ * channelId: 'foobar',
2141
+ * data: { text: 'hello world' }
2142
+ * })
2143
+ * ```
2144
+ *
2145
+ * Creates an {@link Amity.Message} in cache
2146
+ *
2147
+ * @param bundle The data necessary to create a new {@link Amity.Message}
2148
+ * @returns The newly created {@link Amity.Message}
2149
+ *
2150
+ * @category Message API
2151
+ */
2152
+ createMessage.optimistically = (bundle) => {
2153
+ var _a, _b, _c;
2154
+ const client = getActiveClient();
2155
+ client.log('user/createMessage.locally', bundle);
2156
+ // should we do this?
2157
+ if (!client.cache)
2158
+ return;
2159
+ const [channel] = (_a = pullFromCache('channel', bundle.channelId)) !== null && _a !== void 0 ? _a : [];
2160
+ pushToCache('channel', Object.assign(Object.assign({}, channel), { messageCount: ((_b = channel.messageCount) !== null && _b !== void 0 ? _b : 0) + 1 }));
2161
+ const message = Object.assign(Object.assign({ localId: uuid(), messageId: Math.random().toString(16), userId: client.userId, channelSegment: ((_c = channel === null || channel === void 0 ? void 0 : channel.messageCount) !== null && _c !== void 0 ? _c : 0) + 1, createdAt: new Date().toISOString() }, bundle), { syncedAt: -1 });
2162
+ pushToCache('message', message);
2163
+ fireEvent('v3.message.didCreate', { messages: [message] });
2164
+ return message;
2165
+ };
2166
+
2167
+ /**
2168
+ * ```js
2169
+ * import { updateMessage } from '@amityco/ts-sdk'
2170
+ * const updated = await updateMessage(messageId, {
2171
+ * data: { text: 'hello world' }
2172
+ * })
2173
+ * ```
2174
+ *
2175
+ * Updates an {@link Amity.Message}
2176
+ *
2177
+ * @param messageId The ID of the {@link Amity.Message} to edit
2178
+ * @param patch The patch data to apply
2179
+ * @returns the updated {@link Amity.Message} object
2180
+ *
2181
+ * @category Message API
2182
+ * @async
2183
+ */
2184
+ const updateMessage = async (messageId, patch) => {
2185
+ const client = getActiveClient();
2186
+ client.log('user/updateMessage', patch);
2187
+ const { data } = await client.http.put(`/api/v3/messages/${messageId}`, patch);
2188
+ decoratePayload(data);
2189
+ ingestInCache(data);
2190
+ // no need for event, fired by server
2191
+ return data.messages.find(message => message.messageId === messageId);
2192
+ };
2193
+ /**
2194
+ * ```js
2195
+ * import { updateMessage } from '@amityco/ts-sdk'
2196
+ * const updated = updateMessage.locally('foobar', {
2197
+ * data: { text: 'hello world' }
2198
+ * })
2199
+ * ```
2200
+ *
2201
+ * Updates an {@link Amity.Message} in cache
2202
+ *
2203
+ * @param messageId The ID of the {@link Amity.Message} to edit
2204
+ * @param patch The patch data to apply
2205
+ * @returns the updated {@link Amity.Message} object
2206
+ *
2207
+ * @category Message API
2208
+ */
2209
+ updateMessage.optimistically = (messageId, patch) => {
2210
+ var _a;
2211
+ const client = getActiveClient();
2212
+ client.log('user/updateMessage', patch);
2213
+ const [message] = (_a = pullFromCache('message', messageId)) !== null && _a !== void 0 ? _a : [];
2214
+ if (!message)
2215
+ return;
2216
+ const updated = Object.assign(Object.assign(Object.assign({}, message), patch), { updatedAt: new Date().toISOString() });
2217
+ pushToCache('message', updated);
2218
+ fireEvent('v3.message.didUpdate', { messages: [updated] });
2219
+ return updated;
2220
+ };
2221
+
2222
+ /**
2223
+ * ```js
2224
+ * import { deleteMessage } from '@amityco/ts-sdk'
2225
+ * const success = await deleteMessage('foobar')
2226
+ * ```
2227
+ *
2228
+ * Delete a {@link Amity.Message}
2229
+ *
2230
+ * @param The ID of the {@link Amity.Message} to delete
2231
+ * @return A success boolean if the {@link Amity.Message} was deleted
2232
+ *
2233
+ * @category Message API
2234
+ * @async
2235
+ */
2236
+ const deleteMessage = async (messageId) => {
2237
+ const client = getActiveClient();
2238
+ client.log('message/deleteMessage', messageId);
2239
+ // API-FIX: This endpoint has not been implemented yet.
2240
+ await client.http.delete(`/api/v3/messages/${messageId}`);
2241
+ const deleted = await getMessage(messageId);
2242
+ // no need for event, fired by server
2243
+ return deleted;
2244
+ };
2245
+ /**
2246
+ * ```js
2247
+ * import { deleteMessage } from '@amityco/ts-sdk'
2248
+ * const success = deleteMessage.locally('foobar')
2249
+ * ```
2250
+ *
2251
+ * Deletes a {@link Amity.Message}
2252
+ *
2253
+ * @param messageId The {@link Amity.Message} ID to delete
2254
+ * @return A success boolean if the {@link Amity.Message} was deleted
2255
+ *
2256
+ * @category Message API
2257
+ */
2258
+ deleteMessage.optimistically = (messageId) => {
2259
+ var _a;
2260
+ const client = getActiveClient();
2261
+ client.log('message/deleteMessage', messageId);
2262
+ const [message] = (_a = pullFromCache('message', messageId)) !== null && _a !== void 0 ? _a : [];
2263
+ if (!message)
2264
+ return;
2265
+ const deleted = Object.assign(Object.assign({}, message), { isDeleted: true, updatedAt: new Date().toISOString() });
2266
+ pushToCache('message', deleted);
2267
+ fireEvent('v3.message.didDelete', { messages: [deleted] });
2268
+ return deleted;
2269
+ };
2270
+
2271
+ /**
2272
+ * ```js
2273
+ * import { queryPosts } from '@amityco/ts-sdk'
2274
+ * const posts = await queryPosts({ targetId, targetType })
2275
+ * ```
2276
+ *
2277
+ * Queries a paginable list of {@link Amity.Post} objects
2278
+ *
2279
+ * @param query The query parameters
2280
+ * @returns posts
2281
+ *
2282
+ * @category Post API
2283
+ * @async
2284
+ */
2285
+ const queryPosts = async (query) => {
2286
+ const client = getActiveClient();
2287
+ client.log('post/queryPosts', query);
2288
+ const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
2289
+ // API-FIX: parameters should be querystring. (1)
2290
+ // API-FIX: backend should answer Amity.Response (2)
2291
+ // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.PostPayload>>>(
2292
+ const { data } = await client.http.get(`/api/v3/posts`, { params: Object.assign(Object.assign({}, params), { options: {
2293
+ token: toToken(page, 'skiplimit'),
2294
+ } }), });
2295
+ // API-FIX: backend should answer Amity.Response (2)
2296
+ // const { paging, posts } = unwrapPayload(data)
2297
+ const { paging } = data, response = __rest(data, ["paging"]);
2298
+ decoratePayload(response);
2299
+ ingestInCache(response);
2300
+ const { posts } = response;
2301
+ const nextPage = toPage(paging.next);
2302
+ const prevPage = toPage(paging.previous);
2303
+ return { data: toRecord(posts), nextPage, prevPage };
2304
+ };
2305
+ /**
2306
+ * ```js
2307
+ * import { queryPosts } from '@amityco/ts-sdk'
2308
+ * const posts = queryPosts.locally({ targetId, targetType })
2309
+ * ```
2310
+ *
2311
+ * Queries a paginable list of {@link Amity.Post} objects from cache
2312
+ *
2313
+ * @param query The query parameters
2314
+ * @returns posts
2315
+ *
2316
+ * @category Post API
2317
+ */
2318
+ queryPosts.locally = (query) => {
2319
+ const client = getActiveClient();
2320
+ client.log('post/queryPosts.locally', query);
2321
+ // TODO
2322
+ };
2323
+
2324
+ /**
2325
+ * ```js
2326
+ * import { getPosts } from '@amityco/ts-sdk'
2327
+ * const posts = await getPosts(['foo', 'bar'])
2328
+ * ```
2329
+ *
2330
+ * Fetches a collection of {@link Amity.Post} objects
2331
+ *
2332
+ * @param postIds the IDs of the {@link Amity.Post} to fetch
2333
+ * @returns the associated collection of {@link Amity.Post} objects
2334
+ *
2335
+ * @category Post API
2336
+ * @async
2337
+ */
2338
+ const getPosts = async (postIds) => {
2339
+ const client = getActiveClient();
2340
+ client.log('post/getPosts', postIds);
2341
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
2342
+ const { data } = await client.http.get(`/api/v3/posts/list`, { params: { postIds } });
2343
+ decoratePayload(data);
2344
+ ingestInCache(data);
2345
+ const { posts } = data;
2346
+ return posts;
2347
+ };
2348
+ /**
2349
+ * ```js
2350
+ * import { getPosts } from '@amityco/ts-sdk'
2351
+ * const posts = getPosts.locally(['foo', 'bar'])
2352
+ * ```
2353
+ *
2354
+ * Fetches a collection of {@link Amity.Post} objects from cache
2355
+ *
2356
+ * @param postIds the IDs of the {@link Amity.Post} to fetch
2357
+ * @returns the associated collection of {@link Amity.Post} objects
2358
+ *
2359
+ * @category Post API
2360
+ */
2361
+ getPosts.locally = (postIds) => {
2362
+ var _a;
2363
+ const client = getActiveClient();
2364
+ client.log('post/getPosts.locally', postIds);
2365
+ const cached = (_a = pullFromCache('post', ...postIds)) !== null && _a !== void 0 ? _a : [];
2366
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) === postIds.length)
2367
+ return toRecord(cached);
2368
+ };
2369
+
2370
+ /**
2371
+ * ```js
2372
+ * import { getPost } from '@amityco/ts-sdk'
2373
+ * const post = await getPost('foobar')
2374
+ * ```
2375
+ *
2376
+ * Fetches a {@link Amity.Post} object
2377
+ *
2378
+ * @param postId the ID of the {@link Amity.Post} to fetch
2379
+ * @returns the associated {@link Amity.Post} object
2380
+ *
2381
+ * @category Post API
2382
+ * @async
2383
+ */
2384
+ const getPost = async (postId) => {
2385
+ const client = getActiveClient();
2386
+ client.log('post/getPost', postId);
2387
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
2388
+ const { data } = await client.http.get(`/api/v3/posts/${postId}`);
2389
+ decoratePayload(data);
2390
+ ingestInCache(data);
2391
+ const { posts } = data;
2392
+ return posts.find(post => post.postId === postId);
2393
+ };
2394
+ /**
2395
+ * ```js
2396
+ * import { getPost } from '@amityco/ts-sdk'
2397
+ * const post = getPost.locally('foobar')
2398
+ * ```
2399
+ *
2400
+ * Fetches a {@link Amity.Post} object
2401
+ *
2402
+ * @param postId the ID of the {@link Amity.Post} to fetch
2403
+ * @returns the associated {@link Amity.Post} object
2404
+ *
2405
+ * @category Post API
2406
+ */
2407
+ getPost.locally = (postId) => {
2408
+ var _a;
2409
+ const client = getActiveClient();
2410
+ client.log('post/getPost.locally', postId);
2411
+ const [post] = (_a = pullFromCache('post', postId)) !== null && _a !== void 0 ? _a : [];
2412
+ return post;
2413
+ };
2414
+
2415
+ /**
2416
+ * ```js
2417
+ * import { createPost } from '@amityco/ts-sdk'
2418
+ * const newPost = await createPost(bundle)
2419
+ * ```
2420
+ *
2421
+ * Creates an {@link Amity.Post}
2422
+ *
2423
+ * @param bundle The data necessary to create a new {@link Amity.Post}
2424
+ * @returns The newly created {@link Amity.Post}
2425
+ *
2426
+ * @category Post API
2427
+ * @async
2428
+ */
2429
+ const createPost = async (bundle) => {
2430
+ const client = getActiveClient();
2431
+ client.log('post/createPost', bundle);
2432
+ // API-FIX: backend rejects that we pass the dataType manually T_T
2433
+ if (!bundle.dataType || ['text', 'image', 'file'].includes(bundle.dataType))
2434
+ delete bundle.dataType;
2435
+ const { data } = await client.http.post('/api/v3/posts', bundle);
2436
+ decoratePayload(data);
2437
+ ingestInCache(data);
2438
+ fireEvent('v3.community.didUpdate', { communities: data.communities });
2439
+ fireEvent('v3.post.didCreate', data);
2440
+ const { posts } = data;
2441
+ return posts[0];
2442
+ };
2443
+
2444
+ /**
2445
+ * ```js
2446
+ * import { updatePost } from '@amityco/ts-sdk'
2447
+ * const updated = await updatePost(postId, {
2448
+ * data: { text: 'hello world' }
2449
+ * })
2450
+ * ```
2451
+ *
2452
+ * Updates an {@link Amity.Post}
2453
+ *
2454
+ * @param postId The ID of the {@link Amity.Post} to edit
2455
+ * @param patch The patch data to apply
2456
+ * @returns the updated {@link Amity.Post} object
2457
+ *
2458
+ * @category Post API
2459
+ * @async
2460
+ */
2461
+ const updatePost = async (postId, patch) => {
2462
+ const client = getActiveClient();
2463
+ client.log('user/updatePost', patch);
2464
+ const { data } = await client.http.put(`/api/v3/posts/${postId}`, patch);
2465
+ decoratePayload(data);
2466
+ ingestInCache(data);
2467
+ fireEvent('v3.post.didUpdate', data);
2468
+ const { posts } = data;
2469
+ return posts.find(post => post.postId === postId);
2470
+ };
2471
+
2472
+ /**
2473
+ * ```js
2474
+ * import { queryCommunities } from '@amityco/ts-sdk'
2475
+ * const communities = await queryCommunities()
2476
+ * ```
2477
+ *
2478
+ * Queries a paginable list of {@link Amity.Community} objects
2479
+ * Search is performed by displayName such as `.startsWith(search)`
2480
+ *
2481
+ * @param query The query parameters
2482
+ * @returns A page of {@link Amity.Community} objects
2483
+ *
2484
+ * @category Community API
2485
+ * @async
2486
+ */
2487
+ const queryCommunities = async (query) => {
2488
+ const client = getActiveClient();
2489
+ client.log('channel/queryCommunities', query);
2490
+ // safe decapsulation
2491
+ const _a = query !== null && query !== void 0 ? query : {}, { page, displayName, membership } = _a, params = __rest(_a, ["page", "displayName", "membership"]);
2492
+ // API-FIX: parameters should be querystring.
2493
+ // API-FIX: backend doesnt answer Amity.Response
2494
+ // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<CommunityPayload>>>(
2495
+ const { data } = await client.http.get(`/api/v3/communities`, { params: Object.assign(Object.assign({}, params), { keyword: displayName, filter: membership, options: {
2496
+ token: toToken(page, 'skiplimit')
2497
+ } }) });
2498
+ // API-FIX: backend to response Amity.Response: const { paging, communities } = unwrapPayload(data)
2499
+ const { paging } = data, response = __rest(data, ["paging"]);
2500
+ decoratePayload(response);
2501
+ ingestInCache(response);
2502
+ const prevPage = toPage(paging === null || paging === void 0 ? void 0 : paging.previous);
2503
+ const nextPage = toPage(paging === null || paging === void 0 ? void 0 : paging.next);
2504
+ const { communities } = response;
2505
+ return { data: toRecord(communities), prevPage, nextPage };
2506
+ };
2507
+ /**
2508
+ * ```js
2509
+ * import { queryCommunities } from '@amityco/ts-sdk'
2510
+ * const communities = queryCommunities.locally()
2511
+ * ```
2512
+ *
2513
+ * Queries a paginable list of {@link Amity.Community} objects from cache
2514
+ *
2515
+ * @param query The query parameters
2516
+ * @returns communities
2517
+ *
2518
+ * @category Community API
2519
+ */
2520
+ queryCommunities.locally = (query) => {
2521
+ const client = getActiveClient();
2522
+ client.log('community/queryCommunities.locally', query);
2523
+ // TODO
2524
+ };
2525
+
2526
+ /**
2527
+ * ```js
2528
+ * import { getCommunities } from '@amityco/ts-sdk'
2529
+ * const communities = await getCommunities(['foo', 'bar'])
2530
+ * ```
2531
+ *
2532
+ * Fetches a collection of {@link Amity.Community} objects
2533
+ *
2534
+ * @param communityIds the IDs of the {@link Amity.Community} to fetch
2535
+ * @returns the associated collection of {@link Amity.Community} objects
2536
+ *
2537
+ * @category Community API
2538
+ * @async
2539
+ */
2540
+ const getCommunities = async (communityIds) => {
2541
+ const client = getActiveClient();
2542
+ client.log('community/getCommunities', communityIds);
2543
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
2544
+ const { data } = await client.http.get(`/api/v3/communities/list`, { params: { communityIds } });
2545
+ decoratePayload(data);
2546
+ ingestInCache(data);
2547
+ const { communities } = data;
2548
+ return toRecord(communities);
2549
+ };
2550
+ /**
2551
+ * ```js
2552
+ * import { getCommunities } from '@amityco/ts-sdk'
2553
+ * const communities = getCommunities.locally(['foo', 'bar']) ?? []
2554
+ * ```
2555
+ *
2556
+ * Fetches a collection of {@link Amity.Community} objects from cache
2557
+ *
2558
+ * @param communityIds the IDs of the {@link Amity.Community} to fetch
2559
+ * @returns the associated collection of {@link Amity.Community} objects
2560
+ *
2561
+ * @category Community API
2562
+ */
2563
+ getCommunities.locally = (communityIds) => {
2564
+ var _a;
2565
+ const client = getActiveClient();
2566
+ client.log('community/getCommunities.locally', communityIds);
2567
+ const cached = (_a = pullFromCache('community', ...communityIds)) !== null && _a !== void 0 ? _a : [];
2568
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) === communityIds.length)
2569
+ return toRecord(cached);
2570
+ };
2571
+
2572
+ /**
2573
+ * ```js
2574
+ * import { getCommunity } from '@amityco/ts-sdk'
2575
+ * const community = await getCommunity('foobar')
2576
+ * ```
2577
+ *
2578
+ * Fetches a {@link Amity.Community} object
2579
+ *
2580
+ * @param communityId the ID of the {@link Amity.Community} to fetch
2581
+ * @returns the associated {@link Amity.Community} object
2582
+ *
2583
+ * @category Community API
2584
+ * @async
2585
+ */
2586
+ const getCommunity = async (communityId) => {
2587
+ const client = getActiveClient();
2588
+ client.log('community/getCommunity', communityId);
2589
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
2590
+ const { data } = await client.http.get(`/api/v3/communities/${communityId}`);
2591
+ decoratePayload(data);
2592
+ ingestInCache(data);
2593
+ const { communities } = data;
2594
+ return communities.find(community => community.communityId === communityId);
2595
+ };
2596
+ /**
2597
+ * ```js
2598
+ * import { getCommunity } from '@amityco/ts-sdk'
2599
+ * const community = getCommunity.locally('foobar')
2600
+ * ```
2601
+ *
2602
+ * Fetches a {@link Amity.Community} object from cache
2603
+ *
2604
+ * @param communityId the ID of the {@link Amity.Community} to fetch
2605
+ * @returns the associated {@link Amity.Community} object
2606
+ *
2607
+ * @category Community API
2608
+ */
2609
+ getCommunity.locally = (communityId) => {
2610
+ var _a;
2611
+ const client = getActiveClient();
2612
+ client.log('community/getCommunity.locally', communityId);
2613
+ const [community] = (_a = pullFromCache('community', communityId)) !== null && _a !== void 0 ? _a : [];
2614
+ return community;
2615
+ };
2616
+
2617
+ /**
2618
+ * ```js
2619
+ * import { createCommunity } from '@amityco/ts-sdk'
2620
+ * const created = await createCommunity({ communityId: 'foobar', displayName: 'foobar' })
2621
+ * ```
2622
+ *
2623
+ * Creates an {@link Amity.Community}
2624
+ *
2625
+ * @param bundle The data necessary to create a new {@link Amity.Community}
2626
+ * @returns The newly created {@link Amity.Community}
2627
+ *
2628
+ * @category Community API
2629
+ * @async
2630
+ */
2631
+ const createCommunity = async (bundle) => {
2632
+ const client = getActiveClient();
2633
+ client.log('user/createCommunity', bundle);
2634
+ const { data } = await client.http.post('/api/v3/communities/', bundle);
2635
+ decoratePayload(data);
2636
+ ingestInCache(data);
2637
+ fireEvent('v3.community.didCreate', data);
2638
+ const { communities } = data;
2639
+ return communities[0];
2640
+ };
2641
+
2642
+ /**
2643
+ * ```js
2644
+ * import { updateCommunity } from '@amityco/ts-sdk'
2645
+ * const updated = await updateCommunity(communityId, { displayName: 'foobar' })
2646
+ * ```
2647
+ *
2648
+ * Updates an {@link Amity.Community}
2649
+ *
2650
+ * @param communityId The ID of the {@link Amity.Community} to edit
2651
+ * @param patch The patch data to apply
2652
+ * @returns the updated {@link Amity.Community} object
2653
+ *
2654
+ * @category Community API
2655
+ * @async
2656
+ */
2657
+ const updateCommunity = async (communityId, patch) => {
2658
+ const client = getActiveClient();
2659
+ client.log('community/updateCommunity', communityId, patch);
2660
+ const { data } = await client.http.put(`/api/v3/communities/${communityId}`, patch);
2661
+ decoratePayload(data);
2662
+ ingestInCache(data);
2663
+ fireEvent('v3.community.didUpdate', data);
2664
+ const { communities } = data;
2665
+ return communities.find(community => community.communityId === communityId);
2666
+ };
2667
+
2668
+ /**
2669
+ * ```js
2670
+ * import { deleteCommunity } from '@amityco/ts-sdk'
2671
+ * const success = await deleteCommunity('foobar')
2672
+ * ```
2673
+ *
2674
+ * Deletes a {@link Amity.Community}
2675
+ *
2676
+ * @param communityId The {@link Amity.Community} ID to delete
2677
+ * @return A success boolean if the {@link Amity.Community} was deleted
2678
+ *
2679
+ * @category Community API
2680
+ * @async
2681
+ */
2682
+ const deleteCommunity = async (communityId) => {
2683
+ const client = getActiveClient();
2684
+ client.log('community/deleteCommunity', communityId);
2685
+ // API-FIX: This endpoint has not been implemented yet.
2686
+ await client.http.delete(`/api/v3/communities/${communityId}`);
2687
+ const deleted = await getCommunity(communityId);
2688
+ fireEvent('v3.community.didDelete', { communities: [deleted] });
2689
+ return deleted;
2690
+ };
2691
+
2692
+ /**
2693
+ * ```js
2694
+ * import { joinCommunity } from '@amityco/ts-sdk'
2695
+ * const isJoined = await joinCommunity('foobar')
2696
+ * ```
2697
+ *
2698
+ * Joins a {@link Amity.Community} object
2699
+ *
2700
+ * @param communityId the {@link Amity.Community} to join
2701
+ * @returns A success boolean if the {@link Amity.Community} was joined
2702
+ *
2703
+ * @category Community API
2704
+ * @async
2705
+ */
2706
+ const joinCommunity = async (communityId) => {
2707
+ const client = getActiveClient();
2708
+ client.log('community/joinCommunity', communityId);
2709
+ const { data } = await client.http.post(`/api/v3/communities/${communityId}/join`);
2710
+ decoratePayload(data);
2711
+ ingestInCache(data);
2712
+ fireEvent('v3.community.didJoin', {
2713
+ communities: data.communities
2714
+ });
2715
+ const { communityUsers } = data;
2716
+ return !!communityUsers.find(communityUser => (communityUser.communityId === communityId
2717
+ && communityUser.communityMembership === 'member'));
2718
+ };
2719
+
2720
+ /**
2721
+ * ```js
2722
+ * import { leaveCommunity } from '@amityco/ts-sdk'
2723
+ * const isLeft = await leaveCommunity('foobar')
2724
+ * ```
2725
+ *
2726
+ * Leaves a {@link Amity.Community} object
2727
+ *
2728
+ * @param communityId the {@link Amity.Community} to leave
2729
+ * @returns A success boolean if {@link Amity.Community} was left
2730
+ *
2731
+ * @category Community API
2732
+ * @async
2733
+ */
2734
+ const leaveCommunity = async (communityId) => {
2735
+ const client = getActiveClient();
2736
+ client.log('community/leaveCommunity', communityId);
2737
+ const { data } = await client.http.delete(`/api/v3/communities/${communityId}/leave`);
2738
+ decoratePayload(data);
2739
+ ingestInCache(data);
2740
+ fireEvent('v3.community.didJoin', {
2741
+ communities: data.communities,
2742
+ });
2743
+ const { communityUsers } = data;
2744
+ return !!communityUsers.find(communityUser => (communityUser.communityId === communityId
2745
+ && communityUser.communityMembership !== 'member'));
2746
+ };
2747
+
2748
+ /**
2749
+ * ```js
2750
+ * import { queryCommunityMembers } from '@amityco/ts-sdk'
2751
+ * const communityMembers = await queryCommunityMembers({ communityId: 'foo' })
2752
+ * ```
2753
+ *
2754
+ * Queries a paginable list of {@link Amity.CommunityUser} objects
2755
+ *
2756
+ * @param query The query parameters
2757
+ * @returns A page of {@link Amity.CommunityUser} objects
2758
+ *
2759
+ * @category Community API
2760
+ * @async
2761
+ **/
2762
+ const queryCommunityMembers = async (query) => {
2763
+ const client = getActiveClient();
2764
+ client.log('community/queryCommunityMembers', query);
2765
+ const _a = query !== null && query !== void 0 ? query : {}, { page, communityId } = _a, params = __rest(_a, ["page", "communityId"]);
2766
+ const { data } = await client.http.get(`/api/v3/communities/${communityId}/users`, {
2767
+ params: Object.assign(Object.assign({}, params), { options: {
2768
+ token: toToken(page, 'skiplimit'),
2769
+ } }),
2770
+ });
2771
+ const { paging } = data, response = __rest(data, ["paging"]);
2772
+ decoratePayload(response);
2773
+ ingestInCache(response);
2774
+ const { communityUsers } = response;
2775
+ const nextPage = toPage(paging.next);
2776
+ const prevPage = toPage(paging.previous);
2777
+ return { data: toRecord(communityUsers), nextPage, prevPage };
2778
+ };
2779
+ /**
2780
+ * ```js
2781
+ * import { queryCommunityMembers } from '@amityco/ts-sdk'
2782
+ * const communityMembers = await queryCommunityMembers(query)
2783
+ * ```
2784
+ *
2785
+ * Queries a paginable list of {@link Amity.Post} objects from cache
2786
+ *
2787
+ * @param query The query parameters
2788
+ * @returns posts
2789
+ *
2790
+ * @category Post API
2791
+ */
2792
+ queryCommunityMembers.locally = (query) => {
2793
+ const client = getActiveClient();
2794
+ client.log('community/queryCommunityMembers', query);
2795
+ // TODO
2796
+ };
2797
+
2798
+ /**
2799
+ * ```js
2800
+ * import { addCommunityMembers } from '@amityco/ts-sdk'
2801
+ * const updated = await addCommunityMembers(communityId, ['foo', 'bar'])
2802
+ * ```
2803
+ *
2804
+ * Adds a list of {@link Amity.User} to a {@link Amity.Community} to add users to
2805
+ *
2806
+ * @param communityId The ID of the {@link Amity.Community} to perform
2807
+ * @param userIds The list of IDs {@link Amity.User} to add
2808
+ * @returns A success boolean if the {@link Amity.User} were added to the {@link Amity.Community}
2809
+ *
2810
+ * @category Community API
2811
+ * @async
2812
+ */
2813
+ const addCommunityMembers = async (communityId, userIds) => {
2814
+ const client = getActiveClient();
2815
+ client.log('community/addCommunityMembers', communityId, userIds);
2816
+ const { data } = await client.http.post(`/api/v3/communities/${communityId}/users`, { communityId, userIds });
2817
+ decoratePayload(data);
2818
+ ingestInCache(data);
2819
+ fireEvent('v3.community.didAddUsers', {
2820
+ communities: data.communities,
2821
+ });
2822
+ const { communityUsers } = data;
2823
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId &&
2824
+ communityUser.communityMembership === 'member');
2825
+ };
2826
+
2827
+ /**
2828
+ * ```js
2829
+ * import { removeCommunityMembers } from '@amityco/ts-sdk'
2830
+ * const updated = await removeCommunityMembers(communityId, ['foo', 'bar'])
2831
+ * ```
2832
+ *
2833
+ * Removes a list of {@link Amity.User} from a {@link Amity.Channel}
2834
+ *
2835
+ * @param communityId The ID of the {@link Amity.Community} to edit
2836
+ * @param userIds The list of IDs {@link Amity.User} to remove
2837
+ * @returns A success boolean if the list of {@link Amity.User} were removed from the {@link Amity.Community}
2838
+ *
2839
+ * @category Community API
2840
+ * @async
2841
+ */
2842
+ const removeCommunityMembers = async (communityId, userIds) => {
2843
+ const client = getActiveClient();
2844
+ client.log('community/removeCommunityMembers', communityId, userIds);
2845
+ const { data } = await client.http.delete(`/api/v3/communities/${communityId}/users`, { data: { communityId, userIds } });
2846
+ decoratePayload(data);
2847
+ ingestInCache(data);
2848
+ fireEvent('v3.community.didRemoveUsers', {
2849
+ communities: data.communities,
2850
+ });
2851
+ const { communityUsers } = data;
2852
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId &&
2853
+ communityUser.communityMembership !== 'member');
2854
+ };
2855
+
2856
+ /**
2857
+ * ```js
2858
+ * import { addCommunityMembersRole } from '@amityco/ts-sdk'
2859
+ * const updated = await addCommunityMembersRole(communityId, 'foo', ['bar'])
2860
+ * ```
2861
+ *
2862
+ * Adds an {@link Amity.Role} to a list of {@link Amity.User} on a {@link Amity.Community}
2863
+ *
2864
+ * @param communityId The ID of the {@link Amity.Community} to perform
2865
+ * @param roleId The ID of the {@link Amity.Role} to apply
2866
+ * @param userId Array of IDs of the {@link Amity.User} to perform
2867
+ * @returns A success boolean if the {@link Amity.Role} were added to list of {@link Amity.User} in the {@link Amity.Community}
2868
+ *
2869
+ * @category Community API
2870
+ * @async
2871
+ */
2872
+ const addCommunityMembersRole = async (communityId, roleId, userIds) => {
2873
+ const client = getActiveClient();
2874
+ client.log('community/addCommunityMembersRole', communityId, roleId, userIds);
2875
+ const { data } = await client.http.post(`/api/v3/communities/${communityId}/users/roles`, { communityId, role: roleId, userIds });
2876
+ decoratePayload(data);
2877
+ ingestInCache(data);
2878
+ const { communityUsers } = data;
2879
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.roles.includes(roleId));
2880
+ };
2881
+
2882
+ /**
2883
+ * ```js
2884
+ * import { removeCommunityMembersRole } from '@amityco/ts-sdk'
2885
+ * const updated = await removeCommunityMembersRole(communityId, 'foo', ['bar'])
2886
+ * ```
2887
+ *
2888
+ * Removes an {@link Amity.Role} from a list of {@link Amity.User} on a {@link Amity.Community}
2889
+ *
2890
+ * @param communityId The ID of the {@link Amity.Community} to perform
2891
+ * @param role The ID of the {@link Amity.Role} to apply
2892
+ * @param userId Array of IDs of the {@link Amity.User} to perform
2893
+ * @returns A success boolean if the {@link Amity.Role} were removed from list of {@link Amity.User} in the {@link Amity.Community}
2894
+ *
2895
+ * @category Community API
2896
+ * @async
2897
+ */
2898
+ const removeCommunityMembersRole = async (communityId, roleId, userIds) => {
2899
+ const client = getActiveClient();
2900
+ client.log('community/removeCommunityMembersRole', communityId, roleId, userIds);
2901
+ const { data } = await client.http.delete(`/api/v3/communities/${communityId}/users/roles`, { data: { communityId, role: roleId, userIds } });
2902
+ decoratePayload(data);
2903
+ ingestInCache(data);
2904
+ const { communityUsers } = data;
2905
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId && !communityUser.roles.includes(roleId));
2906
+ };
2907
+
2908
+ /**
2909
+ * ```js
2910
+ * import { deletePost } from '@amityco/ts-sdk'
2911
+ * const success = await deletePost('foobar')
2912
+ * ```
2913
+ *
2914
+ * Deletes a {@link Amity.Post}
2915
+ *
2916
+ * @param postId The {@link Amity.Post} ID to delete
2917
+ * @return A success boolean if the {@link Amity.Post} was deleted
2918
+ *
2919
+ * @category Post API
2920
+ * @async
2921
+ */
2922
+ const deletePost = async (postId) => {
2923
+ const client = getActiveClient();
2924
+ client.log('post/deletePost', postId);
2925
+ // API-FIX: This endpoint has not been implemented yet.
2926
+ await client.http.delete(`/api/v3/posts/${postId}`);
2927
+ // API-FIX: as for now we have no choice but to refetch
2928
+ const deleted = await getPost(postId);
2929
+ if (deleted.targetType === 'community') {
2930
+ const community = await getCommunity(deleted.targetId);
2931
+ fireEvent('v3.community.didUpdate', { communities: [community] });
2932
+ }
2933
+ fireEvent('v3.post.didDelete', { posts: [deleted] });
2934
+ return deleted;
2935
+ };
2936
+
2937
+ /**
2938
+ * ```js
2939
+ * import { queryComments } from '@amityco/ts-sdk'
2940
+ * const comments = await queryComments({ postId })
2941
+ * ```
2942
+ *
2943
+ * Queries a paginable list of {@link Amity.Comment} objects
2944
+ *
2945
+ * @param query The query parameters
2946
+ * @returns A page of {@link Amity.Comment} objects
2947
+ *
2948
+ * @category Comment API
2949
+ * @async
2950
+ */
2951
+ const queryComments = async (query) => {
2952
+ const client = getActiveClient();
2953
+ client.log('comment/queryComments', query);
2954
+ const { page } = query, params = __rest(query, ["page"]);
2955
+ query.parentId !== undefined;
2956
+ // API-FIX: parameters should be querystring. (1)
2957
+ // API-FIX: backend should answer Amity.Response (2)
2958
+ // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.CommentPayload>>>(
2959
+ const { data } = await client.http.get(`/api/v3/comments`, {
2960
+ params: Object.assign(Object.assign({}, params), {
2961
+ // filterByParentId, API-FIX: backend does not support this boolean LOL. what the hell seriously.
2962
+ options: {
2963
+ token: toToken(page, 'afterbefore'),
2964
+ } }),
2965
+ });
2966
+ // API-FIX: backend should answer Amity.Response (2)
2967
+ // const { paging, comments } = unwrapPayload(data)
2968
+ const { paging } = data, response = __rest(data, ["paging"]);
2969
+ decoratePayload(response);
2970
+ ingestInCache(response);
2971
+ const prevPage = toPage(paging.previous);
2972
+ const nextPage = toPage(paging.next);
2973
+ const { comments } = response;
2974
+ return { data: toRecord(comments), prevPage, nextPage };
2975
+ };
2976
+ /**
2977
+ * ```js
2978
+ * import { queryComments } from '@amityco/ts-sdk'
2979
+ * const comments = queryComments.locally({ postId })
2980
+ * ```
2981
+ *
2982
+ * Queries a paginable list of {@link Amity.Comment} objects from cache
2983
+ *
2984
+ * @param query The query parameters
2985
+ * @returns comments
2986
+ *
2987
+ * @category Comment API
2988
+ */
2989
+ queryComments.locally = (query) => {
2990
+ var _a;
2991
+ const client = getActiveClient();
2992
+ client.log('post/queryComments.locally', query);
2993
+ const { referenceId, referenceType, parentId, isDeleted, page = { before: 0, limit: 5 }, } = query;
2994
+ if (isNaN(page.after) && isNaN(page.before))
2995
+ page.before = 0;
2996
+ if (isNaN(page.limit))
2997
+ page.limit = 5;
2998
+ let comments = (_a = pullFromCache('comment')) !== null && _a !== void 0 ? _a : [];
2999
+ // no cache
3000
+ if (!comments.length)
3001
+ return;
3002
+ // filter
3003
+ comments = filterByPropEquality(comments, 'referenceId', referenceId);
3004
+ comments = filterByPropEquality(comments, 'referenceType', referenceType);
3005
+ comments = filterByPropEquality(comments, 'parentId', parentId);
3006
+ comments = filterByPropEquality(comments, 'isDeleted', isDeleted);
3007
+ // no interesting cache
3008
+ if (!comments.length)
3009
+ return;
3010
+ // sort
3011
+ comments = comments.sort(sortBySegmentNumber);
3012
+ // paging
3013
+ // API-FIX we can't reuse proper page because the message page is done
3014
+ // by segmentNumber which is sadly unique to the entire platform.
3015
+ // this part is copied and adapted from sliceByPaging function
3016
+ const afterIndex = !isNaN(page.after)
3017
+ ? comments.findIndex(({ segmentNumber }) => segmentNumber === page.after + 1)
3018
+ : 0;
3019
+ const beforeIndex = !isNaN(page.before) && page.before !== 0
3020
+ ? comments.findIndex(({ segmentNumber }) => segmentNumber === page.before - 1) + 1
3021
+ : comments.length;
3022
+ if (afterIndex < 0 || beforeIndex < 0)
3023
+ return;
3024
+ let slice = comments.slice(afterIndex !== -1 ? afterIndex : 0, beforeIndex !== -1 ? beforeIndex : undefined);
3025
+ // nothing left after slicing
3026
+ if (!slice.length)
3027
+ return;
3028
+ if (!isNaN(page.after) && !isNaN(page.before)) ;
3029
+ else if (!isNaN(page.after)) {
3030
+ slice = slice.slice(0, page.limit);
3031
+ }
3032
+ else if (!isNaN(page.before)) {
3033
+ slice = slice.slice(-page.limit);
3034
+ }
3035
+ for (let i = 0; i < slice.length - 1; i++)
3036
+ if (slice[i].segmentNumber !== slice[i + 1].segmentNumber - 1)
3037
+ return;
3038
+ const prevPage = slice[0].segmentNumber > 1
3039
+ ? { before: slice[0].segmentNumber, limit: page.limit }
3040
+ : undefined;
3041
+ const nextPage = {
3042
+ after: slice[slice.length - 1].segmentNumber,
3043
+ limit: page.limit,
3044
+ };
3045
+ return { data: toRecord(slice), nextPage, prevPage };
3046
+ };
3047
+
3048
+ /**
3049
+ * ```js
3050
+ * import { getComments } from '@amityco/ts-sdk'
3051
+ * const comments = await getComments(['foo', 'bar'])
3052
+ * ```
3053
+ *
3054
+ * Fetches a collection of {@link Amity.Comment} objects
3055
+ *
3056
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
3057
+ * @returns the associated collection of {@link Amity.Comment} objects
3058
+ *
3059
+ * @category Comment API
3060
+ * @async
3061
+ */
3062
+ const getComments = async (commentIds) => {
3063
+ const client = getActiveClient();
3064
+ client.log('comment/getComments', commentIds);
3065
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
3066
+ const { data } = await client.http.get(`/api/v3/comments/list`, { params: { commentIds } });
3067
+ decoratePayload(data);
3068
+ ingestInCache(data);
3069
+ const { comments } = data;
3070
+ return toRecord(comments);
3071
+ };
3072
+ /**
3073
+ * ```js
3074
+ * import { getComments } from '@amityco/ts-sdk'
3075
+ * const comments = getComments.locally(['foo', 'bar'])
3076
+ * ```
3077
+ *
3078
+ * Fetches a collection of {@link Amity.Comment} objects from cache
3079
+ *
3080
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
3081
+ * @returns the associated collection of {@link Amity.Comment} objects
3082
+ *
3083
+ * @category Comment API
3084
+ */
3085
+ getComments.locally = (commentIds) => {
3086
+ var _a;
3087
+ const client = getActiveClient();
3088
+ client.log('comment/getComments.locally', commentIds);
3089
+ const cached = (_a = pullFromCache('comment', ...commentIds)) !== null && _a !== void 0 ? _a : [];
3090
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) === commentIds.length)
3091
+ return toRecord(cached);
3092
+ };
3093
+
3094
+ /**
3095
+ * ```js
3096
+ * import { getComment } from '@amityco/ts-sdk'
3097
+ * const comment = await getComment('foobar')
3098
+ * ```
3099
+ *
3100
+ * Fetches a {@link Amity.Comment} object
3101
+ *
3102
+ * @param commentId the ID of the {@link Amity.Comment} to fetch
3103
+ * @returns the associated {@link Amity.Comment} object
3104
+ *
3105
+ * @category Comment API
3106
+ * @async
3107
+ */
3108
+ const getComment = async (commentId) => {
3109
+ const client = getActiveClient();
3110
+ client.log('comment/getComment', commentId);
3111
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
3112
+ const { data } = await client.http.get(`/api/v3/comments/${commentId}`);
3113
+ decoratePayload(data);
3114
+ ingestInCache(data);
3115
+ const { comments } = data;
3116
+ return comments.find(comment => comment.commentId === commentId);
3117
+ };
3118
+ /**
3119
+ * ```js
3120
+ * import { getComment } from '@amityco/ts-sdk'
3121
+ * const comment = getComment.locally('foobar')
3122
+ * ```
3123
+ *
3124
+ * Fetches a {@link Amity.Comment} object
3125
+ *
3126
+ * @param commentId the ID of the {@link Amity.Comment} to fetch
3127
+ * @returns the associated {@link Amity.Comment} object
3128
+ *
3129
+ * @category Comment API
3130
+ */
3131
+ getComment.locally = (commentId) => {
3132
+ var _a;
3133
+ const client = getActiveClient();
3134
+ client.log('comment/getComment.locally', commentId);
3135
+ const [comment] = (_a = pullFromCache('comment', commentId)) !== null && _a !== void 0 ? _a : [];
3136
+ return comment;
3137
+ };
3138
+
3139
+ /**
3140
+ * ```js
3141
+ * import { createComment } from '@amityco/ts-sdk'
3142
+ * const newComment = await createComment(bundle)
3143
+ * ```
3144
+ *
3145
+ * Creates an {@link Amity.Comment}
3146
+ *
3147
+ * @param bundle The data necessary to create a new {@link Amity.Comment}
3148
+ * @returns The newly created {@link Amity.Comment}
3149
+ *
3150
+ * @category Comment API
3151
+ * @async
3152
+ */
3153
+ const createComment = async (bundle) => {
3154
+ const client = getActiveClient();
3155
+ client.log('comment/createComment', bundle);
3156
+ const { data } = await client.http.post('/api/v3/comments', bundle);
3157
+ decoratePayload(data);
3158
+ ingestInCache(data);
3159
+ const post = await getPost(bundle.referenceId);
3160
+ fireEvent('v3.post.didUpdate', { posts: [post] });
3161
+ fireEvent('v3.comment.didCreate', data);
3162
+ const { comments } = data;
3163
+ return comments[0];
3164
+ };
3165
+
3166
+ /**
3167
+ * ```js
3168
+ * import { updateComment } from '@amityco/ts-sdk'
3169
+ * const updated = await updateComment(commentId, {
3170
+ * data: { text: 'hello world' }
3171
+ * })
3172
+ * ```
3173
+ *
3174
+ * Updates an {@link Amity.Comment}
3175
+ *
3176
+ * @param commentId The ID of the {@link Amity.Comment} to edit
3177
+ * @param patch The patch data to apply
3178
+ * @returns the updated {@link Amity.Comment} object
3179
+ *
3180
+ * @category Comment API
3181
+ * @async
3182
+ */
3183
+ const updateComment = async (commentId, patch) => {
3184
+ const client = getActiveClient();
3185
+ client.log('user/updateComment', patch);
3186
+ const { data } = await client.http.put(`/api/v3/comments/${commentId}`, patch);
3187
+ decoratePayload(data);
3188
+ ingestInCache(data);
3189
+ fireEvent('v3.comment.didUpdate', data);
3190
+ const { comments } = data;
3191
+ return comments.find(comment => comment.commentId === commentId);
3192
+ };
3193
+
3194
+ /**
3195
+ * ```js
3196
+ * import { deleteComment } from '@amityco/ts-sdk'
3197
+ * const success = await deleteComment('foobar')
3198
+ * ```
3199
+ *
3200
+ * Deletes a {@link Amity.Comment}
3201
+ *
3202
+ * @param commentId The {@link Amity.Comment} ID to delete
3203
+ * @return A success boolean if the {@link Amity.Comment} was deleted
3204
+ *
3205
+ * @category Comment API
3206
+ * @async
3207
+ */
3208
+ const deleteComment = async (commentId) => {
3209
+ const client = getActiveClient();
3210
+ client.log('comment/deleteComment', commentId);
3211
+ // API-FIX: This endpoint has not been implemented yet.
3212
+ await client.http.delete(`/api/v3/comments/${commentId}`);
3213
+ const deleted = await getComment(commentId);
3214
+ const post = await getPost(deleted.referenceId);
3215
+ fireEvent('v3.post.didUpdate', { posts: [post] });
3216
+ fireEvent('v3.comment.didDelete', { comments: [deleted] });
3217
+ return deleted;
3218
+ };
3219
+
3220
+ /** @hidden */
3221
+ const fetchReference = async (referenceType, referenceId) => {
3222
+ if (referenceType === 'message')
3223
+ return getMessage(referenceId);
3224
+ else if (referenceType === 'post')
3225
+ return getPost(referenceId);
3226
+ else if (referenceType === 'comment')
3227
+ return getComment(referenceId);
3228
+ throw new Error(`Incorrect referenceType: ${referenceType}`);
3229
+ };
3230
+
3231
+ /**
3232
+ * ```js
3233
+ * import { addReaction } from '@amityco/ts-sdk'
3234
+ * const success = await addReaction('post', postId, 'like')
3235
+ * ```
3236
+ *
3237
+ * Creates an {@link Amity.Reaction}
3238
+ *
3239
+ * @param referenceType The type of thing to add a {@link Amity.Reaction} to, such as a post or a comment.
3240
+ * @param referenceId The ID of the thing to add a new {@link Amity.Reaction} to.
3241
+ * @param reactionName Reaction name, such as a `like` or `love`.
3242
+ * @returns The added result.
3243
+ *
3244
+ * @category Reaction API
3245
+ * @async
3246
+ **/
3247
+ const addReaction = async (referenceType, referenceId, reactionName) => {
3248
+ var _a, _b;
3249
+ const client = getActiveClient();
3250
+ client.log('reaction/createReaction', {
3251
+ referenceId,
3252
+ referenceType,
3253
+ reactionName,
3254
+ });
3255
+ await client.http.post('/api/v2/reactions', { referenceId, referenceType, reactionName });
3256
+ const model = await fetchReference(referenceType, referenceId);
3257
+ dispatchReactable(referenceType, model);
3258
+ return (_b = (_a = model.myReactions) === null || _a === void 0 ? void 0 : _a.includes(reactionName)) !== null && _b !== void 0 ? _b : false;
3259
+ };
3260
+ /**
3261
+ * ```js
3262
+ * import { addReaction } from '@amityco/ts-sdk'
3263
+ * const success = addReaction.optimistically('post', postId, 'like')
3264
+ * ```
3265
+ *
3266
+ * Creates an {@link Amity.Reaction} optimistically
3267
+ *
3268
+ * @param referenceType The type of thing to add a {@link Amity.Reaction} to, such as a post or a comment.
3269
+ * @param referenceId The ID of the thing to add a new {@link Amity.Reaction} to.
3270
+ * @param reactionName Reaction name, such as a `like` or `love`.
3271
+ * @returns The added result.
3272
+ *
3273
+ * @category Reaction API
3274
+ **/
3275
+ addReaction.optimistically = (referenceType, referenceId, reactionName) => {
3276
+ var _a, _b;
3277
+ const model = mutateCache(referenceType, referenceId, model => {
3278
+ var _a, _b, _c;
3279
+ if ((_a = model.myReactions) === null || _a === void 0 ? void 0 : _a.includes(reactionName))
3280
+ return;
3281
+ return Object.assign(Object.assign({}, model), { syncedAt: -1, reactionsCount: model.reactionsCount + 1, myReactions: [...((_b = model.myReactions) !== null && _b !== void 0 ? _b : []), reactionName], reactions: Object.assign(Object.assign({}, model.reactions), { [reactionName]: ((_c = model.reactions[reactionName]) !== null && _c !== void 0 ? _c : 0) + 1 }) });
3282
+ });
3283
+ model && dispatchReactable(referenceType, model);
3284
+ return (_b = (_a = model === null || model === void 0 ? void 0 : model.myReactions) === null || _a === void 0 ? void 0 : _a.includes(reactionName)) !== null && _b !== void 0 ? _b : false;
3285
+ };
3286
+
3287
+ /**
3288
+ * ```js
3289
+ * import { deleteReaction } from '@amityco/ts-sdk'
3290
+ * const success = await deleteReaction('post', 'foobar', 'like')
3291
+ * ```
3292
+ *
3293
+ * Removes a {@link Amity.Reaction} from a {@link Amity.Reactable} object
3294
+ *
3295
+ * @param referenceType The type of thing to add a {@link Amity.Reaction} to, such as a post or a comment.
3296
+ * @param referenceId The ID of the thing to add a new {@link Amity.Reaction} to.
3297
+ * @param reactionName Reaction name, such as a `like` or `love`.
3298
+ * @returns The removed result.
3299
+ *
3300
+ * @category Reaction API
3301
+ * @async
3302
+ **/
3303
+ const removeReaction = async (referenceType, referenceId, reactionName) => {
3304
+ var _a, _b;
3305
+ const client = getActiveClient();
3306
+ client.log('reaction/removeReaction', {
3307
+ referenceId,
3308
+ referenceType,
3309
+ reactionName,
3310
+ });
3311
+ await client.http.delete(`/api/v2/reactions`, { data: { referenceId, referenceType, reactionName } });
3312
+ const model = await fetchReference(referenceType, referenceId);
3313
+ dispatchReactable(referenceType, model);
3314
+ return (_b = !((_a = model.myReactions) === null || _a === void 0 ? void 0 : _a.includes(reactionName))) !== null && _b !== void 0 ? _b : false;
3315
+ };
3316
+ /**
3317
+ * ```js
3318
+ * import { removeReaction } from '@amityco/ts-sdk'
3319
+ * const success = removeReaction.optimistically('post', postId, 'like')
3320
+ * ```
3321
+ *
3322
+ * Removes a {@link Amity.Reaction} from a {@link Amity.Reactable} object optimistically
3323
+ *
3324
+ * @param referenceType The type of thing to add a {@link Amity.Reaction} to, such as a post or a comment.
3325
+ * @param referenceId The ID of the thing to add a new {@link Amity.Reaction} to.
3326
+ * @param reactionName Reaction name, such as a `like` or `love`.
3327
+ * @returns The added result.
3328
+ *
3329
+ * @category Reaction API
3330
+ **/
3331
+ removeReaction.optimistically = (referenceType, referenceId, reactionName) => {
3332
+ var _a, _b;
3333
+ const model = mutateCache(referenceType, referenceId, model => {
3334
+ var _a, _b, _c;
3335
+ if (!((_a = model.myReactions) === null || _a === void 0 ? void 0 : _a.includes(reactionName)))
3336
+ return;
3337
+ return Object.assign(Object.assign({}, model), { syncedAt: -1, reactionsCount: Math.max(0, model.reactionsCount - 1), myReactions: ((_b = model.myReactions) !== null && _b !== void 0 ? _b : []).filter(item => item !== reactionName), reactions: Object.assign(Object.assign({}, model.reactions), { [reactionName]: Math.max(0, ((_c = model.reactions[reactionName]) !== null && _c !== void 0 ? _c : 0) - 1) }) });
3338
+ });
3339
+ model && dispatchReactable(referenceType, model);
3340
+ return (_b = !((_a = model === null || model === void 0 ? void 0 : model.myReactions) === null || _a === void 0 ? void 0 : _a.includes(reactionName))) !== null && _b !== void 0 ? _b : false;
3341
+ };
3342
+
3343
+ /**
3344
+ * ```js
3345
+ * import { onReactionRemoved } from '@amityco/ts-sdk'
3346
+ * const dispose = onReactionRemoved(message => {
3347
+ * // ...
3348
+ * })
3349
+ * ```
3350
+ *
3351
+ * Fired when an {@link Amity.Reaction} has been removed
3352
+ *
3353
+ * @param callback The function to call when the event was fired
3354
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3355
+ *
3356
+ * @category Message Events
3357
+ **/
3358
+ const onReactionRemoved = (referenceType, referenceId, callback) => {
3359
+ const client = getActiveClient();
3360
+ const filter = (payload) => {
3361
+ // TODO: lol
3362
+ decoratePayload(payload);
3363
+ ingestInCache(payload);
3364
+ };
3365
+ return createEventSubscriber(client, 'reaction/onReactionRemoved', 'v3.message.didUpdate', filter);
3366
+ };
3367
+
3368
+ var REFERENCE_TYPES = {
3369
+ post: {
3370
+ domainName: 'posts',
3371
+ eventName: 'v3/post.isflagbyme',
3372
+ primaryKey: 'postId',
3373
+ },
3374
+ comment: {
3375
+ domainName: 'comments',
3376
+ eventName: 'v3/comment.isflagbyme',
3377
+ primaryKey: 'commentId',
3378
+ },
3379
+ message: {
3380
+ domainName: 'messages',
3381
+ eventName: 'v3/message.isFlaggedByMe',
3382
+ primaryKey: 'messageId',
3383
+ },
3384
+ user: {
3385
+ domainName: 'users',
3386
+ eventName: 'user.isFlagByMe',
3387
+ primaryKey: 'userId',
3388
+ },
3389
+ };
3390
+
3391
+ /**
3392
+ * ```js
3393
+ * import { createReport } from '@amityco/ts-sdk'
3394
+ * const flagged = await createReport('post', postId)
3395
+ * ```
3396
+ *
3397
+ * @param referenceType The type of thing to add a report to, such as a post or a comment.
3398
+ * @param referenceId The ID of the thing to add a new report to.
3399
+ * @returns the created report result
3400
+ *
3401
+ * @category Report API
3402
+ * @async
3403
+ **/
3404
+ const createReport = async (referenceType, referenceId) => {
3405
+ const client = getActiveClient();
3406
+ client.log('report/createReport', { referenceType, referenceId });
3407
+ const { domainName } = REFERENCE_TYPES[referenceType];
3408
+ const { data } = await client.http.post(`/api/v3/${domainName}/${referenceId}/flag`);
3409
+ decoratePayload(data);
3410
+ ingestInCache(data);
3411
+ fireEvent(`v3.${referenceType}.didUpdate`, data);
3412
+ return !!data;
3413
+ };
3414
+
3415
+ /**
3416
+ * ```js
3417
+ * import { deleteReport } from '@amityco/ts-sdk'
3418
+ * const unflagged = await deleteReport('post', postId)
3419
+ * ```
3420
+ *
3421
+ * @param referenceType The type of thing to delete a report to, such as a post or a comment.
3422
+ * @param referenceId The ID of the thing to delete a report to.
3423
+ * @returns the deleted report result
3424
+ *
3425
+ * @category Report API
3426
+ * @async
3427
+ **/
3428
+ const deleteReport = async (referenceType, referenceId) => {
3429
+ const client = getActiveClient();
3430
+ client.log('report/deleteReport', { referenceType, referenceId });
3431
+ const { domainName } = REFERENCE_TYPES[referenceType];
3432
+ const { data } = await client.http.delete(`/api/v3/${domainName}/${referenceId}/unflag`);
3433
+ decoratePayload(data);
3434
+ ingestInCache(data);
3435
+ fireEvent(`v3.${referenceType}.didUpdate`, data);
3436
+ return !!data;
3437
+ };
3438
+
3439
+ /**
3440
+ * ```js
3441
+ * import { isReportedByMe } from '@amityco/ts-sdk'
3442
+ * const isReported = await isReportedByMe('post', postId)
3443
+ * ```
3444
+ *
3445
+ * @param referenceType The type of thing to check a report to, such as a post or a comment.
3446
+ * @param referenceId The ID of the thing to check a report to.
3447
+ * @returns `true` if the report is created by me, `false` if doesn't.
3448
+ *
3449
+ * @category Report API
3450
+ * @async
3451
+ **/
3452
+ const isReportedByMe = async (referenceType, referenceId) => {
3453
+ var _a, _b;
3454
+ const client = getActiveClient();
3455
+ client.log('report/isReportedByMe', { referenceType, referenceId });
3456
+ const { eventName, primaryKey } = REFERENCE_TYPES[referenceType];
3457
+ const { result, isFlagByMe } = (_a = (await synchronousWSCall(client, eventName, {
3458
+ [primaryKey]: referenceId,
3459
+ }))) !== null && _a !== void 0 ? _a : {};
3460
+ return (_b = result !== null && result !== void 0 ? result : isFlagByMe) !== null && _b !== void 0 ? _b : false;
3461
+ };
3462
+
3463
+ /**
3464
+ * ```js
3465
+ * import { queryChannels } from '@amityco/ts-sdk'
3466
+ * const channels = await queryChannels()
3467
+ * ```
3468
+ *
3469
+ * Queries a paginable list of {@link Amity.Channel} objects
3470
+ * Search is performed by displayName such as `.startsWith(search)`
3471
+ *
3472
+ * @param query The query parameters
3473
+ * @returns A page of {@link Amity.Channel} objects
3474
+ *
3475
+ * @category Channel API
3476
+ * @async
3477
+ */
3478
+ const queryChannels = async (query) => {
3479
+ const client = getActiveClient();
3480
+ client.log('channel/queryChannels', query);
3481
+ // safe decapsulation
3482
+ const _a = query !== null && query !== void 0 ? query : {}, { page, displayName, membership } = _a, params = __rest(_a, ["page", "displayName", "membership"]);
3483
+ // API-FIX: parameters should be querystring.
3484
+ // API-FIX: backend doesnt answer Amity.Response
3485
+ // const { data } = await client.http.get<Amity.Response<Amity.Paged<ChannelPayload>>>(
3486
+ const { data } = await client.http.get(`/api/v3/channels`, { params: Object.assign(Object.assign({}, params), { keyword: displayName, filter: membership, options: {
3487
+ token: toToken(page, 'skiplimit'),
3488
+ } }) });
3489
+ const { paging } = data, response = __rest(data, ["paging"]);
3490
+ decoratePayload(response);
3491
+ ingestInCache(response);
3492
+ const prevPage = toPage(paging === null || paging === void 0 ? void 0 : paging.previous);
3493
+ const nextPage = toPage(paging === null || paging === void 0 ? void 0 : paging.next);
3494
+ const { channels } = response;
3495
+ return { data: toRecord(channels), prevPage, nextPage };
3496
+ };
3497
+ /**
3498
+ * ```js
3499
+ * import { queryChannels } from '@amityco/ts-sdk'
3500
+ * const channels = queryChannels.locally()
3501
+ * ```
3502
+ *
3503
+ * Queries a paginable list of {@link Amity.Channel} objects from cache
3504
+ *
3505
+ * @param query The query parameters
3506
+ * @returns channels
3507
+ *
3508
+ * @category Channel API
3509
+ */
3510
+ queryChannels.locally = (query) => {
3511
+ const client = getActiveClient();
3512
+ client.log('channel/queryChannels.locally', query);
3513
+ // TODO
3514
+ };
3515
+
3516
+ /**
3517
+ * ```js
3518
+ * import { getChannels } from '@amityco/ts-sdk'
3519
+ * const channels = await getChannels(['foo', 'bar'])
3520
+ * ```
3521
+ *
3522
+ * Fetches a collection of {@link Amity.Channel} objects
3523
+ *
3524
+ * @param channelIds the IDs of the {@link Amity.Channel} to fetch
3525
+ * @returns the associated collection of {@link Amity.Channel} objects
3526
+ *
3527
+ * @category Channel API
3528
+ * @async
3529
+ */
3530
+ const getChannels = async (channelIds) => {
3531
+ const client = getActiveClient();
3532
+ client.log('channel/getChannels', channelIds);
3533
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
3534
+ const { data } = await client.http.get(`/api/v3/channels/list`, { params: { channelIds } });
3535
+ decoratePayload(data);
3536
+ ingestInCache(data);
3537
+ const { channels } = data;
3538
+ return toRecord(channels);
3539
+ };
3540
+ /**
3541
+ * ```js
3542
+ * import { getChannels } from '@amityco/ts-sdk'
3543
+ * const channels = getChannels.locally(['foo', 'bar']) ?? []
3544
+ * ```
3545
+ *
3546
+ * Fetches a collection of {@link Amity.Channel} objects from cache
3547
+ *
3548
+ * @param channelIds the IDs of the {@link Amity.Channel} to fetch
3549
+ * @returns the associated collection of {@link Amity.Channel} objects
3550
+ *
3551
+ * @category Channel API
3552
+ */
3553
+ getChannels.locally = (channelIds) => {
3554
+ var _a;
3555
+ const client = getActiveClient();
3556
+ client.log('channel/getChannels.locally', channelIds);
3557
+ const cached = (_a = pullFromCache('channel', ...channelIds)) !== null && _a !== void 0 ? _a : [];
3558
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) === channelIds.length)
3559
+ return toRecord(cached);
3560
+ };
3561
+
3562
+ /**
3563
+ * ```js
3564
+ * import { getChannel } from '@amityco/ts-sdk'
3565
+ * const channel = await getChannel('foobar')
3566
+ * ```
3567
+ *
3568
+ * Fetches a {@link Amity.Channel} object
3569
+ *
3570
+ * @param channelId the ID of the {@link Amity.Channel} to fetch
3571
+ * @returns the associated {@link Amity.Channel} object
3572
+ *
3573
+ * @category Channel API
3574
+ * @async
3575
+ */
3576
+ const getChannel = async (channelId) => {
3577
+ const client = getActiveClient();
3578
+ client.log('channel/getChannel', channelId);
3579
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
3580
+ const { data } = await client.http.get(`/api/v3/channels/${channelId}`);
3581
+ decoratePayload(data);
3582
+ ingestInCache(data);
3583
+ const { channels } = data;
3584
+ return channels.find(channel => channel.channelId === channelId);
3585
+ };
3586
+ /**
3587
+ * ```js
3588
+ * import { getChannel } from '@amityco/ts-sdk'
3589
+ * const channel = getChannel.locally('foobar')
3590
+ * ```
3591
+ *
3592
+ * Fetches a {@link Amity.Channel} object from cache
3593
+ *
3594
+ * @param channelId the ID of the {@link Amity.Channel} to fetch
3595
+ * @returns the associated {@link Amity.Channel} object
3596
+ *
3597
+ * @category Channel API
3598
+ */
3599
+ getChannel.locally = (channelId) => {
3600
+ var _a;
3601
+ const client = getActiveClient();
3602
+ client.log('channel/getChannel.locally', channelId);
3603
+ const [channel] = (_a = pullFromCache('channel', channelId)) !== null && _a !== void 0 ? _a : [];
3604
+ return channel;
3605
+ };
3606
+
3607
+ /**
3608
+ * ```js
3609
+ * import { createChannel } from '@amityco/ts-sdk'
3610
+ * const created = await createChannel({ channelId: 'foobar', displayName: 'foobar' })
3611
+ * ```
3612
+ *
3613
+ * Creates an {@link Amity.Channel}
3614
+ *
3615
+ * @param bundle The data necessary to create a new {@link Amity.Channel}
3616
+ * @returns The newly created {@link Amity.Channel}
3617
+ *
3618
+ * @category Channel API
3619
+ * @async
3620
+ */
3621
+ const createChannel = async (bundle) => {
3622
+ const client = getActiveClient();
3623
+ client.log('user/createChannel', bundle);
3624
+ const { data } = await client.http.post('/api/v3/channels', bundle);
3625
+ decoratePayload(data);
3626
+ ingestInCache(data);
3627
+ // no need for event, fired by server
3628
+ const { channels } = data;
3629
+ return channels[0];
3630
+ };
3631
+
3632
+ /**
3633
+ * ```js
3634
+ * import { updateChannel } from '@amityco/ts-sdk'
3635
+ * const updated = await updateChannel(channelId, { displayName: 'foobar' })
3636
+ * ```
3637
+ *
3638
+ * Updates an {@link Amity.Channel}
3639
+ *
3640
+ * @param channelId The ID of the {@link Amity.Channel} to edit
3641
+ * @param patch The patch data to apply
3642
+ * @returns the updated {@link Amity.Channel} object
3643
+ *
3644
+ * @category Channel API
3645
+ * @async
3646
+ */
3647
+ const updateChannel = async (channelId, patch) => {
3648
+ const client = getActiveClient();
3649
+ client.log('channel/updateChannel', channelId, patch);
3650
+ const { data } = await client.http.put(`/api/v3/channels/${channelId}`, patch);
3651
+ decoratePayload(data);
3652
+ ingestInCache(data);
3653
+ // no need for event, fired by server
3654
+ const { channels } = data;
3655
+ return channels.find(channel => channel.channelId === channelId);
3656
+ };
3657
+
3658
+ /**
3659
+ * ```js
3660
+ * import { deleteChannel } from '@amityco/ts-sdk'
3661
+ * const success = await deleteChannel('foobar')
3662
+ * ```
3663
+ *
3664
+ * Deletes a {@link Amity.Channel}
3665
+ *
3666
+ * @param channelId The {@link Amity.Channel} ID to delete
3667
+ * @return A success boolean if the {@link Amity.Channel} was deleted
3668
+ *
3669
+ * @category Channel API
3670
+ * @async
3671
+ */
3672
+ const deleteChannel = async (channelId) => {
3673
+ const client = getActiveClient();
3674
+ client.log('channel/deleteChannel', channelId);
3675
+ // API-FIX: This endpoint has not been implemented yet.
3676
+ await client.http.delete(`/api/v3/channels/${channelId}`);
3677
+ const deleted = await getChannel(channelId);
3678
+ // no need for event, fired by server
3679
+ return deleted;
3680
+ };
3681
+
3682
+ /**
3683
+ * ```js
3684
+ * import { joinChannel } from '@amityco/ts-sdk'
3685
+ * const isJoined = await joinChannel('foobar')
3686
+ * ```
3687
+ *
3688
+ * Joins a {@link Amity.Channel} object
3689
+ *
3690
+ * @param channelId the {@link Amity.Channel} to join
3691
+ * @returns A success boolean if the {@link Amity.Channel} was joined
3692
+ *
3693
+ * @category Channel API
3694
+ * @async
3695
+ */
3696
+ const joinChannel = async (channelId) => {
3697
+ const client = getActiveClient();
3698
+ client.log('channel/joinChannel', channelId);
3699
+ const { data } = await client.http.post(`/api/v3/channels/${channelId}/join`);
3700
+ decoratePayload(data);
3701
+ ingestInCache(data);
3702
+ // no need for event, fired by server
3703
+ const { channelUsers } = data;
3704
+ return !!channelUsers.find(channelUser => (channelUser.channelId === channelId
3705
+ && channelUser.membership === 'member'));
3706
+ };
3707
+
3708
+ /**
3709
+ * ```js
3710
+ * import { leaveChannel } from '@amityco/ts-sdk'
3711
+ * const isLeft = await leaveChannel('foobar')
3712
+ * ```
3713
+ *
3714
+ * Leave a {@link Amity.Channel} object
3715
+ *
3716
+ * @param channelId the {@link Amity.Channel} to leave
3717
+ * @returns A success boolean if the {@link Amity.Channel} was left
3718
+ *
3719
+ * @category Channel API
3720
+ * @async
3721
+ */
3722
+ const leaveChannel = async (channelId) => {
3723
+ const client = getActiveClient();
3724
+ client.log('channel/leaveChannel', channelId);
3725
+ const { data } = await client.http.delete(`/api/v3/channels/${channelId}/leave`);
3726
+ decoratePayload(data);
3727
+ ingestInCache(data);
3728
+ // no need for event, fired by server
3729
+ const { channelUsers } = data;
3730
+ return !!channelUsers.find(channelUser => (channelUser.channelId === channelId
3731
+ && channelUser.membership !== 'member'));
3732
+ };
3733
+
3734
+ /**
3735
+ * ```js
3736
+ * import { queryChannelMembers } from '@amityco/ts-sdk'
3737
+ * const channelMembers = await queryChannelMembers({ channelId: 'foo' })
3738
+ * ```
3739
+ *
3740
+ * Queries a paginable list of {@link Amity.ChannelUser} objects
3741
+ *
3742
+ * @param query The query parameters
3743
+ * @returns A page of {@link Amity.ChannelUser} objects
3744
+ *
3745
+ * @category Channel API
3746
+ * @async
3747
+ **/
3748
+ const queryChannelMembers = async (query) => {
3749
+ const client = getActiveClient();
3750
+ client.log('channel/queryChannelMembers', query);
3751
+ const _a = query !== null && query !== void 0 ? query : {}, { page, channelId, membership } = _a, params = __rest(_a, ["page", "channelId", "membership"]);
3752
+ const { data } = await client.http.get(`/api/v3/channels/${channelId}/users`, {
3753
+ params: Object.assign(Object.assign({}, params), { filter: membership, options: {
3754
+ token: toToken(page, 'skiplimit'),
3755
+ } }),
3756
+ });
3757
+ const { paging } = data, response = __rest(data, ["paging"]);
3758
+ decoratePayload(response);
3759
+ ingestInCache(response);
3760
+ const { channelUsers } = response;
3761
+ const nextPage = toPage(paging.next);
3762
+ const prevPage = toPage(paging.previous);
3763
+ return { data: toRecord(channelUsers), nextPage, prevPage };
3764
+ };
3765
+ /**
3766
+ * ```js
3767
+ * import { queryChannelMembers } from '@amityco/ts-sdk'
3768
+ * const channelMembers = await queryChannelMembers(query)
3769
+ * ```
3770
+ *
3771
+ * Queries a paginable list of {@link Amity.Post} objects from cache
3772
+ *
3773
+ * @param query The query parameters
3774
+ * @returns posts
3775
+ *
3776
+ * @category Post API
3777
+ */
3778
+ queryChannelMembers.locally = (query) => {
3779
+ const client = getActiveClient();
3780
+ client.log('channel/queryChannelMembers', query);
3781
+ // TODO
3782
+ };
3783
+
3784
+ /**
3785
+ * ```js
3786
+ * import { addChannelMembers } from '@amityco/ts-sdk'
3787
+ * const updated = await addChannelMembers(channelId, ['foo', 'bar'])
3788
+ * ```
3789
+ *
3790
+ * Adds a list of {@link Amity.User} to a {@link Amity.Channel}
3791
+ *
3792
+ * @param channelId The ID of the {@link Amity.Channel} to perform
3793
+ * @param userIds The list of IDs {@link Amity.User} to add
3794
+ * @returns A success boolean if the {@link Amity.User} were added to the {@link Amity.Channel}
3795
+ *
3796
+ * @category Channel API
3797
+ * @async
3798
+ */
3799
+ const addChannelMembers = async (channelId, userIds) => {
3800
+ const client = getActiveClient();
3801
+ client.log('channel/addChannelMembers', channelId, userIds);
3802
+ const { data } = await client.http.post(`/api/v3/channels/${channelId}/users`, { channelId, userIds });
3803
+ decoratePayload(data);
3804
+ ingestInCache(data);
3805
+ fireEvent('v3.channel.didAddUsers', {
3806
+ channels: data.channels,
3807
+ });
3808
+ const { channelUsers } = data;
3809
+ return !!channelUsers.find(channelUser => channelUser.channelId === channelId && channelUser.membership === 'member');
3810
+ };
3811
+
3812
+ /**
3813
+ * ```js
3814
+ * import { removeChannelMembers } from '@amityco/ts-sdk'
3815
+ * const updated = await removeChannelMembers(channelId, ['foo', 'bar'])
3816
+ * ```
3817
+ *
3818
+ * Removes a list of {@link Amity.User} from a {@link Amity.Channel}
3819
+ *
3820
+ * @param channelId The ID of the {@link Amity.Channel} to perform
3821
+ * @param userIds The list of IDs {@link Amity.User} to remove
3822
+ * @returns A success boolean if the list of {@link Amity.User} were removed from the {@link Amity.Channel}
3823
+ *
3824
+ * @category Channel API
3825
+ * @async
3826
+ */
3827
+ const removeChannelMembers = async (channelId, userIds) => {
3828
+ const client = getActiveClient();
3829
+ client.log('channel/removeChannelMembers', channelId, userIds);
3830
+ const { data } = await client.http.delete(`/api/v3/channels/${channelId}/users`, { data: { channelId, userIds } });
3831
+ decoratePayload(data);
3832
+ ingestInCache(data);
3833
+ fireEvent('v3.channel.didRemoveUsers', {
3834
+ channels: data.channels,
3835
+ });
3836
+ const { channelUsers } = data;
3837
+ return !!channelUsers.find(channelUser => channelUser.channelId === channelId && channelUser.membership !== 'member');
3838
+ };
3839
+
3840
+ /**
3841
+ * ```js
3842
+ * import { addChannelMembersRole } from '@amityco/ts-sdk'
3843
+ * const updated = await addChannelMembersRole(channelId, 'foo', ['bar'])
3844
+ * ```
3845
+ *
3846
+ * Adds an {@link Amity.Role} to a list of {@link Amity.User} on a {@link Amity.Channel}
3847
+ *
3848
+ * @param channelId The ID of the {@link Amity.Channel} to perform
3849
+ * @param roleId The ID of the {@link Amity.Role} to apply
3850
+ * @param userId Array of IDs of the {@link Amity.User} to perform
3851
+ * @returns A success boolean if the {@link Amity.Role} were added to list of {@link Amity.User} in the {@link Amity.Channel}
3852
+ *
3853
+ * @category Channel API
3854
+ * @async
3855
+ */
3856
+ const addChannelMembersRole = async (channelId, roleId, userIds) => {
3857
+ const client = getActiveClient();
3858
+ client.log('channel/addChannelMembersRole', channelId, roleId, userIds);
3859
+ const { data } = await client.http.post(`/api/v3/channels/${channelId}/users/roles`, { channelId, role: roleId, userIds });
3860
+ decoratePayload(data);
3861
+ ingestInCache(data);
3862
+ const { channelUsers } = data;
3863
+ return !!channelUsers.find(channelUser => channelUser.channelId === channelId && channelUser.roles.includes(roleId));
3864
+ };
3865
+
3866
+ /**
3867
+ * ```js
3868
+ * import { removeChannelMembersRole } from '@amityco/ts-sdk'
3869
+ * const updated = await removeChannelMembersRole(channelId, 'foo', ['bar'])
3870
+ * ```
3871
+ *
3872
+ * Removes an {@link Amity.Role} from a list of {@link Amity.User} on a {@link Amity.Channel}
3873
+ *
3874
+ * @param channelId The ID of the {@link Amity.Channel} to perform
3875
+ * @param roleId The ID of the {@link Amity.Role} to apply
3876
+ * @param userId Array of IDs of the {@link Amity.User} to perform
3877
+ * @returns A success boolean if the {@link Amity.Role} were removed from list of {@link Amity.User} in the {@link Amity.Channel}
3878
+ *
3879
+ * @category Channel API
3880
+ * @async
3881
+ */
3882
+ const removeChannelMembersRole = async (channelId, roleId, userIds) => {
3883
+ const client = getActiveClient();
3884
+ client.log('channel/removeChannelMembersRole', channelId, roleId, userIds);
3885
+ const { data } = await client.http.delete(`/api/v3/channels/${channelId}/users/roles`, { data: { channelId, role: roleId, userIds } });
3886
+ decoratePayload(data);
3887
+ ingestInCache(data);
3888
+ const { channelUsers } = data;
3889
+ return !!channelUsers.find(channelUser => channelUser.channelId === channelId && !channelUser.roles.includes(roleId));
3890
+ };
3891
+
3892
+ /**
3893
+ * ```js
3894
+ * import { onChannelUpdated } from '@amityco/ts-sdk'
3895
+ * const dispose = onChannelUpdated(channel => {
3896
+ * // ...
3897
+ * })
3898
+ * ```
3899
+ *
3900
+ * Fired when any {@link Amity.Channel} have been updated
3901
+ *
3902
+ * @param callback The function to call when the event was fired
3903
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3904
+ *
3905
+ * @category Channel Events
3906
+ */
3907
+ const onChannelUpdated = (callback) => {
3908
+ const client = getActiveClient();
3909
+ const filter = (payload) => {
3910
+ decoratePayload(payload);
3911
+ ingestInCache(payload);
3912
+ callback(payload.channels[0]);
3913
+ };
3914
+ return createEventSubscriber(client, 'onChannelUpdated', 'v3.channel.didUpdate', filter);
3915
+ };
3916
+
3917
+ /**
3918
+ * ```js
3919
+ * import { onChannelDeleted } from '@amityco/ts-sdk'
3920
+ * const dispose = onChannelDeleted(channel => {
3921
+ * // ...
3922
+ * })
3923
+ * ```
3924
+ *
3925
+ * Fired when any {@link Amity.Channel} have been deleted
3926
+ *
3927
+ * @param callback The function to call when the event was fired
3928
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3929
+ *
3930
+ * @category Channel Events
3931
+ */
3932
+ const onChannelDeleted = (callback) => {
3933
+ const client = getActiveClient();
3934
+ const filter = (payload) => {
3935
+ decoratePayload(payload);
3936
+ ingestInCache(payload);
3937
+ callback(payload.channels[0]);
3938
+ };
3939
+ return createEventSubscriber(client, 'onChannelDeleted', 'v3.channel.didDelete', filter);
3940
+ };
3941
+
3942
+ /**
3943
+ * ```js
3944
+ * import { onChannelJoined } from '@amityco/ts-sdk'
3945
+ * const dispose = onChannelJoined(channel => {
3946
+ * // ...
3947
+ * })
3948
+ * ```
3949
+ *
3950
+ * Fired when any {@link Amity.Channel} was joined
3951
+ *
3952
+ * @param callback The function to call when the event was fired
3953
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3954
+ *
3955
+ * @category Channel Events
3956
+ */
3957
+ const onChannelJoined = (callback) => {
3958
+ const client = getActiveClient();
3959
+ const filter = (payload) => {
3960
+ decoratePayload(payload);
3961
+ ingestInCache(payload);
3962
+ callback(payload.channels[0]);
3963
+ };
3964
+ return createEventSubscriber(client, 'onChannelJoined', 'v3.channel.didJoin', filter);
3965
+ };
3966
+
3967
+ /**
3968
+ * ```js
3969
+ * import { onChannelLeft } from '@amityco/ts-sdk'
3970
+ * const dispose = onChannelLeft(channel => {
3971
+ * // ...
3972
+ * })
3973
+ * ```
3974
+ *
3975
+ * Fired when any {@link Amity.Channel} was left
3976
+ *
3977
+ * @param callback The function to call when the event was fired
3978
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3979
+ *
3980
+ * @category Channel Events
3981
+ */
3982
+ const onChannelLeft = (callback) => {
3983
+ const client = getActiveClient();
3984
+ const filter = (payload) => {
3985
+ decoratePayload(payload);
3986
+ ingestInCache(payload);
3987
+ callback(payload.channels[0]);
3988
+ };
3989
+ return createEventSubscriber(client, 'onChannelLeft', 'v3.channel.didLeave', filter);
3990
+ };
3991
+
3992
+ /**
3993
+ * ```js
3994
+ * import { onMemberAdded } from '@amityco/ts-sdk'
3995
+ * const dispose = onMemberAdded(channel => {
3996
+ * // ...
3997
+ * })
3998
+ * ```
3999
+ *
4000
+ * Fired when any {@link Amity.User} has been added to any {@link Amity.Channel}
4001
+ *
4002
+ * @param callback The function to call when the event was fired
4003
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4004
+ *
4005
+ * @category Channel Events
4006
+ */
4007
+ const onMemberAdded = (callback) => {
4008
+ const client = getActiveClient();
4009
+ const filter = (payload) => {
4010
+ decoratePayload(payload);
4011
+ ingestInCache(payload);
4012
+ callback(payload.channels[0]);
4013
+ };
4014
+ return createEventSubscriber(client, 'onMemberAdded', 'v3.channel.didAddUsers', filter);
4015
+ };
4016
+
4017
+ /**
4018
+ * ```js
4019
+ * import { onMemberRemoved } from '@amityco/ts-sdk'
4020
+ * const dispose = onMemberRemoved(channel => {
4021
+ * // ...
4022
+ * })
4023
+ * ```
4024
+ *
4025
+ * Fired when any {@link Amity.User} has been removed from any {@link Amity.Channel}
4026
+ *
4027
+ * @param callback The function to call when the event was fired
4028
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4029
+ *
4030
+ * @category Channel Events
4031
+ */
4032
+ const onMemberRemoved = (callback) => {
4033
+ const client = getActiveClient();
4034
+ const filter = (payload) => {
4035
+ decoratePayload(payload);
4036
+ ingestInCache(payload);
4037
+ callback(payload.channels[0]);
4038
+ };
4039
+ return createEventSubscriber(client, 'onMemberRemoved', 'v3.channel.didRemoveUsers', filter);
4040
+ };
4041
+
4042
+ /**
4043
+ * ```js
4044
+ * import { observeChannel } from '@amityco/ts-sdk'
4045
+ *
4046
+ * let channel = {}
4047
+ * const dispose = observeChannel(channelId, ({ data }) => channel = data)
4048
+ * ```
4049
+ *
4050
+ * Observe all mutation on a given {@link Amity.Channel}
4051
+ *
4052
+ * @param channelId the ID of the channel to observe
4053
+ * @param callback the function to call when new data are available
4054
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channel
4055
+ *
4056
+ * @category Channel Observer
4057
+ */
4058
+ const observeChannel = (channelId, callback) => {
4059
+ const { log } = getActiveClient();
4060
+ const timestamp = Date.now();
4061
+ log(`observeChannel(tmpid: ${timestamp}) > listen`);
4062
+ // wrapper function to make sure
4063
+ const router = (result, action) => {
4064
+ var _a, _b, _c;
4065
+ // filter function
4066
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.channelId) !== channelId)
4067
+ return;
4068
+ if (callback instanceof Function)
4069
+ return callback(result);
4070
+ if (action !== 'onFetch')
4071
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4072
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
4073
+ };
4074
+ const disposers = [];
4075
+ disposers.push(onChannelUpdated(data => router({ data }, 'onUpdate')), onChannelDeleted(data => router({ data }, 'onDelete')), onChannelJoined(data => router({ data }, 'onJoin')), onChannelLeft(data => router({ data }, 'onLeft')), onMemberAdded(data => router({ data }, 'onMemberAdded')), onMemberRemoved(data => router({ data }, 'onMemberRemoved')));
4076
+ runQuery(createQuery(getChannel, channelId), result => result.data && router(result, 'onFetch'));
4077
+ return () => {
4078
+ log(`observeChannel(tmpid: ${timestamp}) > dispose`);
4079
+ disposers.forEach(fn => fn());
4080
+ };
4081
+ };
4082
+
4083
+ /**
4084
+ * ```js
4085
+ * import { onMessageCreated } from '@amityco/ts-sdk'
4086
+ * const dispose = onMessageCreated(message => {
4087
+ * // ...
4088
+ * })
4089
+ * ```
4090
+ *
4091
+ * Fired when an {@link Amity.Message} has been created
4092
+ *
4093
+ * @param callback The function to call when the event was fired
4094
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4095
+ *
4096
+ * @category Message Events
4097
+ */
4098
+ const onMessageCreated = (callback) => {
4099
+ const client = getActiveClient();
4100
+ const filter = (payload) => {
4101
+ decoratePayload(payload);
4102
+ ingestInCache(payload);
4103
+ callback(payload.messages[0]);
4104
+ };
4105
+ return createEventSubscriber(client, 'message/onMessageCreated', 'v3.message.didCreate', filter);
4106
+ };
4107
+
4108
+ /**
4109
+ * ```js
4110
+ * import { onMessageUpdated } from '@amityco/ts-sdk'
4111
+ * const dispose = onMessageUpdated(message => {
4112
+ * // ...
4113
+ * })
4114
+ * ```
4115
+ *
4116
+ * Fired when an {@link Amity.Message} has been updated
4117
+ *
4118
+ * @param callback The function to call when the event was fired
4119
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4120
+ *
4121
+ * @category Message Events
4122
+ */
4123
+ const onMessageUpdated = (callback) => {
4124
+ const client = getActiveClient();
4125
+ const filter = (payload) => {
4126
+ decoratePayload(payload);
4127
+ ingestInCache(payload);
4128
+ callback(payload.messages[0]);
4129
+ };
4130
+ return createEventSubscriber(client, 'message/onMessageUpdated', 'v3.message.didUpdate', filter);
4131
+ };
4132
+
4133
+ /**
4134
+ * ```js
4135
+ * import { onMessageDeleted } from '@amityco/ts-sdk'
4136
+ * const dispose = onMessageDeleted(message => {
4137
+ * // ...
4138
+ * })
4139
+ * ```
4140
+ *
4141
+ * Fired when an {@link Amity.Message} was deleted
4142
+ *
4143
+ * @param callback The function to call when the event was fired
4144
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4145
+ *
4146
+ * @category Message Events
4147
+ */
4148
+ const onMessageDeleted = (callback) => {
4149
+ const client = getActiveClient();
4150
+ const filter = (payload) => {
4151
+ decoratePayload(payload);
4152
+ ingestInCache(payload);
4153
+ callback(payload.messages[0]);
4154
+ };
4155
+ return createEventSubscriber(client, 'message/onMessageDeleted', 'v3.message.didDelete', filter);
4156
+ };
4157
+
4158
+ /**
4159
+ * ```js
4160
+ * import { observeMessage } from '@amityco/ts-sdk'
4161
+ *
4162
+ * let message = {}
4163
+ * const unsub = observeMessage(messageId, updated => message = updated)
4164
+ * ```
4165
+ *
4166
+ * Observe all mutations on a {@link Amity.Message} given a single messageId
4167
+ *
4168
+ * @param client the client to observe the message with
4169
+ * @param messageId the ID of the message to observe
4170
+ * @param callback the function to call when new data are available
4171
+ * @param policy a query policy option for this observer
4172
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the message
4173
+ *
4174
+ * @category Message Observer
4175
+ */
4176
+ const observeMessage = (messageId, callback, policy = 'cache_then_server') => {
4177
+ const { log } = getActiveClient();
4178
+ const timestamp = Date.now();
4179
+ log(`observeMessage(tmpid: ${timestamp}) > listen`);
4180
+ // wrapper function to make sure
4181
+ const router = (result, action) => {
4182
+ var _a, _b, _c;
4183
+ // filter function
4184
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.messageId) !== messageId)
4185
+ return;
4186
+ if (callback instanceof Function)
4187
+ return callback(result);
4188
+ if (action !== 'onFetch')
4189
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4190
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
4191
+ };
4192
+ const disposers = [];
4193
+ disposers.push(onMessageUpdated(message => router(message, 'onUpdate')), onMessageDeleted(message => router(message, 'onDelete')));
4194
+ if (policy !== 'no_fetch') {
4195
+ runQuery(createQuery(getMessage, messageId), (result) => result.data && router(result, 'onFetch'), queryOptions(policy));
4196
+ }
4197
+ return () => {
4198
+ log(`observeMessages(tmpid: ${timestamp}) > dispose`);
4199
+ disposers.forEach(fn => fn());
4200
+ };
4201
+ };
4202
+
4203
+ /**
4204
+ * ```js
4205
+ * import { observeMessages } from '@amityco/ts-sdk'
4206
+ *
4207
+ * let messages = []
4208
+ * const unsub = observeMessages(channelId, message => merge(messages, message))
4209
+ * ```
4210
+ *
4211
+ * Observe all mutations on a list of {@link Amity.Message} for a given {@link Amity.Channel} object
4212
+ *
4213
+ * @param client the client to observe the message with
4214
+ * @param channelId the ID of the channel where to observe the messages
4215
+ * @param callback the function to call when new data are available
4216
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
4217
+ *
4218
+ * @category Message Observer
4219
+ */
4220
+ const observeMessages = (channelId, callback) => {
4221
+ const { log } = getActiveClient();
4222
+ const timestamp = Date.now();
4223
+ log(`observeMessages(tmpid: ${timestamp}) > listen`);
4224
+ const disposers = [];
4225
+ const router = (message, action) => {
4226
+ var _a, _b;
4227
+ if (message.channelId !== channelId)
4228
+ return;
4229
+ if (callback instanceof Function)
4230
+ return callback(message);
4231
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, message);
4232
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, message);
4233
+ };
4234
+ disposers.push(onMessageCreated(message => router(message, 'onCreate')), onMessageUpdated(message => router(message, 'onUpdate')), onMessageDeleted(message => router(message, 'onDelete')));
4235
+ return () => {
4236
+ log(`observeMessages(tmpid: ${timestamp}) > dispose`);
4237
+ disposers.forEach(fn => fn());
4238
+ };
4239
+ };
4240
+
4241
+ /**
4242
+ * ```js
4243
+ * import { onCommunityCreated } from '@amityco/ts-sdk'
4244
+ * const dispose = onCommunityCreated(channel => {
4245
+ * // ...
4246
+ * })
4247
+ * ```
4248
+ *
4249
+ * Fired when any {@link Amity.Community} have been created
4250
+ *
4251
+ * @param callback The function to call when the event was fired
4252
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4253
+ *
4254
+ * @category Community Events
4255
+ */
4256
+ const onCommunityCreated = (callback) => {
4257
+ const client = getActiveClient();
4258
+ const filter = (payload) => {
4259
+ decoratePayload(payload);
4260
+ ingestInCache(payload);
4261
+ callback(payload.communities[0]);
4262
+ };
4263
+ return createEventSubscriber(client, 'onCommunityCreated', 'v3.community.didCreate', filter);
4264
+ };
4265
+
4266
+ /**
4267
+ * ```js
4268
+ * import { onCommunityUpdated } from '@amityco/ts-sdk'
4269
+ * const dispose = onCommunityUpdated(channel => {
4270
+ * // ...
4271
+ * })
4272
+ * ```
4273
+ *
4274
+ * Fired when any {@link Amity.Community} have been updated
4275
+ *
4276
+ * @param callback The function to call when the event was fired
4277
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4278
+ *
4279
+ * @category Community Events
4280
+ */
4281
+ const onCommunityUpdated = (callback) => {
4282
+ const client = getActiveClient();
4283
+ const filter = (payload) => {
4284
+ decoratePayload(payload);
4285
+ ingestInCache(payload);
4286
+ callback(payload.communities[0]);
4287
+ };
4288
+ return createEventSubscriber(client, 'onCommunityUpdated', 'v3.community.didUpdate', filter);
4289
+ };
4290
+
4291
+ /**
4292
+ * ```js
4293
+ * import { onCommunityDeleted } from '@amityco/ts-sdk'
4294
+ * const dispose = onCommunityDeleted(channel => {
4295
+ * // ...
4296
+ * })
4297
+ * ```
4298
+ *
4299
+ * Fired when any {@link Amity.Community} have been deleted
4300
+ *
4301
+ * @param callback The function to call when the event was fired
4302
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4303
+ *
4304
+ * @category Community Events
4305
+ */
4306
+ const onCommunityDeleted = (callback) => {
4307
+ const client = getActiveClient();
4308
+ const filter = (payload) => {
4309
+ decoratePayload(payload);
4310
+ ingestInCache(payload);
4311
+ callback(payload.communities[0]);
4312
+ };
4313
+ return createEventSubscriber(client, 'onCommunityDeleted', 'v3.community.didDelete', filter);
4314
+ };
4315
+
4316
+ /**
4317
+ * ```js
4318
+ * import { onCommunityJoined } from '@amityco/ts-sdk'
4319
+ * const dispose = onCommunityJoined(channel => {
4320
+ * // ...
4321
+ * })
4322
+ * ```
4323
+ *
4324
+ * Fired when any {@link Amity.Community} was joined
4325
+ *
4326
+ * @param callback The function to call when the event was fired
4327
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4328
+ *
4329
+ * @category Community Events
4330
+ */
4331
+ const onCommunityJoined = (callback) => {
4332
+ const client = getActiveClient();
4333
+ const filter = (payload) => {
4334
+ decoratePayload(payload);
4335
+ ingestInCache(payload);
4336
+ callback(payload.communities[0]);
4337
+ };
4338
+ return createEventSubscriber(client, 'onCommunityJoined', 'v3.community.didJoin', filter);
4339
+ };
4340
+
4341
+ /**
4342
+ * ```js
4343
+ * import { onCommunityLeft } from '@amityco/ts-sdk'
4344
+ * const dispose = onCommunityLeft(channel => {
4345
+ * // ...
4346
+ * })
4347
+ * ```
4348
+ *
4349
+ * Fired when any {@link Amity.Community} was left
4350
+ *
4351
+ * @param callback The function to call when the event was fired
4352
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4353
+ *
4354
+ * @category Community Events
4355
+ */
4356
+ const onCommunityLeft = (callback) => {
4357
+ const client = getActiveClient();
4358
+ const filter = (payload) => {
4359
+ decoratePayload(payload);
4360
+ ingestInCache(payload);
4361
+ callback(payload.communities[0]);
4362
+ };
4363
+ return createEventSubscriber(client, 'onCommunityLeft', 'v3.community.didLeave', filter);
4364
+ };
4365
+
4366
+ /**
4367
+ * ```js
4368
+ * import { observeCommunity } from '@amityco/ts-sdk'
4369
+ *
4370
+ * let community = {}
4371
+ * const dispose = observeCommunity(communityId, updated => community = updated)
4372
+ * ```
4373
+ *
4374
+ * Observe all mutation on a given {@link Amity.Community}
4375
+ *
4376
+ * @param communityId the ID of the community to observe
4377
+ * @param callback the function to call when new data are available
4378
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community
4379
+ *
4380
+ * @category Community Observer
4381
+ */
4382
+ const observeCommunity = (communityId, callback) => {
4383
+ const { log } = getActiveClient();
4384
+ const timestamp = Date.now();
4385
+ log(`observeCommunity(tmpid: ${timestamp}) > listen`);
4386
+ // wrapper function to make sure
4387
+ const router = (result, action) => {
4388
+ var _a, _b, _c;
4389
+ // filter function
4390
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.communityId) !== communityId)
4391
+ return;
4392
+ if (callback instanceof Function)
4393
+ return callback(result);
4394
+ if (action !== 'onFetch')
4395
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4396
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
4397
+ };
4398
+ const disposers = [];
4399
+ disposers.push(onCommunityUpdated(data => router({ data }, 'onUpdate')), onCommunityDeleted(data => router({ data }, 'onDelete')), onCommunityJoined(data => router({ data }, 'onJoin')), onCommunityLeft(data => router({ data }, 'onLeft')));
4400
+ runQuery(createQuery(getCommunity, communityId), result => result.data && router(result, 'onFetch'));
4401
+ return () => {
4402
+ log(`observeCommunity(tmpid: ${timestamp}) > dispose`);
4403
+ disposers.forEach(fn => fn());
4404
+ };
4405
+ };
4406
+
4407
+ /**
4408
+ * ```js
4409
+ * import { queryGlobalFeed } from '@amityco/ts-sdk'
4410
+ * const posts = await queryGlobalFeed()
4411
+ * ```
4412
+ *
4413
+ * Queries a paginable list of {@link Amity.Post} objects
4414
+ *
4415
+ * @param query The query parameters
4416
+ * @returns A page of {@link Amity.Post} objects
4417
+ *
4418
+ * @category Feed API
4419
+ * @async
4420
+ **/
4421
+ const queryGlobalFeed = async (query) => {
4422
+ const client = getActiveClient();
4423
+ client.log('feed/queryGlobalFeed', query);
4424
+ const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
4425
+ const { data } = await client.http.get(`/api/v4/me/global-feeds`, { params: Object.assign(Object.assign({}, params), { options: {
4426
+ token: toToken(page, 'skiplimit')
4427
+ } }) });
4428
+ const { paging } = data, response = __rest(data, ["paging"]);
4429
+ decoratePayload(response);
4430
+ ingestInCache(response);
4431
+ const { posts } = response;
4432
+ const nextPage = toPage(paging.next);
4433
+ const prevPage = toPage(paging.previous);
4434
+ return { data: toRecord(posts), nextPage, prevPage };
4435
+ };
4436
+
4437
+ /**
4438
+ * ```js
4439
+ * import { onPostCreated } from '@amityco/ts-sdk'
4440
+ * const dispose = onPostCreated(post => {
4441
+ * // ...
4442
+ * })
4443
+ * ```
4444
+ *
4445
+ * Fired when an {@link Amity.Post} has been created
4446
+ *
4447
+ * @param callback The function to call when the event was fired
4448
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4449
+ *
4450
+ * @category Post Events
4451
+ */
4452
+ const onPostCreated = (callback) => {
4453
+ const client = getActiveClient();
4454
+ const filter = (payload) => {
4455
+ decoratePayload(payload);
4456
+ ingestInCache(payload);
4457
+ callback(payload.posts[0]);
4458
+ };
4459
+ return createEventSubscriber(client, 'message/onPostCreated', 'v3.post.didCreate', filter);
4460
+ };
4461
+
4462
+ /**
4463
+ * ```js
4464
+ * import { onPostUpdated } from '@amityco/ts-sdk'
4465
+ * const dispose = onPostUpdated(post => {
4466
+ * // ...
4467
+ * })
4468
+ * ```
4469
+ *
4470
+ * Fired when an {@link Amity.Post} has been updated
4471
+ *
4472
+ * @param callback The function to call when the event was fired
4473
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4474
+ *
4475
+ * @category Post Events
4476
+ */
4477
+ const onPostUpdated = (callback) => {
4478
+ const client = getActiveClient();
4479
+ const filter = (payload) => {
4480
+ decoratePayload(payload);
4481
+ ingestInCache(payload);
4482
+ callback(payload.posts[0]);
4483
+ };
4484
+ return createEventSubscriber(client, 'message/onPostUpdated', 'v3.post.didUpdate', filter);
4485
+ };
4486
+
4487
+ /**
4488
+ * ```js
4489
+ * import { onPostDeleted } from '@amityco/ts-sdk'
4490
+ * const dispose = onPostDeleted(post => {
4491
+ * // ...
4492
+ * })
4493
+ * ```
4494
+ *
4495
+ * Fired when an {@link Amity.Post} has been deleted
4496
+ *
4497
+ * @param callback The function to call when the event was fired
4498
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4499
+ *
4500
+ * @category Post Events
4501
+ */
4502
+ const onPostDeleted = (callback) => {
4503
+ const client = getActiveClient();
4504
+ const filter = (payload) => {
4505
+ decoratePayload(payload);
4506
+ ingestInCache(payload);
4507
+ callback(payload.posts[0]);
4508
+ };
4509
+ return createEventSubscriber(client, 'message/onPostDeleted', 'v3.post.didDelete', filter);
4510
+ };
4511
+
4512
+ /**
4513
+ * ```js
4514
+ * import { observePosts } from '@amityco/ts-sdk'
4515
+ *
4516
+ * let posts = []
4517
+ * const unsub = observePosts({
4518
+ * targetType: Amity.PostTargetType,
4519
+ * targetId: Amity.Post['targetId'],
4520
+ * }, post => merge(posts, post))
4521
+ * ```
4522
+ *
4523
+ * Observe all mutations on a list of {@link Amity.Post} for a given target object
4524
+ *
4525
+ * @param targetType the type of the target
4526
+ * @param targetId the ID of the target
4527
+ * @param callback the function to call when new data are available
4528
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
4529
+ *
4530
+ * @category Post Observer
4531
+ */
4532
+ const observePosts = (params, callback) => {
4533
+ const { log } = getActiveClient();
4534
+ const timestamp = Date.now();
4535
+ log(`observePosts(tmpid: ${timestamp}) > listen`);
4536
+ const disposers = [];
4537
+ const router = (post, action) => {
4538
+ var _a, _b;
4539
+ if (params.targetId !== post.targetId
4540
+ || params.targetType !== post.targetType)
4541
+ return;
4542
+ if (callback instanceof Function)
4543
+ return callback(post);
4544
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, post);
4545
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, post);
4546
+ };
4547
+ disposers.push(onPostCreated(post => router(post, 'onCreate')), onPostUpdated(post => router(post, 'onUpdate')), onPostDeleted(post => router(post, 'onDelete')));
4548
+ return () => {
4549
+ log(`observePosts(tmpid: ${timestamp}) > dispose`);
4550
+ disposers.forEach(fn => fn());
4551
+ };
4552
+ };
4553
+
4554
+ /**
4555
+ * ```js
4556
+ * import { observePost } from '@amityco/ts-sdk'
4557
+ *
4558
+ * let post = {}
4559
+ * const dispose = observePost(postId, updated => post = updated)
4560
+ * ```
4561
+ *
4562
+ * Observe all mutation on a given {@link Amity.Post}
4563
+ *
4564
+ * @param postId the ID of the post to observe
4565
+ * @param callback the function to call when new data are available
4566
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the post
4567
+ *
4568
+ * @category Post Observer
4569
+ */
4570
+ const observePost = (postId, callback, policy = 'cache_then_server') => {
4571
+ const { log } = getActiveClient();
4572
+ const timestamp = Date.now();
4573
+ log(`observePost(tmpid: ${timestamp}) > listen`);
4574
+ // wrapper function to make sure
4575
+ const router = (result, action) => {
4576
+ var _a, _b, _c;
4577
+ // filter function
4578
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.postId) !== postId)
4579
+ return;
4580
+ if (callback instanceof Function)
4581
+ return callback(result);
4582
+ if (action !== 'onFetch')
4583
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4584
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
4585
+ };
4586
+ const disposers = [];
4587
+ disposers.push(onPostUpdated(data => router({ data }, 'onUpdate')), onPostDeleted(data => router({ data }, 'onDelete')));
4588
+ runQuery(createQuery(getPost, postId), (result) => result.data && router(result, 'onFetch'), queryOptions(policy));
4589
+ return () => {
4590
+ log(`observePosts(tmpid: ${timestamp}) > dispose`);
4591
+ disposers.forEach(fn => fn());
4592
+ };
4593
+ };
4594
+
4595
+ /**
4596
+ * ```js
4597
+ * import { onCommentCreated } from '@amityco/ts-sdk'
4598
+ * const dispose = onCommentCreated(comment => {
4599
+ * // ...
4600
+ * })
4601
+ * ```
4602
+ *
4603
+ * Fired when an {@link Amity.Comment} has been created
4604
+ *
4605
+ * @param callback The function to call when the event was fired
4606
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4607
+ *
4608
+ * @category Comment Events
4609
+ */
4610
+ const onCommentCreated = (callback) => {
4611
+ const client = getActiveClient();
4612
+ const filter = (payload) => {
4613
+ decoratePayload(payload);
4614
+ ingestInCache(payload);
4615
+ callback(payload.comments[0]);
4616
+ };
4617
+ return createEventSubscriber(client, 'message/onCommentCreated', 'v3.comment.didCreate', filter);
4618
+ };
4619
+
4620
+ /**
4621
+ * ```js
4622
+ * import { onCommentUpdated } from '@amityco/ts-sdk'
4623
+ * const dispose = onCommentUpdated(comment => {
4624
+ * // ...
4625
+ * })
4626
+ * ```
4627
+ *
4628
+ * Fired when an {@link Amity.Comment} has been updated
4629
+ *
4630
+ * @param callback The function to call when the event was fired
4631
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4632
+ *
4633
+ * @category Comment Events
4634
+ */
4635
+ const onCommentUpdated = (callback) => {
4636
+ const client = getActiveClient();
4637
+ const filter = (payload) => {
4638
+ decoratePayload(payload);
4639
+ ingestInCache(payload);
4640
+ callback(payload.comments[0]);
4641
+ };
4642
+ return createEventSubscriber(client, 'message/onCommentUpdated', 'v3.comment.didUpdate', filter);
4643
+ };
4644
+
4645
+ /**
4646
+ * ```js
4647
+ * import { onCommentDeleted } from '@amityco/ts-sdk'
4648
+ * const dispose = onCommentDeleted(comment => {
4649
+ * // ...
4650
+ * })
4651
+ * ```
4652
+ *
4653
+ * Fired when an {@link Amity.Comment} has been deleted
4654
+ *
4655
+ * @param callback The function to call when the event was fired
4656
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4657
+ *
4658
+ * @category Comment Events
4659
+ */
4660
+ const onCommentDeleted = (callback) => {
4661
+ const client = getActiveClient();
4662
+ const filter = (payload) => {
4663
+ decoratePayload(payload);
4664
+ ingestInCache(payload);
4665
+ callback(payload.comments[0]);
4666
+ };
4667
+ return createEventSubscriber(client, 'message/onCommentDeleted', 'v3.comment.didDelete', filter);
4668
+ };
4669
+
4670
+ /**
4671
+ * ```js
4672
+ * import { observeComments } from '@amityco/ts-sdk'
4673
+ *
4674
+ * let comments = []
4675
+ * const unsub = observeComments(postId, comment => merge(comments, comment))
4676
+ * ```
4677
+ *
4678
+ * Observe all mutations on a list of {@link Amity.Comment} for a given {@link Amity.Post} object
4679
+ *
4680
+ * @param postId the ID of the post where to observe the comments
4681
+ * @param callback the function to call when new data are available
4682
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comments
4683
+ *
4684
+ * @category Comment Observer
4685
+ */
4686
+ const observeComments = (postId, callback) => {
4687
+ const { log } = getActiveClient();
4688
+ const timestamp = Date.now();
4689
+ log(`observeComments(tmpid: ${timestamp}) > listen`);
4690
+ const disposers = [];
4691
+ const router = (comment, action) => {
4692
+ var _a, _b;
4693
+ if (comment.referenceId !== postId)
4694
+ return;
4695
+ if (callback instanceof Function)
4696
+ return callback(comment);
4697
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, comment);
4698
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, comment);
4699
+ };
4700
+ disposers.push(onCommentCreated(comment => router(comment, 'onCreate')), onCommentUpdated(comment => router(comment, 'onUpdate')), onCommentDeleted(comment => router(comment, 'onDelete')));
4701
+ return () => {
4702
+ log(`observeComments(tmpid: ${timestamp}) > dispose`);
4703
+ disposers.forEach(fn => fn());
4704
+ };
4705
+ };
4706
+
4707
+ /**
4708
+ * ```js
4709
+ * import { observeComment } from '@amityco/ts-sdk'
4710
+ *
4711
+ * let comment = {}
4712
+ * const dispose = observeComment(commentId, ({ data }) => comment = data)
4713
+ * ```
4714
+ *
4715
+ * Observe all mutation on a given {@link Amity.Comment}
4716
+ *
4717
+ * @param commentId the ID of the comment to observe
4718
+ * @param callback the function to call when new data are available
4719
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comment
4720
+ *
4721
+ * @category Comment Observer
4722
+ */
4723
+ const observeComment = (commentId, callback, policy = 'cache_then_server') => {
4724
+ const { log } = getActiveClient();
4725
+ const timestamp = Date.now();
4726
+ log(`observeComment(tmpid: ${timestamp}) > listen`);
4727
+ // wrapper function to make sure
4728
+ const router = (result, action) => {
4729
+ var _a, _b, _c;
4730
+ // filter function
4731
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.commentId) !== commentId)
4732
+ return;
4733
+ if (callback instanceof Function)
4734
+ return callback(result);
4735
+ if (action !== 'onFetch')
4736
+ (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4737
+ (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
4738
+ };
4739
+ const disposers = [];
4740
+ disposers.push(onCommentUpdated(data => router({ data }, 'onUpdate')), onCommentDeleted(data => router({ data }, 'onDelete')));
4741
+ runQuery(createQuery(getComment, commentId), result => result.data && router(result, 'onFetch'), queryOptions(policy));
4742
+ return () => {
4743
+ log(`observeComment(tmpid: ${timestamp}) > dispose`);
4744
+ disposers.forEach(fn => fn());
4745
+ };
4746
+ };
4747
+
4748
+ exports.addChannelMembers = addChannelMembers;
4749
+ exports.addChannelMembersRole = addChannelMembersRole;
4750
+ exports.addCommunityMembers = addCommunityMembers;
4751
+ exports.addCommunityMembersRole = addCommunityMembersRole;
4752
+ exports.addReaction = addReaction;
4753
+ exports.clearCache = clearCache;
4754
+ exports.connectClient = connectClient;
4755
+ exports.createCache = createCache;
4756
+ exports.createChannel = createChannel;
4757
+ exports.createClient = createClient;
4758
+ exports.createComment = createComment;
4759
+ exports.createCommunity = createCommunity;
4760
+ exports.createFile = createFile;
4761
+ exports.createMessage = createMessage;
4762
+ exports.createPost = createPost;
4763
+ exports.createQuery = createQuery;
4764
+ exports.createReport = createReport;
4765
+ exports.decorateModel = decorateModel;
4766
+ exports.decorateModels = decorateModels;
4767
+ exports.decoratePayload = decoratePayload;
4768
+ exports.deleteChannel = deleteChannel;
4769
+ exports.deleteComment = deleteComment;
4770
+ exports.deleteCommunity = deleteCommunity;
4771
+ exports.deleteFile = deleteFile;
4772
+ exports.deleteMessage = deleteMessage;
4773
+ exports.deletePost = deletePost;
4774
+ exports.deleteReport = deleteReport;
4775
+ exports.disconnectClient = disconnectClient;
4776
+ exports.dropFromCache = dropFromCache;
4777
+ exports.enableCache = enableCache;
4778
+ exports.fileUrlWithSize = fileUrlWithSize;
4779
+ exports.filterByPropEquality = filterByPropEquality;
4780
+ exports.getActiveClient = getActiveClient;
4781
+ exports.getChannel = getChannel;
4782
+ exports.getChannels = getChannels;
4783
+ exports.getComment = getComment;
4784
+ exports.getComments = getComments;
4785
+ exports.getCommunities = getCommunities;
4786
+ exports.getCommunity = getCommunity;
4787
+ exports.getFile = getFile;
4788
+ exports.getMessage = getMessage;
4789
+ exports.getMessages = getMessages;
4790
+ exports.getPost = getPost;
4791
+ exports.getPosts = getPosts;
4792
+ exports.getRole = getRole;
4793
+ exports.getUser = getUser;
4794
+ exports.getUsers = getUsers;
4795
+ exports.ingestInCache = ingestInCache;
4796
+ exports.isAfterBefore = isAfterBefore;
4797
+ exports.isConnected = isConnected;
4798
+ exports.isFetcher = isFetcher;
4799
+ exports.isFresh = isFresh;
4800
+ exports.isLocal = isLocal;
4801
+ exports.isMutator = isMutator;
4802
+ exports.isOffline = isOffline;
4803
+ exports.isPaged = isPaged;
4804
+ exports.isReportedByMe = isReportedByMe;
4805
+ exports.isSkipLimit = isSkipLimit;
4806
+ exports.isSyncable = isSyncable;
4807
+ exports.isSynced = isSynced;
4808
+ exports.joinChannel = joinChannel;
4809
+ exports.joinCommunity = joinCommunity;
4810
+ exports.leaveChannel = leaveChannel;
4811
+ exports.leaveCommunity = leaveCommunity;
4812
+ exports.memoryStore = memoryStore;
4813
+ exports.memoryStores = memoryStores;
4814
+ exports.mergeInCache = mergeInCache;
4815
+ exports.mutateCache = mutateCache;
4816
+ exports.observeChannel = observeChannel;
4817
+ exports.observeComment = observeComment;
4818
+ exports.observeComments = observeComments;
4819
+ exports.observeCommunity = observeCommunity;
4820
+ exports.observeFile = observeFile;
4821
+ exports.observeMessage = observeMessage;
4822
+ exports.observeMessages = observeMessages;
4823
+ exports.observePost = observePost;
4824
+ exports.observePosts = observePosts;
4825
+ exports.observeUser = observeUser;
4826
+ exports.onChannelDeleted = onChannelDeleted;
4827
+ exports.onChannelJoined = onChannelJoined;
4828
+ exports.onChannelLeft = onChannelLeft;
4829
+ exports.onChannelUpdated = onChannelUpdated;
4830
+ exports.onClientDisconnected = onClientDisconnected;
4831
+ exports.onCommentCreated = onCommentCreated;
4832
+ exports.onCommentDeleted = onCommentDeleted;
4833
+ exports.onCommentUpdated = onCommentUpdated;
4834
+ exports.onCommunityCreated = onCommunityCreated;
4835
+ exports.onCommunityDeleted = onCommunityDeleted;
4836
+ exports.onCommunityJoined = onCommunityJoined;
4837
+ exports.onCommunityLeft = onCommunityLeft;
4838
+ exports.onCommunityUpdated = onCommunityUpdated;
4839
+ exports.onMemberAdded = onMemberAdded;
4840
+ exports.onMemberRemoved = onMemberRemoved;
4841
+ exports.onMessageCreated = onMessageCreated;
4842
+ exports.onMessageDeleted = onMessageDeleted;
4843
+ exports.onMessageUpdated = onMessageUpdated;
4844
+ exports.onPostCreated = onPostCreated;
4845
+ exports.onPostDeleted = onPostDeleted;
4846
+ exports.onPostUpdated = onPostUpdated;
4847
+ exports.onReactionRemoved = onReactionRemoved;
4848
+ exports.onUserUpdated = onUserUpdated;
4849
+ exports.persistentStore = persistentStore;
4850
+ exports.pullFromCache = pullFromCache;
4851
+ exports.pushToCache = pushToCache;
4852
+ exports.queryChannelMembers = queryChannelMembers;
4853
+ exports.queryChannels = queryChannels;
4854
+ exports.queryComments = queryComments;
4855
+ exports.queryCommunities = queryCommunities;
4856
+ exports.queryCommunityMembers = queryCommunityMembers;
4857
+ exports.queryGlobalFeed = queryGlobalFeed;
4858
+ exports.queryMessages = queryMessages;
4859
+ exports.queryOptions = queryOptions;
4860
+ exports.queryPosts = queryPosts;
4861
+ exports.queryRoles = queryRoles;
4862
+ exports.queryUsers = queryUsers;
4863
+ exports.removeChannelMembers = removeChannelMembers;
4864
+ exports.removeChannelMembersRole = removeChannelMembersRole;
4865
+ exports.removeCommunityMembers = removeCommunityMembers;
4866
+ exports.removeCommunityMembersRole = removeCommunityMembersRole;
4867
+ exports.removeReaction = removeReaction;
4868
+ exports.runQuery = runQuery;
4869
+ exports.sliceByPaging = sliceByPaging;
4870
+ exports.sortByChannelSegment = sortByChannelSegment;
4871
+ exports.sortByDisplayName = sortByDisplayName;
4872
+ exports.sortByFirstCreated = sortByFirstCreated;
4873
+ exports.sortByLastActivity = sortByLastActivity;
4874
+ exports.sortByLastCreated = sortByLastCreated;
4875
+ exports.sortBySegmentNumber = sortBySegmentNumber;
4876
+ exports.syncInCache = syncInCache;
4877
+ exports.toPage = toPage;
4878
+ exports.toToken = toToken;
4879
+ exports.updateChannel = updateChannel;
4880
+ exports.updateComment = updateComment;
4881
+ exports.updateCommunity = updateCommunity;
4882
+ exports.updateMessage = updateMessage;
4883
+ exports.updatePost = updatePost;
4884
+ exports.updateUser = updateUser;