@amityco/ts-sdk 0.0.1-beta.8 → 0.0.1-beta.9

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 (244) hide show
  1. package/dist/@types/core/events.d.ts +63 -17
  2. package/dist/@types/core/events.d.ts.map +1 -1
  3. package/dist/@types/core/transport.d.ts +15 -0
  4. package/dist/@types/core/transport.d.ts.map +1 -1
  5. package/dist/@types/domains/client.d.ts +3 -0
  6. package/dist/@types/domains/client.d.ts.map +1 -1
  7. package/dist/@types/domains/comment.d.ts +1 -1
  8. package/dist/@types/domains/comment.d.ts.map +1 -1
  9. package/dist/@types/domains/community.d.ts +1 -1
  10. package/dist/@types/domains/community.d.ts.map +1 -1
  11. package/dist/@types/domains/group.d.ts +2 -2
  12. package/dist/@types/domains/group.d.ts.map +1 -1
  13. package/dist/@types/domains/partials.d.ts +3 -0
  14. package/dist/@types/domains/partials.d.ts.map +1 -1
  15. package/dist/@types/domains/post.d.ts +1 -1
  16. package/dist/@types/domains/post.d.ts.map +1 -1
  17. package/dist/@types/domains/user.d.ts +2 -1
  18. package/dist/@types/domains/user.d.ts.map +1 -1
  19. package/dist/client/api/connectClient.d.ts.map +1 -1
  20. package/dist/client/api/createClient.d.ts +2 -1
  21. package/dist/client/api/createClient.d.ts.map +1 -1
  22. package/dist/client/api/disconnectClient.d.ts.map +1 -1
  23. package/dist/client/api/getToken.d.ts +3 -1
  24. package/dist/client/api/getToken.d.ts.map +1 -1
  25. package/dist/comment/api/deleteComment.d.ts +1 -0
  26. package/dist/comment/api/deleteComment.d.ts.map +1 -1
  27. package/dist/comment/events/index.d.ts +4 -0
  28. package/dist/comment/events/index.d.ts.map +1 -1
  29. package/dist/comment/events/onCommentCreated.d.ts +1 -1
  30. package/dist/comment/events/onCommentCreated.d.ts.map +1 -1
  31. package/dist/comment/events/onCommentDeleted.d.ts +1 -1
  32. package/dist/comment/events/onCommentDeleted.d.ts.map +1 -1
  33. package/dist/comment/events/onCommentFlagged.d.ts +17 -0
  34. package/dist/comment/events/onCommentFlagged.d.ts.map +1 -0
  35. package/dist/comment/events/onCommentReactionAdded.d.ts +17 -0
  36. package/dist/comment/events/onCommentReactionAdded.d.ts.map +1 -0
  37. package/dist/comment/events/onCommentReactionRemoved.d.ts +17 -0
  38. package/dist/comment/events/onCommentReactionRemoved.d.ts.map +1 -0
  39. package/dist/comment/events/onCommentUnflagged.d.ts +17 -0
  40. package/dist/comment/events/onCommentUnflagged.d.ts.map +1 -0
  41. package/dist/comment/events/onCommentUpdated.d.ts +1 -1
  42. package/dist/comment/events/onCommentUpdated.d.ts.map +1 -1
  43. package/dist/comment/events/utils.d.ts +2 -0
  44. package/dist/comment/events/utils.d.ts.map +1 -0
  45. package/dist/comment/observers/observeComment.d.ts +1 -1
  46. package/dist/comment/observers/observeComment.d.ts.map +1 -1
  47. package/dist/comment/observers/observeComments.d.ts +5 -1
  48. package/dist/comment/observers/observeComments.d.ts.map +1 -1
  49. package/dist/community/events/index.d.ts +4 -0
  50. package/dist/community/events/index.d.ts.map +1 -1
  51. package/dist/community/events/onCommunityCreated.d.ts +2 -2
  52. package/dist/community/events/onCommunityCreated.d.ts.map +1 -1
  53. package/dist/community/events/onCommunityDeleted.d.ts +2 -2
  54. package/dist/community/events/onCommunityDeleted.d.ts.map +1 -1
  55. package/dist/community/events/onCommunityJoined.d.ts +3 -3
  56. package/dist/community/events/onCommunityJoined.d.ts.map +1 -1
  57. package/dist/community/events/onCommunityLeft.d.ts +3 -3
  58. package/dist/community/events/onCommunityLeft.d.ts.map +1 -1
  59. package/dist/community/events/onCommunityUpdated.d.ts +2 -2
  60. package/dist/community/events/onCommunityUpdated.d.ts.map +1 -1
  61. package/dist/community/events/onCommunityUserAdded.d.ts +17 -0
  62. package/dist/community/events/onCommunityUserAdded.d.ts.map +1 -0
  63. package/dist/community/events/onCommunityUserBanned.d.ts +17 -0
  64. package/dist/community/events/onCommunityUserBanned.d.ts.map +1 -0
  65. package/dist/community/events/onCommunityUserRemoved.d.ts +17 -0
  66. package/dist/community/events/onCommunityUserRemoved.d.ts.map +1 -0
  67. package/dist/community/events/onCommunityUserUnbanned.d.ts +17 -0
  68. package/dist/community/events/onCommunityUserUnbanned.d.ts.map +1 -0
  69. package/dist/community/events/utils.d.ts +3 -0
  70. package/dist/community/events/utils.d.ts.map +1 -0
  71. package/dist/community/observers/observeCommunity.d.ts +1 -1
  72. package/dist/community/observers/observeCommunity.d.ts.map +1 -1
  73. package/dist/core/cache/ingest.d.ts.map +1 -1
  74. package/dist/core/events.d.ts +4 -2
  75. package/dist/core/events.d.ts.map +1 -1
  76. package/dist/core/model/index.d.ts +1 -0
  77. package/dist/core/model/index.d.ts.map +1 -1
  78. package/dist/core/model/isMatch.d.ts +3 -0
  79. package/dist/core/model/isMatch.d.ts.map +1 -0
  80. package/dist/core/network.d.ts +11 -0
  81. package/dist/core/network.d.ts.map +1 -0
  82. package/dist/core/subscription.d.ts +14 -0
  83. package/dist/core/subscription.d.ts.map +1 -0
  84. package/dist/core/transports/http.d.ts +11 -0
  85. package/dist/core/transports/http.d.ts.map +1 -0
  86. package/dist/core/transports/index.d.ts +4 -0
  87. package/dist/core/transports/index.d.ts.map +1 -0
  88. package/dist/core/transports/mqtt.d.ts +17 -0
  89. package/dist/core/transports/mqtt.d.ts.map +1 -0
  90. package/dist/core/transports/utils.d.ts +13 -0
  91. package/dist/core/transports/utils.d.ts.map +1 -0
  92. package/dist/core/transports/ws.d.ts +27 -0
  93. package/dist/core/transports/ws.d.ts.map +1 -0
  94. package/dist/index.cjs.js +1208 -514
  95. package/dist/index.d.ts +1 -0
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.esm.js +1185 -515
  98. package/dist/index.umd.js +5 -3
  99. package/dist/post/api/deletePost.d.ts +1 -0
  100. package/dist/post/api/deletePost.d.ts.map +1 -1
  101. package/dist/post/events/index.d.ts +6 -0
  102. package/dist/post/events/index.d.ts.map +1 -1
  103. package/dist/post/events/onPostApproved.d.ts +17 -0
  104. package/dist/post/events/onPostApproved.d.ts.map +1 -0
  105. package/dist/post/events/onPostCreated.d.ts +1 -1
  106. package/dist/post/events/onPostCreated.d.ts.map +1 -1
  107. package/dist/post/events/onPostDeclined.d.ts +17 -0
  108. package/dist/post/events/onPostDeclined.d.ts.map +1 -0
  109. package/dist/post/events/onPostDeleted.d.ts +1 -1
  110. package/dist/post/events/onPostDeleted.d.ts.map +1 -1
  111. package/dist/post/events/onPostFlagged.d.ts +17 -0
  112. package/dist/post/events/onPostFlagged.d.ts.map +1 -0
  113. package/dist/post/events/onPostReactionAdded.d.ts +17 -0
  114. package/dist/post/events/onPostReactionAdded.d.ts.map +1 -0
  115. package/dist/post/events/onPostReactionRemoved.d.ts +17 -0
  116. package/dist/post/events/onPostReactionRemoved.d.ts.map +1 -0
  117. package/dist/post/events/onPostUnflagged.d.ts +17 -0
  118. package/dist/post/events/onPostUnflagged.d.ts.map +1 -0
  119. package/dist/post/events/onPostUpdated.d.ts +1 -1
  120. package/dist/post/events/onPostUpdated.d.ts.map +1 -1
  121. package/dist/post/events/utils.d.ts +2 -0
  122. package/dist/post/events/utils.d.ts.map +1 -0
  123. package/dist/post/observers/observePost.d.ts +1 -1
  124. package/dist/post/observers/observePost.d.ts.map +1 -1
  125. package/dist/post/observers/observePosts.d.ts +1 -1
  126. package/dist/post/observers/observePosts.d.ts.map +1 -1
  127. package/dist/reaction/events/onReactionAdded.d.ts +4 -2
  128. package/dist/reaction/events/onReactionAdded.d.ts.map +1 -1
  129. package/dist/reaction/events/onReactionRemoved.d.ts +4 -2
  130. package/dist/reaction/events/onReactionRemoved.d.ts.map +1 -1
  131. package/dist/reaction/utils/index.d.ts +1 -0
  132. package/dist/reaction/utils/index.d.ts.map +1 -1
  133. package/dist/reaction/utils/preparePayloadForCache.d.ts +3 -0
  134. package/dist/reaction/utils/preparePayloadForCache.d.ts.map +1 -0
  135. package/dist/report/api/createReport.d.ts.map +1 -1
  136. package/dist/report/api/deleteReport.d.ts.map +1 -1
  137. package/dist/user/events/index.d.ts +3 -0
  138. package/dist/user/events/index.d.ts.map +1 -1
  139. package/dist/user/events/onUserFlagCleared.d.ts +17 -0
  140. package/dist/user/events/onUserFlagCleared.d.ts.map +1 -0
  141. package/dist/user/events/onUserFlagged.d.ts +17 -0
  142. package/dist/user/events/onUserFlagged.d.ts.map +1 -0
  143. package/dist/user/events/onUserUnflagged.d.ts +17 -0
  144. package/dist/user/events/onUserUnflagged.d.ts.map +1 -0
  145. package/dist/user/events/onUserUpdated.d.ts +1 -1
  146. package/dist/user/events/onUserUpdated.d.ts.map +1 -1
  147. package/dist/user/events/utils.d.ts +2 -0
  148. package/dist/user/events/utils.d.ts.map +1 -0
  149. package/dist/user/observers/observeUser.d.ts +1 -1
  150. package/dist/user/observers/observeUser.d.ts.map +1 -1
  151. package/package.json +4 -1
  152. package/rollup.config.js +2 -2
  153. package/src/@types/core/events.ts +64 -23
  154. package/src/@types/core/transport.ts +14 -0
  155. package/src/@types/domains/client.ts +3 -0
  156. package/src/@types/domains/comment.ts +1 -0
  157. package/src/@types/domains/community.ts +1 -0
  158. package/src/@types/domains/group.ts +2 -2
  159. package/src/@types/domains/partials.ts +4 -0
  160. package/src/@types/domains/post.ts +1 -0
  161. package/src/@types/domains/user.ts +2 -0
  162. package/src/client/api/connectClient.ts +12 -2
  163. package/src/client/api/createClient.ts +7 -7
  164. package/src/client/api/disconnectClient.ts +5 -0
  165. package/src/client/api/getToken.ts +1 -1
  166. package/src/client/events/onConnectionError.ts +1 -1
  167. package/src/comment/api/createComment.ts +2 -2
  168. package/src/comment/api/deleteComment.ts +2 -2
  169. package/src/comment/api/updateComment.ts +1 -1
  170. package/src/comment/events/index.ts +6 -0
  171. package/src/comment/events/onCommentCreated.ts +4 -22
  172. package/src/comment/events/onCommentDeleted.ts +4 -22
  173. package/src/comment/events/onCommentFlagged.ts +21 -0
  174. package/src/comment/events/onCommentReactionAdded.ts +52 -0
  175. package/src/comment/events/onCommentReactionRemoved.ts +52 -0
  176. package/src/comment/events/onCommentUnflagged.ts +21 -0
  177. package/src/comment/events/onCommentUpdated.ts +4 -22
  178. package/src/comment/events/utils.ts +34 -0
  179. package/src/comment/observers/observeComment.ts +21 -7
  180. package/src/comment/observers/observeComments.ts +11 -3
  181. package/src/community/api/addCommunityMembers.ts +1 -1
  182. package/src/community/api/createCommunity.ts +1 -1
  183. package/src/community/api/deleteCommunity.ts +1 -1
  184. package/src/community/api/joinCommunity.ts +1 -1
  185. package/src/community/api/leaveCommunity.ts +1 -1
  186. package/src/community/api/removeCommunityMembers.ts +1 -1
  187. package/src/community/api/updateCommunity.ts +1 -1
  188. package/src/community/events/index.ts +5 -0
  189. package/src/community/events/onCommunityCreated.ts +5 -23
  190. package/src/community/events/onCommunityDeleted.ts +5 -23
  191. package/src/community/events/onCommunityJoined.ts +5 -23
  192. package/src/community/events/onCommunityLeft.ts +5 -23
  193. package/src/community/events/onCommunityUpdated.ts +5 -23
  194. package/src/community/events/onCommunityUserAdded.ts +19 -0
  195. package/src/community/events/onCommunityUserBanned.ts +19 -0
  196. package/src/community/events/onCommunityUserRemoved.ts +19 -0
  197. package/src/community/events/onCommunityUserUnbanned.ts +19 -0
  198. package/src/community/events/utils.ts +108 -0
  199. package/src/community/observers/observeCommunity.ts +23 -9
  200. package/src/core/cache/ingest.ts +19 -3
  201. package/src/core/events.ts +45 -4
  202. package/src/core/model/index.ts +1 -0
  203. package/src/core/model/isMatch.ts +12 -0
  204. package/src/core/network.ts +14 -0
  205. package/src/core/subscription.ts +75 -0
  206. package/src/core/transports/http.ts +63 -0
  207. package/src/core/transports/index.ts +3 -0
  208. package/src/core/transports/mqtt.ts +141 -0
  209. package/src/core/transports/utils.ts +25 -0
  210. package/src/core/transports/ws.ts +61 -0
  211. package/src/index.ts +1 -0
  212. package/src/post/api/createPost.ts +2 -2
  213. package/src/post/api/deletePost.ts +2 -2
  214. package/src/post/api/updatePost.ts +1 -1
  215. package/src/post/events/index.ts +9 -0
  216. package/src/post/events/onPostApproved.ts +19 -0
  217. package/src/post/events/onPostCreated.ts +4 -24
  218. package/src/post/events/onPostDeclined.ts +19 -0
  219. package/src/post/events/onPostDeleted.ts +4 -24
  220. package/src/post/events/onPostFlagged.ts +19 -0
  221. package/src/post/events/onPostReactionAdded.ts +50 -0
  222. package/src/post/events/onPostReactionRemoved.ts +50 -0
  223. package/src/post/events/onPostUnflagged.ts +19 -0
  224. package/src/post/events/onPostUpdated.ts +4 -24
  225. package/src/post/events/utils.ts +40 -0
  226. package/src/post/observers/observePost.ts +25 -7
  227. package/src/post/observers/observePosts.ts +12 -2
  228. package/src/reaction/events/onReactionAdded.ts +36 -15
  229. package/src/reaction/events/onReactionRemoved.ts +37 -14
  230. package/src/reaction/utils/dispatchReactable.ts +2 -2
  231. package/src/reaction/utils/index.ts +1 -0
  232. package/src/reaction/utils/preparePayloadForCache.ts +45 -0
  233. package/src/report/api/createReport.ts +5 -1
  234. package/src/report/api/deleteReport.ts +5 -1
  235. package/src/user/events/index.ts +4 -0
  236. package/src/user/events/onUserFlagCleared.ts +19 -0
  237. package/src/user/events/onUserFlagged.ts +19 -0
  238. package/src/user/events/onUserUnflagged.ts +19 -0
  239. package/src/user/events/onUserUpdated.ts +4 -24
  240. package/src/user/events/utils.ts +24 -0
  241. package/src/user/observers/observeUser.ts +11 -3
  242. package/dist/core/transports.d.ts +0 -49
  243. package/dist/core/transports.d.ts.map +0 -1
  244. package/src/core/transports.ts +0 -151
package/dist/index.cjs.js CHANGED
@@ -2,28 +2,32 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ var isMatchWith = require('lodash.ismatchwith');
5
6
  var jsBase64 = require('js-base64');
6
7
  var nativeIdGenerator = require('react-native-uuid');
7
8
  var debug = require('debug');
8
9
  var axios = require('axios');
9
10
  var HttpAgent = require('agentkeepalive');
10
11
  var io = require('socket.io-client');
12
+ var mqtt = require('mqtt');
11
13
  var mitt = require('mitt');
12
14
  var AsyncStorage = require('@react-native-async-storage/async-storage');
13
15
 
14
16
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
15
17
 
18
+ var isMatchWith__default = /*#__PURE__*/_interopDefaultLegacy(isMatchWith);
16
19
  var nativeIdGenerator__default = /*#__PURE__*/_interopDefaultLegacy(nativeIdGenerator);
17
20
  var debug__default = /*#__PURE__*/_interopDefaultLegacy(debug);
18
21
  var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
19
22
  var HttpAgent__default = /*#__PURE__*/_interopDefaultLegacy(HttpAgent);
20
23
  var io__default = /*#__PURE__*/_interopDefaultLegacy(io);
24
+ var mqtt__default = /*#__PURE__*/_interopDefaultLegacy(mqtt);
21
25
  var mitt__default = /*#__PURE__*/_interopDefaultLegacy(mitt);
22
26
  var AsyncStorage__default = /*#__PURE__*/_interopDefaultLegacy(AsyncStorage);
23
27
 
24
28
  var _a;
25
29
  // used in createClient
26
- const VERSION$1 = (_a = 'v0.0.1-beta.8-cjs') !== null && _a !== void 0 ? _a : '__dev__';
30
+ const VERSION$1 = (_a = 'v0.0.1-beta.9-cjs') !== null && _a !== void 0 ? _a : '__dev__';
27
31
 
28
32
  /**
29
33
  * Generic ASC error
@@ -290,24 +294,6 @@ const syncInCache = (original, replacement) => {
290
294
  pushToCache(name, replacement);
291
295
  };
292
296
 
293
- /**
294
- * Ingest a payload (v3) into the cache
295
- *
296
- * @param payload a "backend v3" payload object
297
- * @param order the order of the keys to process (in case of need)
298
- *
299
- * @category Cache
300
- */
301
- const ingestInCache = (payload = {}, order = Object.keys(payload)) => {
302
- order
303
- .forEach(key => {
304
- const name = storeInterests[key];
305
- if (!name)
306
- return;
307
- pushToCache(name, ...payload[key]);
308
- });
309
- };
310
-
311
297
  /**
312
298
  * Apply partial mutation to objects in the cache
313
299
  *
@@ -339,6 +325,58 @@ const mergeInCache = (name, mutation) => {
339
325
  mutateCache(name, key, model => (Object.assign(Object.assign({}, model), mutation)));
340
326
  };
341
327
 
328
+ /**
329
+ * converts an array looking collection to an object collection, grouped by localId
330
+ *
331
+ * @param array array of {@link Amity.Syncable}
332
+ * @returns array converted to object, grouped by localId
333
+ *
334
+ * @hidden
335
+ */
336
+ const toRecord = (array) => (array.reduce((acc, item) => (Object.assign(Object.assign({}, acc), { [item.localId]: item })), {}));
337
+
338
+ /** @hidden */
339
+ const isMatch = (model1, model2) => {
340
+ const customizer = (oldValue, newValue, key) => {
341
+ if (key === 'syncedAt') {
342
+ return true;
343
+ }
344
+ };
345
+ return isMatchWith__default['default'](model1, model2, customizer);
346
+ };
347
+
348
+ /**
349
+ * Ingest a payload (v3) into the cache
350
+ *
351
+ * @param payload a "backend v3" payload object
352
+ * @param order the order of the keys to process (in case of need)
353
+ *
354
+ * @category Cache
355
+ */
356
+ const ingestInCache = (payload = {}, order = Object.keys(payload)) => {
357
+ order
358
+ .forEach(key => {
359
+ const name = storeInterests[key];
360
+ if (!name)
361
+ return;
362
+ payload[key].forEach(model => {
363
+ var _a;
364
+ const [cached] = (_a = pullFromCache(name, getResolver(name)(model))) !== null && _a !== void 0 ? _a : [];
365
+ if (cached) {
366
+ // > instead of >= - some updates like reactions do not change updatedAt
367
+ if (cached.updatedAt && cached.updatedAt > model.updatedAt) {
368
+ return;
369
+ }
370
+ // personal fields like isJoined, myReactions are missed from real time event payload
371
+ mergeInCache(name, model);
372
+ }
373
+ else {
374
+ pushToCache(name, model);
375
+ }
376
+ });
377
+ });
378
+ };
379
+
342
380
  /**
343
381
  * Creates a cache instance. The cache instance will handle stores
344
382
  * given to it as input, and will be used as the first source of cached data
@@ -769,6 +807,45 @@ const createLogger = (session) => {
769
807
  return print;
770
808
  };
771
809
 
810
+ const API_ENDPOINT = {
811
+ EU: 'eu',
812
+ SG: 'sg',
813
+ US: 'us',
814
+ };
815
+ var UrlTemplate;
816
+ (function (UrlTemplate) {
817
+ UrlTemplate["HTTP"] = "https://api.{region}.amity.co";
818
+ UrlTemplate["MQTT"] = "wss://sse.{region}.amity.co:443/mqtt";
819
+ })(UrlTemplate || (UrlTemplate = {}));
820
+ const getUrlFromTemplate = (template, region) => {
821
+ return template.replace('{region}', region);
822
+ };
823
+
824
+ /**
825
+ * Unwraps v3 server payload (for error handling and type extraction)
826
+ *
827
+ * @param response A typical "v3" response (related to backend's service strategy)
828
+ *
829
+ * @returns The data returned by the backend
830
+ * @throws An error related to backend's rejection
831
+ *
832
+ * @category Transport
833
+ * @hidden
834
+ */
835
+ const unwrapPayload = (response) => {
836
+ if (response.status === 'success') {
837
+ return response.data;
838
+ }
839
+ else if (response.status === 'fail') {
840
+ throw new ASCUnknownError(response.code);
841
+ }
842
+ else if (response.status === 'error') {
843
+ throw new ASCApiError(response.message, response.code, "error" /* ERROR */);
844
+ }
845
+ // unjust, but helps force uncast "T | undefined" to allow deconstruction without warnings
846
+ return undefined;
847
+ };
848
+
772
849
  /**
773
850
  * Axios param serializer (for querystring)
774
851
  * @hidden
@@ -797,7 +874,7 @@ const stringify = (params, prefix) => {
797
874
  * @category Transport
798
875
  * @hidden
799
876
  */
800
- const createHttpTransport = (endpoint = 'https://api.amity.co') => {
877
+ const createHttpTransport = (endpoint) => {
801
878
  const options = {
802
879
  maxSockets: 100,
803
880
  maxFreeSockets: 10,
@@ -818,7 +895,8 @@ const createHttpTransport = (endpoint = 'https://api.amity.co') => {
818
895
  unwrapPayload(response.data);
819
896
  });
820
897
  return instance;
821
- };
898
+ };
899
+
822
900
  /**
823
901
  * Creates a pre-configured socket.io instance
824
902
  *
@@ -828,42 +906,19 @@ const createHttpTransport = (endpoint = 'https://api.amity.co') => {
828
906
  * @category Transport
829
907
  * @hidden
830
908
  */
831
- const createWebsocketTransport = (endpoint = 'https://api.ekomedia.technology') => {
909
+ const createWebsocketTransport = (endpoint) => {
832
910
  const socket = io__default['default'](endpoint, {
833
911
  autoConnect: false,
834
912
  reconnectionDelay: 2000,
835
913
  transports: ['websocket'],
836
914
  });
915
+ // FIXME: disconnectClient removes this listener and client can get global ban event
837
916
  socket.on('disconnect', (reason) => {
838
917
  if (reason === 'io server disconnect')
839
918
  socket.connect();
840
919
  });
841
920
  return socket;
842
921
  };
843
- /**
844
- * Unwraps v3 server payload (for error handling and type extraction)
845
- *
846
- * @param response A typical "v3" response (related to backend's service strategy)
847
- *
848
- * @returns The data returned by the backend
849
- * @throws An error related to backend's rejection
850
- *
851
- * @category Transport
852
- * @hidden
853
- */
854
- const unwrapPayload = (response) => {
855
- if (response.status === 'success') {
856
- return response.data;
857
- }
858
- else if (response.status === 'fail') {
859
- throw new ASCUnknownError(response.code);
860
- }
861
- else if (response.status === 'error') {
862
- throw new ASCApiError(response.message, response.code, "error" /* ERROR */);
863
- }
864
- // unjust, but helps force uncast "T | undefined" to allow deconstruction without warnings
865
- return undefined;
866
- };
867
922
  /**
868
923
  * Promisify a websocket event emission - resulting in a synchronous http-like XHR (ws legacy)
869
924
  *
@@ -893,14 +948,131 @@ const synchronousWSCall = async (client, event, data) => {
893
948
  return value;
894
949
  };
895
950
 
951
+ const QOS_FAILURE_CODE = 128;
952
+ const RETRY_BASE_TIMEOUT = 1000;
953
+ const RETRY_COUNT_MAX = 10;
954
+ var MqttError;
955
+ (function (MqttError) {
956
+ MqttError[MqttError["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED";
957
+ MqttError[MqttError["BAD_USERNAME_OR_PASSWORD"] = 4] = "BAD_USERNAME_OR_PASSWORD";
958
+ MqttError[MqttError["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED";
959
+ })(MqttError || (MqttError = {}));
960
+ function getMqttOptions(params) {
961
+ return Object.assign({ clean: false, clientId: `mqttjs_ + ${Math.random().toString(16).substr(2, 8)}`, protocolId: 'MQTT', protocolVersion: 4, reconnectPeriod: 0, will: {
962
+ topic: 'WillMsg',
963
+ payload: 'Connection Closed abnormally..!',
964
+ qos: 0,
965
+ retain: false
966
+ } }, params);
967
+ }
968
+ /**
969
+ * Creates a pre-configured socket.io instance
970
+ *
971
+ * @param endpoint The mqtt server's URL
972
+ * @returns A pre-configured (non-connected) mqtt client instance
973
+ *
974
+ * @category Transport
975
+ * @hidden
976
+ */
977
+ const createMqttTransport = (endpoint) => {
978
+ let mqttClient;
979
+ let retryCount = 0;
980
+ let allowReconnection = true;
981
+ async function connect(params) {
982
+ if (mqttClient) {
983
+ mqttClient.removeAllListeners();
984
+ mqttClient.end(true);
985
+ }
986
+ mqttClient = mqtt__default['default'].connect(endpoint, getMqttOptions({ username: params.userId, password: params.accessToken }));
987
+ mqttClient.on('connect', () => {
988
+ retryCount = 0;
989
+ allowReconnection = true;
990
+ });
991
+ mqttClient.on('error', (error) => {
992
+ switch (error.code) {
993
+ case 2 /* IDENTIFIER_REJECTED */:
994
+ case 4 /* BAD_USERNAME_OR_PASSWORD */:
995
+ case 5 /* NOT_AUTHORIZED */:
996
+ allowReconnection = false;
997
+ }
998
+ });
999
+ mqttClient.on('close', () => {
1000
+ if (allowReconnection) {
1001
+ reconnect();
1002
+ }
1003
+ });
1004
+ return new Promise(resolve => mqttClient.once('connect', () => resolve()));
1005
+ }
1006
+ const reconnect = () => {
1007
+ setTimeout(() => {
1008
+ retryCount = retryCount + 1;
1009
+ mqttClient.reconnect();
1010
+ }, RETRY_BASE_TIMEOUT * Math.pow(2, retryCount > RETRY_COUNT_MAX ? RETRY_COUNT_MAX : retryCount));
1011
+ };
1012
+ return {
1013
+ connect,
1014
+ async disconnect() {
1015
+ allowReconnection = false;
1016
+ if (this.connected) {
1017
+ return new Promise(resolve => mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.end(true, undefined, () => resolve()));
1018
+ }
1019
+ },
1020
+ get connected() {
1021
+ return !!(mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.connected);
1022
+ },
1023
+ on(event, handler) {
1024
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.on(event, handler);
1025
+ },
1026
+ once(event, handler) {
1027
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.once(event, handler);
1028
+ },
1029
+ off(event, handler) {
1030
+ if (handler !== undefined) {
1031
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.off(event, handler);
1032
+ }
1033
+ else {
1034
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.removeAllListeners(event);
1035
+ }
1036
+ },
1037
+ removeAllListeners() {
1038
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.removeAllListeners();
1039
+ },
1040
+ subscribe(topic, callback) {
1041
+ const callbackWrapper = (error, granted) => {
1042
+ if (error || granted[0].qos === QOS_FAILURE_CODE) {
1043
+ const ascError = error
1044
+ ? new ASCError(error.message, 800000 /* UNKNOWN_ERROR */, "error" /* ERROR */)
1045
+ // TODO throw the actual error, once BE can tell us the actual error code
1046
+ : new ASCUnknownError(800000 /* UNKNOWN_ERROR */, "error" /* ERROR */);
1047
+ console.error(`Failed to subscribe to topic ${topic}`, ascError);
1048
+ callback === null || callback === void 0 ? void 0 : callback(ascError);
1049
+ }
1050
+ else {
1051
+ console.log(`Subscribed to topic ${granted[0].topic}`);
1052
+ callback === null || callback === void 0 ? void 0 : callback();
1053
+ }
1054
+ };
1055
+ if (mqttClient) {
1056
+ mqttClient.subscribe(topic, { qos: 0 }, callbackWrapper);
1057
+ }
1058
+ else {
1059
+ callbackWrapper(new Error('No connection to broker'), []);
1060
+ }
1061
+ return () => mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.unsubscribe(topic);
1062
+ },
1063
+ unsubscribe(topic) {
1064
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.unsubscribe(topic);
1065
+ }
1066
+ };
1067
+ };
1068
+
896
1069
  // need to sync up the list
897
- const EVENTS$1 = [
1070
+ const WS_EVENTS = [
898
1071
  'disconnected',
899
1072
  'error',
900
1073
  'connect_error',
901
1074
  'reconnect_error',
902
1075
  'reconnect_failed',
903
- 'v3.user.didUpdate',
904
1076
  'v3.channel.didUpdate',
905
1077
  'v3.channel.didUpdate',
906
1078
  'v3.channel.didJoin',
@@ -913,6 +1085,15 @@ const EVENTS$1 = [
913
1085
  'v3.message.didUpdate',
914
1086
  'v3.message.didDelete',
915
1087
  ];
1088
+ const MQTT_EVENTS = [
1089
+ 'connect',
1090
+ 'message',
1091
+ 'disconnect',
1092
+ 'error',
1093
+ 'close',
1094
+ 'end',
1095
+ 'reconnect'
1096
+ ];
916
1097
  /** @hidden */
917
1098
  const createEventEmitter = () => {
918
1099
  return mitt__default['default']();
@@ -928,10 +1109,20 @@ const createEventEmitter = () => {
928
1109
  * @hidden
929
1110
  */
930
1111
  const proxyWebsocketEvents = (ws, emitter) => {
931
- EVENTS$1.forEach(event => {
1112
+ WS_EVENTS.forEach(event => {
932
1113
  ws.on(event, (param) => emitter.emit(event, param));
933
1114
  });
934
1115
  };
1116
+ const proxyMqttEvents = (mqttClient, emitter) => {
1117
+ MQTT_EVENTS.forEach(event => {
1118
+ mqttClient.on(event, (...params) => emitter.emit(event, params.length === 1 ? params[0] : params));
1119
+ });
1120
+ // @ts-ignore
1121
+ mqttClient.on('message', (topic, payload) => {
1122
+ const message = JSON.parse(payload.toString());
1123
+ emitter.emit(message.eventType, message.data);
1124
+ });
1125
+ };
935
1126
  /**
936
1127
  * Standardize the subscription of SSE through web sockets
937
1128
  *
@@ -983,14 +1174,15 @@ const fireEvent = (event, payload) => {
983
1174
  *
984
1175
  * @category Client API
985
1176
  **/
986
- const createClient = (apiKey, apiEndpoint = 'https://api.amity.co', debugSession = 'amity') => {
1177
+ const createClient = (apiKey, apiEndpoint = API_ENDPOINT.SG, debugSession = 'amity') => {
987
1178
  const log = createLogger(debugSession);
988
1179
  log('client/api/createClient', {
989
1180
  apiKey: apiKey.replace(/.{5}$/g, 'xxxxx'),
990
1181
  apiEndpoint,
991
1182
  });
992
- const http = createHttpTransport(apiEndpoint);
993
- const ws = createWebsocketTransport(apiEndpoint);
1183
+ const http = createHttpTransport(getUrlFromTemplate(UrlTemplate.HTTP, apiEndpoint));
1184
+ const ws = createWebsocketTransport(getUrlFromTemplate(UrlTemplate.HTTP, apiEndpoint));
1185
+ const mqtt = createMqttTransport(getUrlFromTemplate(UrlTemplate.MQTT, apiEndpoint));
994
1186
  const emitter = createEventEmitter();
995
1187
  const client = {
996
1188
  version: `${VERSION$1}`,
@@ -998,6 +1190,7 @@ const createClient = (apiKey, apiEndpoint = 'https://api.amity.co', debugSession
998
1190
  log,
999
1191
  http,
1000
1192
  ws,
1193
+ mqtt,
1001
1194
  emitter,
1002
1195
  use: () => setActiveClient(client),
1003
1196
  };
@@ -1010,6 +1203,38 @@ const createClient = (apiKey, apiEndpoint = 'https://api.amity.co', debugSession
1010
1203
  return client;
1011
1204
  };
1012
1205
 
1206
+ /**
1207
+ * ```js
1208
+ * import { disconnectClient } from '@amityco/ts-sdk'
1209
+ * const success = await disconnectClient()
1210
+ * ```
1211
+ *
1212
+ * Disconnects an {@link Amity.Client} instance from ASC servers
1213
+ *
1214
+ * @param client The {@link Amity.Client} instance to disconnect
1215
+ * @returns a success boolean if disconnected
1216
+ *
1217
+ * @category Client API
1218
+ * @async
1219
+ */
1220
+ const disconnectClient = async () => {
1221
+ const client = getActiveClient();
1222
+ client.log('client/api/disconnectClient');
1223
+ await new Promise(resolve => {
1224
+ client.ws.once('disconnect', resolve);
1225
+ client.ws.disconnect();
1226
+ client.mqtt.disconnect();
1227
+ });
1228
+ client.emitter.all.clear();
1229
+ // FIXME: it removes listener in ws.ts, it breaks global ban event
1230
+ client.ws.removeAllListeners();
1231
+ client.mqtt.removeAllListeners();
1232
+ client.userId = undefined;
1233
+ client.user = undefined;
1234
+ client.accessToken = undefined;
1235
+ return !client.ws.connected;
1236
+ };
1237
+
1013
1238
  // TODO: find a way to uniquely identify the device
1014
1239
  // import { getStorage } from './storage'
1015
1240
  /** @hidden */
@@ -1066,6 +1291,83 @@ const getToken = async (params) => {
1066
1291
  return data;
1067
1292
  };
1068
1293
 
1294
+ const EVENTS = [
1295
+ 'disconnected',
1296
+ 'error',
1297
+ 'connect_error',
1298
+ 'reconnect_error',
1299
+ 'reconnect_failed',
1300
+ ];
1301
+ /**
1302
+ * ```js
1303
+ * import { onConnectionError } from '@amityco/ts-sdk'
1304
+ * const dispose = onClientBanned(() => {
1305
+ * // ...
1306
+ * })
1307
+ * ```
1308
+ *
1309
+ * Fired when any {@link Amity.Client} have been banned from the platform
1310
+ *
1311
+ * @param callback The function to call when the event was fired
1312
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1313
+ *
1314
+ * @category Client Events
1315
+ */
1316
+ const onConnectionError = (callback) => {
1317
+ const client = getActiveClient();
1318
+ const subscribers = EVENTS.map(event => (createEventSubscriber(client, `client/onConnectionError(${event})`, event, (response) => {
1319
+ const error = (response && 'code' in response)
1320
+ ? new ASCError(response.message, response.code, "fatal" /* FATAL */)
1321
+ : new ASCConnectionError(event);
1322
+ callback(error);
1323
+ })));
1324
+ return () => {
1325
+ subscribers.forEach(fn => fn());
1326
+ };
1327
+ };
1328
+
1329
+ /**
1330
+ * ```js
1331
+ * import { onClientDisconnected } from '@amityco/ts-sdk'
1332
+ * const dispose = onClientDisconnected(() => {
1333
+ * // ...
1334
+ * })
1335
+ * ```
1336
+ *
1337
+ * Fired when any {@link Amity.Client} have been disconnected
1338
+ *
1339
+ * @param callback The function to call when the event was fired
1340
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1341
+ *
1342
+ * @category Client Events
1343
+ */
1344
+ const onClientDisconnected = (callback) => {
1345
+ return onConnectionError(({ code }) => {
1346
+ code === 800211 /* DISCONNECTED */ && callback();
1347
+ });
1348
+ };
1349
+
1350
+ /**
1351
+ * ```js
1352
+ * import { onClientBanned } from '@amityco/ts-sdk'
1353
+ * const dispose = onClientBanned(() => {
1354
+ * // ...
1355
+ * })
1356
+ * ```
1357
+ *
1358
+ * Fired when any {@link Amity.Client} have been banned from the platform
1359
+ *
1360
+ * @param callback The function to call when the event was fired
1361
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1362
+ *
1363
+ * @category Client Events
1364
+ */
1365
+ const onClientBanned = (callback) => {
1366
+ return onConnectionError(({ code }) => {
1367
+ code === 400312 /* GLOBAL_BAN */ && callback();
1368
+ });
1369
+ };
1370
+
1069
1371
  /**
1070
1372
  * ```js
1071
1373
  * import { connectClient } from '@amityco/ts-sdk/client/api'
@@ -1094,11 +1396,12 @@ const connectClient = async (params) => {
1094
1396
  (_b = params.deviceId) !== null && _b !== void 0 ? _b : (params.deviceId = getDeviceId());
1095
1397
  // @ts-ignore: in that particular case, typing can be
1096
1398
  // ignored since we enforce default values just before.
1097
- const { accessToken } = await getToken(params);
1399
+ const { accessToken, users } = await getToken(params);
1098
1400
  // manually setup the token for http transport
1099
1401
  client.http.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
1100
1402
  // manually setup the token for ws transport
1101
1403
  client.ws.io.opts.query = { token: accessToken };
1404
+ // FIXME: events are duplicated if connectClient is called few times without disconnectClient
1102
1405
  // wire websocket events to our event emitter
1103
1406
  proxyWebsocketEvents(client.ws, client.emitter);
1104
1407
  // TODO: in phase 2, this should not be necessary. we should have WS
@@ -1107,41 +1410,20 @@ const connectClient = async (params) => {
1107
1410
  client.ws.once('connect', resolve);
1108
1411
  client.ws.open();
1109
1412
  });
1413
+ const unsubscribe = onClientBanned(() => {
1414
+ disconnectClient();
1415
+ unsubscribe();
1416
+ });
1110
1417
  client.userId = params.userId;
1418
+ client.user = users[0];
1419
+ client.accessToken = accessToken;
1111
1420
  return client.ws.connected;
1112
1421
  };
1113
1422
 
1114
1423
  /**
1115
1424
  * ```js
1116
- * import { disconnectClient } from '@amityco/ts-sdk'
1117
- * const success = await disconnectClient()
1118
- * ```
1119
- *
1120
- * Disconnects an {@link Amity.Client} instance from ASC servers
1121
- *
1122
- * @param client The {@link Amity.Client} instance to disconnect
1123
- * @returns a success boolean if disconnected
1124
- *
1125
- * @category Client API
1126
- * @async
1127
- */
1128
- const disconnectClient = async () => {
1129
- const client = getActiveClient();
1130
- client.log('client/api/disconnectClient');
1131
- await new Promise(resolve => {
1132
- client.ws.once('disconnect', resolve);
1133
- client.ws.disconnect();
1134
- });
1135
- client.emitter.all.clear();
1136
- client.ws.removeAllListeners();
1137
- client.userId = undefined;
1138
- return !client.ws.connected;
1139
- };
1140
-
1141
- /**
1142
- * ```js
1143
- * import { isConnected } from '@amityco/ts-sdk'
1144
- * const connected = isConnected()
1425
+ * import { isConnected } from '@amityco/ts-sdk'
1426
+ * const connected = isConnected()
1145
1427
  * ```
1146
1428
  *
1147
1429
  * Checks if a {@link Amity.Client} instance is connected to ASC servers
@@ -1294,16 +1576,6 @@ const clearCache = (stores = ['user', 'file', 'channel', 'message', 'community',
1294
1576
  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(); });
1295
1577
  };
1296
1578
 
1297
- /**
1298
- * converts an array looking collection to an object collection, grouped by localId
1299
- *
1300
- * @param array array of {@link Amity.Syncable}
1301
- * @returns array converted to object, grouped by localId
1302
- *
1303
- * @hidden
1304
- */
1305
- const toRecord = (array) => (array.reduce((acc, item) => (Object.assign(Object.assign({}, acc), { [item.localId]: item })), {}));
1306
-
1307
1579
  /**
1308
1580
  * Set the model's syncedAt property and localId
1309
1581
  *
@@ -1389,82 +1661,51 @@ const sortByLastCreated = ({ createdAt: a }, { createdAt: b }) => new Date(b).va
1389
1661
  */
1390
1662
  const sortByLastActivity = ({ lastActivity: a }, { lastActivity: b }) => new Date(b).valueOf() - new Date(a).valueOf();
1391
1663
 
1392
- const EVENTS = [
1393
- 'disconnected',
1394
- 'error',
1395
- 'connect_error',
1396
- 'reconnect_error',
1397
- 'reconnect_failed',
1398
- ];
1399
- /**
1400
- * ```js
1401
- * import { onConnectionError } from '@amityco/ts-sdk'
1402
- * const dispose = onClientBanned(() => {
1403
- * // ...
1404
- * })
1405
- * ```
1406
- *
1407
- * Fired when any {@link Amity.Client} have been banned from the platform
1408
- *
1409
- * @param callback The function to call when the event was fired
1410
- * @returns an {@link Amity.Unsubscriber} function to stop listening
1411
- *
1412
- * @category Client Events
1413
- */
1414
- const onConnectionError = (callback) => {
1415
- const client = getActiveClient();
1416
- const subscribers = EVENTS.map(event => (createEventSubscriber(client, `client/onConnectionError(${event})`, event, (response) => {
1417
- const error = (response && 'code' in response)
1418
- ? new ASCError(response.message, response.code, "fatal" /* FATAL */)
1419
- : new ASCConnectionError(event);
1420
- callback(error);
1421
- })));
1422
- return () => {
1423
- subscribers.forEach(fn => fn());
1424
- };
1425
- };
1426
-
1427
- /**
1428
- * ```js
1429
- * import { onClientDisconnected } from '@amityco/ts-sdk'
1430
- * const dispose = onClientDisconnected(() => {
1431
- * // ...
1432
- * })
1433
- * ```
1434
- *
1435
- * Fired when any {@link Amity.Client} have been disconnected
1436
- *
1437
- * @param callback The function to call when the event was fired
1438
- * @returns an {@link Amity.Unsubscriber} function to stop listening
1439
- *
1440
- * @category Client Events
1441
- */
1442
- const onClientDisconnected = (callback) => {
1443
- return onConnectionError(({ code }) => {
1444
- code === 800211 /* DISCONNECTED */ && callback();
1445
- });
1446
- };
1447
-
1448
- /**
1449
- * ```js
1450
- * import { onClientBanned } from '@amityco/ts-sdk'
1451
- * const dispose = onClientBanned(() => {
1452
- * // ...
1453
- * })
1454
- * ```
1455
- *
1456
- * Fired when any {@link Amity.Client} have been banned from the platform
1457
- *
1458
- * @param callback The function to call when the event was fired
1459
- * @returns an {@link Amity.Unsubscriber} function to stop listening
1460
- *
1461
- * @category Client Events
1462
- */
1463
- const onClientBanned = (callback) => {
1464
- return onConnectionError(({ code }) => {
1465
- code === 400312 /* GLOBAL_BAN */ && callback();
1466
- });
1467
- };
1664
+ exports.SubscriptionLevels = void 0;
1665
+ (function (SubscriptionLevels) {
1666
+ SubscriptionLevels["COMMUNITY"] = "community";
1667
+ SubscriptionLevels["POST"] = "post";
1668
+ SubscriptionLevels["COMMENT"] = "comment";
1669
+ SubscriptionLevels["POST_AND_COMMENT"] = "post_and_comment";
1670
+ SubscriptionLevels["USER"] = "user";
1671
+ })(exports.SubscriptionLevels || (exports.SubscriptionLevels = {}));
1672
+ const getCommunityUserTopic = ({ path }, level) => {
1673
+ switch (level) {
1674
+ case 'post':
1675
+ return `${path}/post/+`;
1676
+ case 'comment':
1677
+ return `${path}/post/+/comment/+`;
1678
+ case 'post_and_comment':
1679
+ return `${path}/post/#`;
1680
+ default:
1681
+ return path;
1682
+ }
1683
+ };
1684
+ const getCommunityTopic = ({ path }, level = exports.SubscriptionLevels.COMMUNITY) => getCommunityUserTopic({ path }, level);
1685
+ const getUserTopic = ({ path }, level = exports.SubscriptionLevels.USER) => getCommunityUserTopic({ path }, level);
1686
+ const getPostTopic = ({ path }, level = exports.SubscriptionLevels.POST) => {
1687
+ switch (level) {
1688
+ case 'comment':
1689
+ return `${path}/comment/+`;
1690
+ default:
1691
+ return path;
1692
+ }
1693
+ };
1694
+ const getCommentTopic = ({ path }) => {
1695
+ return path;
1696
+ };
1697
+ let mqttAccessToken;
1698
+ let mqttUserId;
1699
+ function subscribeTopic(topic, callback) {
1700
+ const { mqtt, emitter, accessToken, user } = getActiveClient();
1701
+ if (mqttAccessToken !== accessToken || mqttUserId !== user._id) {
1702
+ mqttAccessToken = accessToken;
1703
+ mqttUserId = user._id;
1704
+ mqtt.connect({ accessToken: accessToken, userId: user._id });
1705
+ proxyMqttEvents(mqtt, emitter);
1706
+ }
1707
+ return mqtt.subscribe(topic, callback);
1708
+ }
1468
1709
 
1469
1710
  /**
1470
1711
  * ```js
@@ -1666,6 +1907,16 @@ const updateUser = async (userId, patch) => {
1666
1907
  return data.users.find(user => user.userId === userId);
1667
1908
  };
1668
1909
 
1910
+ const createUserEventSubscriber = (event, callback) => {
1911
+ const client = getActiveClient();
1912
+ const filter = (payload) => {
1913
+ decoratePayload(payload);
1914
+ ingestInCache(payload);
1915
+ callback(payload.users[0]);
1916
+ };
1917
+ return createEventSubscriber(client, event, event, filter);
1918
+ };
1919
+
1669
1920
  /**
1670
1921
  * ```js
1671
1922
  * import { onUserUpdated } from '@amityco/ts-sdk'
@@ -1674,22 +1925,65 @@ const updateUser = async (userId, patch) => {
1674
1925
  * })
1675
1926
  * ```
1676
1927
  *
1677
- * Fired when any {@link Amity.User} have been updated
1928
+ * Fired when a {@link Amity.User} has been updated
1678
1929
  *
1679
1930
  * @param callback The function to call when the event was fired
1680
1931
  * @returns an {@link Amity.Unsubscriber} function to stop listening
1681
1932
  *
1682
1933
  * @category User Events
1683
1934
  */
1684
- const onUserUpdated = (callback) => {
1685
- const client = getActiveClient();
1686
- const filter = (payload) => {
1687
- decoratePayload(payload);
1688
- ingestInCache(payload);
1689
- callback(payload.users[0]);
1690
- };
1691
- return createEventSubscriber(client, 'user/onUserUpdate', 'v3.user.didUpdate', filter);
1692
- };
1935
+ const onUserUpdated = (callback) => createUserEventSubscriber('user.updated', callback);
1936
+
1937
+ /**
1938
+ * ```js
1939
+ * import { onUserFlagged } from '@amityco/ts-sdk'
1940
+ * const dispose = onUserFlagged(user => {
1941
+ * // ...
1942
+ * })
1943
+ * ```
1944
+ *
1945
+ * Fired when a {@link Amity.User} has been flagged
1946
+ *
1947
+ * @param callback The function to call when the event was fired
1948
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1949
+ *
1950
+ * @category User Events
1951
+ */
1952
+ const onUserFlagged = (callback) => createUserEventSubscriber('user.flagged', callback);
1953
+
1954
+ /**
1955
+ * ```js
1956
+ * import { onUserUnflagged } from '@amityco/ts-sdk'
1957
+ * const dispose = onUserUnflagged(user => {
1958
+ * // ...
1959
+ * })
1960
+ * ```
1961
+ *
1962
+ * Fired when a flag has been removed from a {@link Amity.User}
1963
+ *
1964
+ * @param callback The function to call when the event was fired
1965
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1966
+ *
1967
+ * @category User Events
1968
+ */
1969
+ const onUserUnflagged = (callback) => createUserEventSubscriber('user.unflagged', callback);
1970
+
1971
+ /**
1972
+ * ```js
1973
+ * import { onUserFlagCleared } from '@amityco/ts-sdk'
1974
+ * const dispose = onUserFlagCleared(user => {
1975
+ * // ...
1976
+ * })
1977
+ * ```
1978
+ *
1979
+ * Fired when flags have been cleared for a {@link Amity.User}
1980
+ *
1981
+ * @param callback The function to call when the event was fired
1982
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
1983
+ *
1984
+ * @category User Events
1985
+ */
1986
+ const onUserFlagCleared = (callback) => createUserEventSubscriber('user.flagCleared', callback);
1693
1987
 
1694
1988
  /**
1695
1989
  * ```js
@@ -1723,7 +2017,7 @@ const observeUser = (userId, callback) => {
1723
2017
  (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
1724
2018
  };
1725
2019
  const disposers = [];
1726
- disposers.push(onUserUpdated(data => router({ data }, 'onUpdate')));
2020
+ disposers.push(onUserUpdated(data => router({ data }, 'onUpdate')), onUserFlagged(data => router({ data }, 'onFlagged')), onUserUnflagged(data => router({ data }, 'onUnflagged')), onUserFlagCleared(data => router({ data }, 'onFlagCleared')));
1727
2021
  runQuery(createQuery(getUser, userId), (result) => result.data && router(result, 'onFetch'));
1728
2022
  return () => {
1729
2023
  log(`observeUser(tmpid: ${timestamp}) > dispose`);
@@ -1987,10 +2281,10 @@ const dispatchReactable = (referenceType, model) => {
1987
2281
  fireEvent('v3.message.didUpdate', { messages: [model] });
1988
2282
  else if (referenceType === 'post')
1989
2283
  // @ts-ignore: refactor later
1990
- fireEvent('v3.post.didUpdate', { posts: [model] });
2284
+ fireEvent('post.updated', { posts: [model] });
1991
2285
  else if (referenceType === 'comment')
1992
2286
  // @ts-ignore: refactor later
1993
- fireEvent('v3.comment.didUpdate', { comments: [model] });
2287
+ fireEvent('comment.updated', { comments: [model] });
1994
2288
  };
1995
2289
 
1996
2290
  /**
@@ -2523,8 +2817,8 @@ const createPost = async (bundle) => {
2523
2817
  const { data } = await client.http.post('/api/v3/posts', bundle);
2524
2818
  decoratePayload(data);
2525
2819
  ingestInCache(data);
2526
- fireEvent('v3.community.didUpdate', { communities: data.communities });
2527
- fireEvent('v3.post.didCreate', data);
2820
+ fireEvent('community.updated', { communities: data.communities });
2821
+ fireEvent('post.created', data);
2528
2822
  const { posts } = data;
2529
2823
  return posts[0];
2530
2824
  };
@@ -2552,7 +2846,7 @@ const updatePost = async (postId, patch) => {
2552
2846
  const { data } = await client.http.put(`/api/v3/posts/${postId}`, patch);
2553
2847
  decoratePayload(data);
2554
2848
  ingestInCache(data);
2555
- fireEvent('v3.post.didUpdate', data);
2849
+ fireEvent('post.updated', data);
2556
2850
  const { posts } = data;
2557
2851
  return posts.find(post => post.postId === postId);
2558
2852
  };
@@ -2722,7 +3016,7 @@ const createCommunity = async (bundle) => {
2722
3016
  const { data } = await client.http.post('/api/v3/communities/', bundle);
2723
3017
  decoratePayload(data);
2724
3018
  ingestInCache(data);
2725
- fireEvent('v3.community.didCreate', data);
3019
+ fireEvent('community.created', data);
2726
3020
  const { communities } = data;
2727
3021
  return communities[0];
2728
3022
  };
@@ -2748,7 +3042,7 @@ const updateCommunity = async (communityId, patch) => {
2748
3042
  const { data } = await client.http.put(`/api/v3/communities/${communityId}`, patch);
2749
3043
  decoratePayload(data);
2750
3044
  ingestInCache(data);
2751
- fireEvent('v3.community.didUpdate', data);
3045
+ fireEvent('community.updated', data);
2752
3046
  const { communities } = data;
2753
3047
  return communities.find(community => community.communityId === communityId);
2754
3048
  };
@@ -2773,7 +3067,7 @@ const deleteCommunity = async (communityId) => {
2773
3067
  // API-FIX: This endpoint has not been implemented yet.
2774
3068
  await client.http.delete(`/api/v3/communities/${communityId}`);
2775
3069
  const deleted = await getCommunity(communityId);
2776
- fireEvent('v3.community.didDelete', { communities: [deleted] });
3070
+ fireEvent('community.deleted', { communities: [deleted] });
2777
3071
  return deleted;
2778
3072
  };
2779
3073
 
@@ -2797,7 +3091,7 @@ const joinCommunity = async (communityId) => {
2797
3091
  const { data } = await client.http.post(`/api/v3/communities/${communityId}/join`);
2798
3092
  decoratePayload(data);
2799
3093
  ingestInCache(data);
2800
- fireEvent('v3.community.didJoin', {
3094
+ fireEvent('community.joined', {
2801
3095
  communities: data.communities
2802
3096
  });
2803
3097
  const { communityUsers } = data;
@@ -2825,7 +3119,7 @@ const leaveCommunity = async (communityId) => {
2825
3119
  const { data } = await client.http.delete(`/api/v3/communities/${communityId}/leave`);
2826
3120
  decoratePayload(data);
2827
3121
  ingestInCache(data);
2828
- fireEvent('v3.community.didJoin', {
3122
+ fireEvent('community.left', {
2829
3123
  communities: data.communities,
2830
3124
  });
2831
3125
  const { communityUsers } = data;
@@ -2904,7 +3198,7 @@ const addCommunityMembers = async (communityId, userIds) => {
2904
3198
  const { data } = await client.http.post(`/api/v3/communities/${communityId}/users`, { communityId, userIds });
2905
3199
  decoratePayload(data);
2906
3200
  ingestInCache(data);
2907
- fireEvent('v3.community.didAddUsers', {
3201
+ fireEvent('community.userAdded', {
2908
3202
  communities: data.communities,
2909
3203
  });
2910
3204
  const { communityUsers } = data;
@@ -2933,7 +3227,7 @@ const removeCommunityMembers = async (communityId, userIds) => {
2933
3227
  const { data } = await client.http.delete(`/api/v3/communities/${communityId}/users`, { data: { communityId, userIds } });
2934
3228
  decoratePayload(data);
2935
3229
  ingestInCache(data);
2936
- fireEvent('v3.community.didRemoveUsers', {
3230
+ fireEvent('community.userRemoved', {
2937
3231
  communities: data.communities,
2938
3232
  });
2939
3233
  const { communityUsers } = data;
@@ -3024,11 +3318,11 @@ const deletePost = async (postId, permanent = false) => {
3024
3318
  // later when realtime events covers that for us.
3025
3319
  if (post.targetType === 'community') {
3026
3320
  const community = await getCommunity(post.targetId);
3027
- fireEvent('v3.community.didUpdate', { communities: [community] });
3321
+ fireEvent('community.updated', { communities: [community] });
3028
3322
  }
3029
3323
  // to support hard deletion
3030
3324
  const deleted = Object.assign(Object.assign({}, post), { isDeleted: true });
3031
- fireEvent('v3.post.didDelete', { posts: [deleted] });
3325
+ fireEvent('post.deleted', { posts: [deleted] });
3032
3326
  if (permanent) {
3033
3327
  setTimeout(() => {
3034
3328
  dropFromCache('post', { postId });
@@ -3276,8 +3570,8 @@ const createComment = async (bundle) => {
3276
3570
  decoratePayload(data);
3277
3571
  ingestInCache(data);
3278
3572
  const post = await getPost(bundle.referenceId);
3279
- fireEvent('v3.post.didUpdate', { posts: [post] });
3280
- fireEvent('v3.comment.didCreate', data);
3573
+ fireEvent('post.updated', { posts: [post] });
3574
+ fireEvent('comment.created', data);
3281
3575
  const { comments } = data;
3282
3576
  return comments[0];
3283
3577
  };
@@ -3305,7 +3599,7 @@ const updateComment = async (commentId, patch) => {
3305
3599
  const { data } = await client.http.put(`/api/v3/comments/${commentId}`, patch);
3306
3600
  decoratePayload(data);
3307
3601
  ingestInCache(data);
3308
- fireEvent('v3.comment.didUpdate', data);
3602
+ fireEvent('comment.updated', data);
3309
3603
  const { comments } = data;
3310
3604
  return comments.find(comment => comment.commentId === commentId);
3311
3605
  };
@@ -3338,8 +3632,8 @@ const deleteComment = async (commentId, permanent = false) => {
3338
3632
  // to support hard deletion
3339
3633
  const deleted = Object.assign(Object.assign({}, comment), { isDeleted: true });
3340
3634
  const post = await getPost(comment.referenceId);
3341
- fireEvent('v3.post.didUpdate', { posts: [post] });
3342
- fireEvent('v3.comment.didDelete', { comments: [deleted] });
3635
+ fireEvent('post.updated', { posts: [post] });
3636
+ fireEvent('comment.deleted', { comments: [deleted] });
3343
3637
  if (permanent) {
3344
3638
  setTimeout(() => {
3345
3639
  dropFromCache('comment', { commentId });
@@ -3362,6 +3656,42 @@ const fetchReference = async (referenceType, referenceId) => {
3362
3656
  throw new Error(`Incorrect referenceType: ${referenceType}`);
3363
3657
  };
3364
3658
 
3659
+ /** @hidden */
3660
+ const preparePayloadForCache = (event, payload) => {
3661
+ var _a, _b;
3662
+ const client = getActiveClient();
3663
+ if (client.userId !== payload.reactor.userId) {
3664
+ return;
3665
+ }
3666
+ let model;
3667
+ let cached;
3668
+ if (event === 'post.addReaction' || event === 'post.removeReaction') {
3669
+ const post = payload.posts[0];
3670
+ cached = ((_a = pullFromCache('post', post.postId)) !== null && _a !== void 0 ? _a : [])[0];
3671
+ model = post;
3672
+ }
3673
+ else {
3674
+ const comment = payload.comments[0];
3675
+ cached = ((_b = pullFromCache('comment', comment.commentId)) !== null && _b !== void 0 ? _b : [])[0];
3676
+ model = comment;
3677
+ }
3678
+ if (!cached || !cached.myReactions) {
3679
+ return;
3680
+ }
3681
+ if (event === 'post.addReaction' || event === 'comment.addReaction') {
3682
+ if (cached.myReactions.includes(payload.reactor.reactionName)) {
3683
+ return;
3684
+ }
3685
+ Object.assign(model, { myReactions: [...cached.myReactions, payload.reactor.reactionName] });
3686
+ }
3687
+ else {
3688
+ if (!cached.myReactions.includes(payload.reactor.reactionName)) {
3689
+ return;
3690
+ }
3691
+ Object.assign(model, { myReactions: cached.myReactions.filter(x => x !== payload.reactor.reactionName) });
3692
+ }
3693
+ };
3694
+
3365
3695
  /**
3366
3696
  * ```js
3367
3697
  * import { addReaction } from '@amityco/ts-sdk'
@@ -3474,75 +3804,468 @@ removeReaction.optimistically = (referenceType, referenceId, reactionName) => {
3474
3804
  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;
3475
3805
  };
3476
3806
 
3807
+ const createPostEventSubscriber = (event, callback) => {
3808
+ const client = getActiveClient();
3809
+ const filter = (payload) => {
3810
+ var _a, _b;
3811
+ const [cached] = (_a = pullFromCache('post', payload.posts[0].postId)) !== null && _a !== void 0 ? _a : [];
3812
+ const { communities } = payload, others = __rest(payload, ["communities"]);
3813
+ decoratePayload(others);
3814
+ ingestInCache(others);
3815
+ if (communities === null || communities === void 0 ? void 0 : communities[0]) {
3816
+ fireEvent('community.updated', { communities });
3817
+ }
3818
+ const [post] = (_b = pullFromCache('post', others.posts[0].postId)) !== null && _b !== void 0 ? _b : [];
3819
+ if (cached && isMatch(cached, post)) {
3820
+ return;
3821
+ }
3822
+ callback(post);
3823
+ };
3824
+ return createEventSubscriber(client, event, event, filter);
3825
+ };
3826
+
3477
3827
  /**
3478
3828
  * ```js
3479
- * import { onReactionRemoved } from '@amityco/ts-sdk'
3480
- * const dispose = onReactionRemoved(message => {
3829
+ * import { onPostCreated } from '@amityco/ts-sdk'
3830
+ * const dispose = onPostCreated(post => {
3481
3831
  * // ...
3482
3832
  * })
3483
3833
  * ```
3484
3834
  *
3485
- * Fired when an {@link Amity.Reaction} has been removed
3835
+ * Fired when {@link Amity.Post} has been created
3486
3836
  *
3487
3837
  * @param callback The function to call when the event was fired
3488
3838
  * @returns an {@link Amity.Unsubscriber} function to stop listening
3489
3839
  *
3490
- * @category Message Events
3491
- **/
3492
- const onReactionRemoved = (referenceType, referenceId, callback) => {
3493
- const client = getActiveClient();
3494
- const filter = (payload) => {
3495
- // TODO: lol
3496
- decoratePayload(payload);
3497
- ingestInCache(payload);
3498
- };
3499
- return createEventSubscriber(client, 'reaction/onReactionRemoved', 'v3.message.didUpdate', filter);
3500
- };
3501
-
3502
- var REFERENCE_TYPES = {
3503
- post: {
3504
- domainName: 'posts',
3505
- eventName: 'v3/post.isflagbyme',
3506
- primaryKey: 'postId',
3507
- },
3508
- comment: {
3509
- domainName: 'comments',
3510
- eventName: 'v3/comment.isflagbyme',
3511
- primaryKey: 'commentId',
3512
- },
3513
- message: {
3514
- domainName: 'messages',
3515
- eventName: 'v3/message.isFlaggedByMe',
3516
- primaryKey: 'messageId',
3517
- },
3518
- user: {
3519
- domainName: 'users',
3520
- eventName: 'user.isFlagByMe',
3521
- primaryKey: 'userId',
3522
- },
3523
- };
3840
+ * @category Post Events
3841
+ */
3842
+ const onPostCreated = (callback) => createPostEventSubscriber('post.created', callback);
3524
3843
 
3525
3844
  /**
3526
3845
  * ```js
3527
- * import { createReport } from '@amityco/ts-sdk'
3528
- * const flagged = await createReport('post', postId)
3846
+ * import { onPostUpdated } from '@amityco/ts-sdk'
3847
+ * const dispose = onPostUpdated(post => {
3848
+ * // ...
3849
+ * })
3529
3850
  * ```
3530
3851
  *
3531
- * @param referenceType The type of thing to add a report to, such as a post or a comment.
3532
- * @param referenceId The ID of the thing to add a new report to.
3533
- * @returns the created report result
3852
+ * Fired when a {@link Amity.Post} has been updated
3534
3853
  *
3535
- * @category Report API
3536
- * @async
3537
- **/
3538
- const createReport = async (referenceType, referenceId) => {
3539
- const client = getActiveClient();
3540
- client.log('report/createReport', { referenceType, referenceId });
3541
- const { domainName } = REFERENCE_TYPES[referenceType];
3854
+ * @param callback The function to call when the event was fired
3855
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3856
+ *
3857
+ * @category Post Events
3858
+ */
3859
+ const onPostUpdated = (callback) => createPostEventSubscriber('post.updated', callback);
3860
+
3861
+ /**
3862
+ * ```js
3863
+ * import { onPostDeleted } from '@amityco/ts-sdk'
3864
+ * const dispose = onPostDeleted(post => {
3865
+ * // ...
3866
+ * })
3867
+ * ```
3868
+ *
3869
+ * Fired when a {@link Amity.Post} has been deleted
3870
+ *
3871
+ * @param callback The function to call when the event was fired
3872
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3873
+ *
3874
+ * @category Post Events
3875
+ */
3876
+ const onPostDeleted = (callback) => createPostEventSubscriber('post.deleted', callback);
3877
+
3878
+ /**
3879
+ * ```js
3880
+ * import { onPostApproved } from '@amityco/ts-sdk'
3881
+ * const dispose = onPostApproved(post => {
3882
+ * // ...
3883
+ * })
3884
+ * ```
3885
+ *
3886
+ * Fired when a {@link Amity.Post} has been updated
3887
+ *
3888
+ * @param callback The function to call when the event was fired
3889
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3890
+ *
3891
+ * @category Post Events
3892
+ */
3893
+ const onPostApproved = (callback) => createPostEventSubscriber('post.approved', callback);
3894
+
3895
+ /**
3896
+ * ```js
3897
+ * import { onPostDeclined } from '@amityco/ts-sdk'
3898
+ * const dispose = onPostDeclined(post => {
3899
+ * // ...
3900
+ * })
3901
+ * ```
3902
+ *
3903
+ * Fired when a {@link Amity.Post} has been updated
3904
+ *
3905
+ * @param callback The function to call when the event was fired
3906
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3907
+ *
3908
+ * @category Post Events
3909
+ */
3910
+ const onPostDeclined = (callback) => createPostEventSubscriber('post.declined', callback);
3911
+
3912
+ /**
3913
+ * ```js
3914
+ * import { onPostFlagged } from '@amityco/ts-sdk'
3915
+ * const dispose = onPostFlagged(post => {
3916
+ * // ...
3917
+ * })
3918
+ * ```
3919
+ *
3920
+ * Fired when a {@link Amity.Post} has been flagged
3921
+ *
3922
+ * @param callback The function to call when the event was fired
3923
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3924
+ *
3925
+ * @category Post Events
3926
+ */
3927
+ const onPostFlagged = (callback) => createPostEventSubscriber('post.flagged', callback);
3928
+
3929
+ /**
3930
+ * ```js
3931
+ * import { onPostUnflagged } from '@amityco/ts-sdk'
3932
+ * const dispose = onPostUnflagged(post => {
3933
+ * // ...
3934
+ * })
3935
+ * ```
3936
+ *
3937
+ * Fired when a flag has been removed from a {@link Amity.Post}
3938
+ *
3939
+ * @param callback The function to call when the event was fired
3940
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3941
+ *
3942
+ * @category Post Events
3943
+ */
3944
+ const onPostUnflagged = (callback) => createPostEventSubscriber('post.unflagged', callback);
3945
+
3946
+ /**
3947
+ * ```js
3948
+ * import { onPostReactionAdded } from '@amityco/ts-sdk'
3949
+ * const dispose = onPostReactionAdded(post => {
3950
+ * // ...
3951
+ * })
3952
+ * ```
3953
+ *
3954
+ * Fired when a {@link Amity.Post} has been reacted
3955
+ *
3956
+ * @param callback The function to call when the event was fired
3957
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3958
+ *
3959
+ * @category Post Events
3960
+ */
3961
+ const onPostReactionAdded = (callback) => {
3962
+ const client = getActiveClient();
3963
+ const filter = (payload) => {
3964
+ var _a, _b;
3965
+ const [cached] = (_a = pullFromCache('post', payload.posts[0].postId)) !== null && _a !== void 0 ? _a : [];
3966
+ const postPayload = __rest(payload, ["reactor"]);
3967
+ decoratePayload(postPayload);
3968
+ preparePayloadForCache('post.addReaction', payload);
3969
+ ingestInCache(postPayload);
3970
+ const [post] = (_b = pullFromCache('post', payload.posts[0].postId)) !== null && _b !== void 0 ? _b : [];
3971
+ if (cached && isMatch(cached, post)) {
3972
+ return;
3973
+ }
3974
+ callback(post);
3975
+ };
3976
+ return createEventSubscriber(client, 'post.addReaction', 'post.addReaction', filter);
3977
+ };
3978
+
3979
+ /**
3980
+ * ```js
3981
+ * import { onPostReactionRemoved } from '@amityco/ts-sdk'
3982
+ * const dispose = onPostReactionRemoved(post => {
3983
+ * // ...
3984
+ * })
3985
+ * ```
3986
+ *
3987
+ * Fired when a reaction has been removed from a {@link Amity.Post}
3988
+ *
3989
+ * @param callback The function to call when the event was fired
3990
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
3991
+ *
3992
+ * @category Post Events
3993
+ */
3994
+ const onPostReactionRemoved = (callback) => {
3995
+ const client = getActiveClient();
3996
+ const filter = (payload) => {
3997
+ var _a, _b;
3998
+ const [cached] = (_a = pullFromCache('post', payload.posts[0].postId)) !== null && _a !== void 0 ? _a : [];
3999
+ const postPayload = __rest(payload, ["reactor"]);
4000
+ decoratePayload(postPayload);
4001
+ preparePayloadForCache('post.removeReaction', payload);
4002
+ ingestInCache(postPayload);
4003
+ const [post] = (_b = pullFromCache('post', payload.posts[0].postId)) !== null && _b !== void 0 ? _b : [];
4004
+ if (cached && isMatch(cached, post)) {
4005
+ return;
4006
+ }
4007
+ callback(post);
4008
+ };
4009
+ return createEventSubscriber(client, 'post.removeReaction', 'post.removeReaction', filter);
4010
+ };
4011
+
4012
+ const createCommentEventSubscriber = (event, callback) => {
4013
+ const client = getActiveClient();
4014
+ const filter = (payload) => {
4015
+ var _a, _b;
4016
+ const [cached] = (_a = pullFromCache('comment', payload.comments[0].commentId)) !== null && _a !== void 0 ? _a : [];
4017
+ decoratePayload(payload);
4018
+ ingestInCache(payload);
4019
+ const [comment] = (_b = pullFromCache('comment', payload.comments[0].commentId)) !== null && _b !== void 0 ? _b : [];
4020
+ if (cached && isMatch(cached, comment)) {
4021
+ return;
4022
+ }
4023
+ callback(comment);
4024
+ };
4025
+ return createEventSubscriber(client, event, event, filter);
4026
+ };
4027
+
4028
+ /**
4029
+ * ```js
4030
+ * import { onCommentCreated } from '@amityco/ts-sdk'
4031
+ * const dispose = onCommentCreated(comment => {
4032
+ * // ...
4033
+ * })
4034
+ * ```
4035
+ *
4036
+ * Fired when {@link Amity.Comment} has been created
4037
+ *
4038
+ * @param callback The function to call when the event was fired
4039
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4040
+ *
4041
+ * @category Comment Events
4042
+ */
4043
+ const onCommentCreated = (callback) => createCommentEventSubscriber('comment.created', callback);
4044
+
4045
+ /**
4046
+ * ```js
4047
+ * import { onCommentUpdated } from '@amityco/ts-sdk'
4048
+ * const dispose = onCommentUpdated(comment => {
4049
+ * // ...
4050
+ * })
4051
+ * ```
4052
+ *
4053
+ * Fired when a {@link Amity.Comment} has been updated
4054
+ *
4055
+ * @param callback The function to call when the event was fired
4056
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4057
+ *
4058
+ * @category Comment Events
4059
+ */
4060
+ const onCommentUpdated = (callback) => createCommentEventSubscriber('comment.updated', callback);
4061
+
4062
+ /**
4063
+ * ```js
4064
+ * import { onCommentDeleted } from '@amityco/ts-sdk'
4065
+ * const dispose = onCommentDeleted(comment => {
4066
+ * // ...
4067
+ * })
4068
+ * ```
4069
+ *
4070
+ * Fired when a {@link Amity.Comment} has been deleted
4071
+ *
4072
+ * @param callback The function to call when the event was fired
4073
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4074
+ *
4075
+ * @category Comment Events
4076
+ */
4077
+ const onCommentDeleted = (callback) => createCommentEventSubscriber('comment.deleted', callback);
4078
+
4079
+ /**
4080
+ * ```js
4081
+ * import { onCommentFlagged } from '@amityco/ts-sdk'
4082
+ * const dispose = onCommentFlagged(comment => {
4083
+ * // ...
4084
+ * })
4085
+ * ```
4086
+ *
4087
+ * Fired when a {@link Amity.Comment} has been flagged
4088
+ *
4089
+ * @param callback The function to call when the event was fired
4090
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4091
+ *
4092
+ * @category Comment Events
4093
+ */
4094
+ const onCommentFlagged = (callback) => createCommentEventSubscriber('comment.flagged', callback);
4095
+
4096
+ /**
4097
+ * ```js
4098
+ * import { onCommentUnflagged } from '@amityco/ts-sdk'
4099
+ * const dispose = onCommentUnflagged(comment => {
4100
+ * // ...
4101
+ * })
4102
+ * ```
4103
+ *
4104
+ * Fired when a flag has been removed from a {@link Amity.Comment}
4105
+ *
4106
+ * @param callback The function to call when the event was fired
4107
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4108
+ *
4109
+ * @category Comment Events
4110
+ */
4111
+ const onCommentUnflagged = (callback) => createCommentEventSubscriber('comment.unflagged', callback);
4112
+
4113
+ /**
4114
+ * ```js
4115
+ * import { onCommentReactionAdded } from '@amityco/ts-sdk'
4116
+ * const dispose = onCommentReactionAdded(comment => {
4117
+ * // ...
4118
+ * })
4119
+ * ```
4120
+ *
4121
+ * Fired when a {@link Amity.Comment} has been reacted
4122
+ *
4123
+ * @param callback The function to call when the event was fired
4124
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4125
+ *
4126
+ * @category Comment Events
4127
+ */
4128
+ const onCommentReactionAdded = (callback) => {
4129
+ const client = getActiveClient();
4130
+ const filter = (payload) => {
4131
+ var _a, _b;
4132
+ const [cached] = (_a = pullFromCache('comment', payload.comments[0].commentId)) !== null && _a !== void 0 ? _a : [];
4133
+ const commentPayload = __rest(payload, ["reactor"]);
4134
+ decoratePayload(commentPayload);
4135
+ preparePayloadForCache('comment.addReaction', payload);
4136
+ ingestInCache(commentPayload);
4137
+ const [comment] = (_b = pullFromCache('comment', payload.comments[0].commentId)) !== null && _b !== void 0 ? _b : [];
4138
+ if (cached && isMatch(cached, comment)) {
4139
+ return;
4140
+ }
4141
+ callback(comment);
4142
+ };
4143
+ return createEventSubscriber(client, 'comment.addReaction', 'comment.addReaction', filter);
4144
+ };
4145
+
4146
+ /**
4147
+ * ```js
4148
+ * import { onCommentReactionRemoved } from '@amityco/ts-sdk'
4149
+ * const dispose = onCommentReactionRemoved(comment => {
4150
+ * // ...
4151
+ * })
4152
+ * ```
4153
+ *
4154
+ * Fired when a reaction has been removed from a {@link Amity.Comment}
4155
+ *
4156
+ * @param callback The function to call when the event was fired
4157
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4158
+ *
4159
+ * @category Comment Events
4160
+ */
4161
+ const onCommentReactionRemoved = (callback) => {
4162
+ const client = getActiveClient();
4163
+ const filter = (payload) => {
4164
+ var _a, _b;
4165
+ const [cached] = (_a = pullFromCache('comment', payload.comments[0].commentId)) !== null && _a !== void 0 ? _a : [];
4166
+ const commentPayload = __rest(payload, ["reactor"]);
4167
+ decoratePayload(commentPayload);
4168
+ preparePayloadForCache('comment.removeReaction', payload);
4169
+ ingestInCache(commentPayload);
4170
+ const [comment] = (_b = pullFromCache('comment', payload.comments[0].commentId)) !== null && _b !== void 0 ? _b : [];
4171
+ if (cached && isMatch(cached, comment)) {
4172
+ return;
4173
+ }
4174
+ callback(comment);
4175
+ };
4176
+ return createEventSubscriber(client, 'comment.removeReaction', 'comment.removeReaction', filter);
4177
+ };
4178
+
4179
+ /**
4180
+ * ```js
4181
+ * import { onReactionRemoved } from '@amityco/ts-sdk'
4182
+ * const dispose = onReactionRemoved('post', postId, post => {
4183
+ * // ...
4184
+ * })
4185
+ * ```
4186
+ *
4187
+ * Fired when an {@link Amity.Reaction} has been removed
4188
+ *
4189
+ * @param {@link Amity.ReactableType} referenceType
4190
+ * @param {string} referenceId
4191
+ * @param callback The function to call when the event was fired
4192
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4193
+ *
4194
+ * @category Message Events
4195
+ **/
4196
+ const onReactionRemoved = (referenceType, referenceId, callback) => {
4197
+ const callbackWrapper = (model) => {
4198
+ if (getResolver(referenceType)(model) === referenceId) {
4199
+ callback(model);
4200
+ }
4201
+ };
4202
+ if (referenceType === 'message') {
4203
+ const client = getActiveClient();
4204
+ const filter = (payload) => {
4205
+ var _a, _b;
4206
+ const reactionsCountInCache = (_b = ((_a = pullFromCache('message', payload.messages[0].messageId)) !== null && _a !== void 0 ? _a : [])[0]) === null || _b === void 0 ? void 0 : _b.reactionsCount;
4207
+ const isReactionEvent = reactionsCountInCache !== payload.messages[0].reactionsCount;
4208
+ decoratePayload(payload);
4209
+ ingestInCache(payload);
4210
+ if (isReactionEvent) {
4211
+ callbackWrapper(payload.messages[0]);
4212
+ }
4213
+ };
4214
+ return createEventSubscriber(client, 'reaction/onReactionRemoved', 'v3.message.didUpdate', filter);
4215
+ }
4216
+ if (referenceType === 'post') {
4217
+ return onPostReactionRemoved(callbackWrapper);
4218
+ }
4219
+ return onCommentReactionRemoved(callbackWrapper);
4220
+ };
4221
+
4222
+ var REFERENCE_TYPES = {
4223
+ post: {
4224
+ domainName: 'posts',
4225
+ eventName: 'v3/post.isflagbyme',
4226
+ primaryKey: 'postId',
4227
+ },
4228
+ comment: {
4229
+ domainName: 'comments',
4230
+ eventName: 'v3/comment.isflagbyme',
4231
+ primaryKey: 'commentId',
4232
+ },
4233
+ message: {
4234
+ domainName: 'messages',
4235
+ eventName: 'v3/message.isFlaggedByMe',
4236
+ primaryKey: 'messageId',
4237
+ },
4238
+ user: {
4239
+ domainName: 'users',
4240
+ eventName: 'user.isFlagByMe',
4241
+ primaryKey: 'userId',
4242
+ },
4243
+ };
4244
+
4245
+ /**
4246
+ * ```js
4247
+ * import { createReport } from '@amityco/ts-sdk'
4248
+ * const flagged = await createReport('post', postId)
4249
+ * ```
4250
+ *
4251
+ * @param referenceType The type of thing to add a report to, such as a post or a comment.
4252
+ * @param referenceId The ID of the thing to add a new report to.
4253
+ * @returns the created report result
4254
+ *
4255
+ * @category Report API
4256
+ * @async
4257
+ **/
4258
+ const createReport = async (referenceType, referenceId) => {
4259
+ const client = getActiveClient();
4260
+ client.log('report/createReport', { referenceType, referenceId });
4261
+ const { domainName } = REFERENCE_TYPES[referenceType];
3542
4262
  const { data } = await client.http.post(`/api/v3/${domainName}/${referenceId}/flag`);
4263
+ const event = referenceType === 'message'
4264
+ ? 'v3.message.didUpdate'
4265
+ : `${referenceType}.updated`;
3543
4266
  decoratePayload(data);
3544
4267
  ingestInCache(data);
3545
- fireEvent(`v3.${referenceType}.didUpdate`, data);
4268
+ fireEvent(event, data);
3546
4269
  return !!data;
3547
4270
  };
3548
4271
 
@@ -3564,9 +4287,12 @@ const deleteReport = async (referenceType, referenceId) => {
3564
4287
  client.log('report/deleteReport', { referenceType, referenceId });
3565
4288
  const { domainName } = REFERENCE_TYPES[referenceType];
3566
4289
  const { data } = await client.http.delete(`/api/v3/${domainName}/${referenceId}/unflag`);
4290
+ const event = referenceType === 'message'
4291
+ ? 'v3.message.didUpdate'
4292
+ : `${referenceType}.updated`;
3567
4293
  decoratePayload(data);
3568
4294
  ingestInCache(data);
3569
- fireEvent(`v3.${referenceType}.didUpdate`, data);
4295
+ fireEvent(event, data);
3570
4296
  return !!data;
3571
4297
  };
3572
4298
 
@@ -4336,166 +5062,253 @@ const observeMessage = (messageId, callback, policy = 'cache_then_server') => {
4336
5062
 
4337
5063
  /**
4338
5064
  * ```js
4339
- * import { observeMessages } from '@amityco/ts-sdk'
5065
+ * import { observeMessages } from '@amityco/ts-sdk'
5066
+ *
5067
+ * let messages = []
5068
+ * const unsub = observeMessages(channelId, message => merge(messages, message))
5069
+ * ```
5070
+ *
5071
+ * Observe all mutations on a list of {@link Amity.Message} for a given {@link Amity.Channel} object
5072
+ *
5073
+ * @param client the client to observe the message with
5074
+ * @param channelId the ID of the channel where to observe the messages
5075
+ * @param callback the function to call when new data are available
5076
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
5077
+ *
5078
+ * @category Message Observer
5079
+ */
5080
+ const observeMessages = (channelId, callback) => {
5081
+ const { log } = getActiveClient();
5082
+ const timestamp = Date.now();
5083
+ log(`observeMessages(tmpid: ${timestamp}) > listen`);
5084
+ const disposers = [];
5085
+ const router = (message, action) => {
5086
+ var _a, _b;
5087
+ if (message.channelId !== channelId)
5088
+ return;
5089
+ if (callback instanceof Function)
5090
+ return callback(message);
5091
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, message);
5092
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, message);
5093
+ };
5094
+ disposers.push(onMessageCreated(message => router(message, 'onCreate')), onMessageUpdated(message => router(message, 'onUpdate')), onMessageDeleted(message => router(message, 'onDelete')));
5095
+ return () => {
5096
+ log(`observeMessages(tmpid: ${timestamp}) > dispose`);
5097
+ disposers.forEach(fn => fn());
5098
+ };
5099
+ };
5100
+
5101
+ const createCommunityEventSubscriber = (event, callback) => {
5102
+ const client = getActiveClient();
5103
+ const filter = (payload) => {
5104
+ var _a, _b;
5105
+ const [cached] = (_a = pullFromCache('community', payload.communities[0].communityId)) !== null && _a !== void 0 ? _a : [];
5106
+ decoratePayload(payload);
5107
+ ingestInCache(payload);
5108
+ const [community] = (_b = pullFromCache('community', payload.communities[0].communityId)) !== null && _b !== void 0 ? _b : [];
5109
+ if (cached && isMatch(cached, community)) {
5110
+ return;
5111
+ }
5112
+ callback(community);
5113
+ };
5114
+ return createEventSubscriber(client, event, event, filter);
5115
+ };
5116
+ function hasPermission(member, payload, permission) {
5117
+ if (member.permissions.some(x => x === permission)) {
5118
+ return true;
5119
+ }
5120
+ return payload.users
5121
+ .find(user => user.userId === member.userId)
5122
+ .permissions.some(x => x === permission);
5123
+ }
5124
+ function getEventRelatedMember(event, payload) {
5125
+ if (event === 'community.joined' || event === 'community.left') {
5126
+ return payload.communityUsers[0];
5127
+ }
5128
+ // NOTE: backend returns the one who took the action and the one on whom
5129
+ // the action was taken. We need the 2nd one
5130
+ if (event === 'community.userRemoved') {
5131
+ return payload.communityUsers.filter(x => x.communityMembership === 'none')[0];
5132
+ }
5133
+ if (event === 'community.userBanned') {
5134
+ return payload.communityUsers.filter(x => x.communityMembership === 'banned')[0];
5135
+ }
5136
+ // NOTE: it might be that in certain edge cases permission check won't be enough
5137
+ if (event === 'community.userUnbanned') {
5138
+ return payload.communityUsers.filter(x => !hasPermission(x, payload, 'BAN_COMMUNITY_USER'))[0];
5139
+ }
5140
+ return payload.communityUsers.filter(x => !hasPermission(x, payload, 'ADD_COMMUNITY_USER'))[0];
5141
+ }
5142
+ const createCommunityMemberEventSubscriber = (event, callback) => {
5143
+ const client = getActiveClient();
5144
+ const filter = (payload) => {
5145
+ var _a, _b, _c, _d;
5146
+ const [cachedCommunity] = (_a = pullFromCache('community', payload.communities[0].communityId)) !== null && _a !== void 0 ? _a : [];
5147
+ const [cachedMember] = (_b = pullFromCache('communityUsers', getResolver('communityUsers')(getEventRelatedMember(event, payload)))) !== null && _b !== void 0 ? _b : [];
5148
+ decoratePayload(payload);
5149
+ ingestInCache(payload);
5150
+ const [community] = (_c = pullFromCache('community', payload.communities[0].communityId)) !== null && _c !== void 0 ? _c : [];
5151
+ const [member] = (_d = pullFromCache('communityUsers', getResolver('communityUsers')(getEventRelatedMember(event, payload)))) !== null && _d !== void 0 ? _d : [];
5152
+ if (cachedCommunity && isMatch(cachedCommunity, community) && cachedMember && isMatch(cachedMember, member)) {
5153
+ return;
5154
+ }
5155
+ callback(community, member);
5156
+ };
5157
+ return createEventSubscriber(client, event, event, filter);
5158
+ };
5159
+
5160
+ /**
5161
+ * ```js
5162
+ * import { onCommunityCreated } from '@amityco/ts-sdk'
5163
+ * const dispose = onCommunityCreated(community => {
5164
+ * // ...
5165
+ * })
5166
+ * ```
5167
+ *
5168
+ * Fired when {@link Amity.Community} have been created
5169
+ *
5170
+ * @param callback The function to call when the event was fired
5171
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
5172
+ *
5173
+ * @category Community Events
5174
+ */
5175
+ const onCommunityCreated = (callback) => createCommunityEventSubscriber('community.created', callback);
5176
+
5177
+ /**
5178
+ * ```js
5179
+ * import { onCommunityUpdated } from '@amityco/ts-sdk'
5180
+ * const dispose = onCommunityUpdated(community => {
5181
+ * // ...
5182
+ * })
5183
+ * ```
5184
+ *
5185
+ * Fired when a {@link Amity.Community} has been updated
5186
+ *
5187
+ * @param callback The function to call when the event was fired
5188
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
5189
+ *
5190
+ * @category Community Events
5191
+ */
5192
+ const onCommunityUpdated = (callback) => createCommunityEventSubscriber('community.updated', callback);
5193
+
5194
+ /**
5195
+ * ```js
5196
+ * import { onCommunityDeleted } from '@amityco/ts-sdk'
5197
+ * const dispose = onCommunityDeleted(community => {
5198
+ * // ...
5199
+ * })
5200
+ * ```
4340
5201
  *
4341
- * let messages = []
4342
- * const unsub = observeMessages(channelId, message => merge(messages, message))
5202
+ * Fired when a {@link Amity.Community} has been deleted
5203
+ *
5204
+ * @param callback The function to call when the event was fired
5205
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
5206
+ *
5207
+ * @category Community Events
5208
+ */
5209
+ const onCommunityDeleted = (callback) => createCommunityEventSubscriber('community.deleted', callback);
5210
+
5211
+ /**
5212
+ * ```js
5213
+ * import { onCommunityJoined } from '@amityco/ts-sdk'
5214
+ * const dispose = onCommunityJoined((community, member) => {
5215
+ * // ...
5216
+ * })
4343
5217
  * ```
4344
5218
  *
4345
- * Observe all mutations on a list of {@link Amity.Message} for a given {@link Amity.Channel} object
5219
+ * Fired when a {@link Amity.Community} has been joined
4346
5220
  *
4347
- * @param client the client to observe the message with
4348
- * @param channelId the ID of the channel where to observe the messages
4349
- * @param callback the function to call when new data are available
4350
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
5221
+ * @param callback The function to call when the event was fired
5222
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4351
5223
  *
4352
- * @category Message Observer
5224
+ * @category Community Events
4353
5225
  */
4354
- const observeMessages = (channelId, callback) => {
4355
- const { log } = getActiveClient();
4356
- const timestamp = Date.now();
4357
- log(`observeMessages(tmpid: ${timestamp}) > listen`);
4358
- const disposers = [];
4359
- const router = (message, action) => {
4360
- var _a, _b;
4361
- if (message.channelId !== channelId)
4362
- return;
4363
- if (callback instanceof Function)
4364
- return callback(message);
4365
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, message);
4366
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, message);
4367
- };
4368
- disposers.push(onMessageCreated(message => router(message, 'onCreate')), onMessageUpdated(message => router(message, 'onUpdate')), onMessageDeleted(message => router(message, 'onDelete')));
4369
- return () => {
4370
- log(`observeMessages(tmpid: ${timestamp}) > dispose`);
4371
- disposers.forEach(fn => fn());
4372
- };
4373
- };
5226
+ const onCommunityJoined = (callback) => createCommunityMemberEventSubscriber('community.joined', callback);
4374
5227
 
4375
5228
  /**
4376
5229
  * ```js
4377
- * import { onCommunityCreated } from '@amityco/ts-sdk'
4378
- * const dispose = onCommunityCreated(channel => {
5230
+ * import { onCommunityLeft } from '@amityco/ts-sdk'
5231
+ * const dispose = onCommunityLeft((community, member) => {
4379
5232
  * // ...
4380
5233
  * })
4381
5234
  * ```
4382
5235
  *
4383
- * Fired when any {@link Amity.Community} have been created
5236
+ * Fired when a {@link Amity.Community} has been left
4384
5237
  *
4385
5238
  * @param callback The function to call when the event was fired
4386
5239
  * @returns an {@link Amity.Unsubscriber} function to stop listening
4387
5240
  *
4388
5241
  * @category Community Events
4389
5242
  */
4390
- const onCommunityCreated = (callback) => {
4391
- const client = getActiveClient();
4392
- const filter = (payload) => {
4393
- decoratePayload(payload);
4394
- ingestInCache(payload);
4395
- callback(payload.communities[0]);
4396
- };
4397
- return createEventSubscriber(client, 'onCommunityCreated', 'v3.community.didCreate', filter);
4398
- };
5243
+ const onCommunityLeft = (callback) => createCommunityMemberEventSubscriber('community.left', callback);
4399
5244
 
4400
5245
  /**
4401
5246
  * ```js
4402
- * import { onCommunityUpdated } from '@amityco/ts-sdk'
4403
- * const dispose = onCommunityUpdated(channel => {
5247
+ * import { onCommunityUserAdded } from '@amityco/ts-sdk'
5248
+ * const dispose = onCommunityUserAdded((community, member) => {
4404
5249
  * // ...
4405
5250
  * })
4406
5251
  * ```
4407
5252
  *
4408
- * Fired when any {@link Amity.Community} have been updated
5253
+ * Fired when a user has been added to a {@link Amity.Community}
4409
5254
  *
4410
5255
  * @param callback The function to call when the event was fired
4411
5256
  * @returns an {@link Amity.Unsubscriber} function to stop listening
4412
5257
  *
4413
5258
  * @category Community Events
4414
5259
  */
4415
- const onCommunityUpdated = (callback) => {
4416
- const client = getActiveClient();
4417
- const filter = (payload) => {
4418
- decoratePayload(payload);
4419
- ingestInCache(payload);
4420
- callback(payload.communities[0]);
4421
- };
4422
- return createEventSubscriber(client, 'onCommunityUpdated', 'v3.community.didUpdate', filter);
4423
- };
5260
+ const onCommunityUserAdded = (callback) => createCommunityMemberEventSubscriber('community.userAdded', callback);
4424
5261
 
4425
5262
  /**
4426
5263
  * ```js
4427
- * import { onCommunityDeleted } from '@amityco/ts-sdk'
4428
- * const dispose = onCommunityDeleted(channel => {
5264
+ * import { onCommunityUserRemoved } from '@amityco/ts-sdk'
5265
+ * const dispose = onCommunityUserRemoved((community, member) => {
4429
5266
  * // ...
4430
5267
  * })
4431
5268
  * ```
4432
5269
  *
4433
- * Fired when any {@link Amity.Community} have been deleted
5270
+ * Fired when a user has been removed from a {@link Amity.Community}
4434
5271
  *
4435
5272
  * @param callback The function to call when the event was fired
4436
5273
  * @returns an {@link Amity.Unsubscriber} function to stop listening
4437
5274
  *
4438
5275
  * @category Community Events
4439
5276
  */
4440
- const onCommunityDeleted = (callback) => {
4441
- const client = getActiveClient();
4442
- const filter = (payload) => {
4443
- decoratePayload(payload);
4444
- ingestInCache(payload);
4445
- callback(payload.communities[0]);
4446
- };
4447
- return createEventSubscriber(client, 'onCommunityDeleted', 'v3.community.didDelete', filter);
4448
- };
5277
+ const onCommunityUserRemoved = (callback) => createCommunityMemberEventSubscriber('community.userRemoved', callback);
4449
5278
 
4450
5279
  /**
4451
5280
  * ```js
4452
- * import { onCommunityJoined } from '@amityco/ts-sdk'
4453
- * const dispose = onCommunityJoined(channel => {
5281
+ * import { onCommunityUserBanned } from '@amityco/ts-sdk'
5282
+ * const dispose = onCommunityUserBanned((community, member) => {
4454
5283
  * // ...
4455
5284
  * })
4456
5285
  * ```
4457
5286
  *
4458
- * Fired when any {@link Amity.Community} was joined
5287
+ * Fired when a user has been banned in a {@link Amity.Community}
4459
5288
  *
4460
5289
  * @param callback The function to call when the event was fired
4461
5290
  * @returns an {@link Amity.Unsubscriber} function to stop listening
4462
5291
  *
4463
5292
  * @category Community Events
4464
5293
  */
4465
- const onCommunityJoined = (callback) => {
4466
- const client = getActiveClient();
4467
- const filter = (payload) => {
4468
- decoratePayload(payload);
4469
- ingestInCache(payload);
4470
- callback(payload.communities[0]);
4471
- };
4472
- return createEventSubscriber(client, 'onCommunityJoined', 'v3.community.didJoin', filter);
4473
- };
5294
+ const onCommunityUserBanned = (callback) => createCommunityMemberEventSubscriber('community.userBanned', callback);
4474
5295
 
4475
5296
  /**
4476
5297
  * ```js
4477
- * import { onCommunityLeft } from '@amityco/ts-sdk'
4478
- * const dispose = onCommunityLeft(channel => {
5298
+ * import { onCommunityUserUnbanned } from '@amityco/ts-sdk'
5299
+ * const dispose = onCommunityUserUnbanned((community, member) => {
4479
5300
  * // ...
4480
5301
  * })
4481
5302
  * ```
4482
5303
  *
4483
- * Fired when any {@link Amity.Community} was left
5304
+ * Fired when a user has been unbanned in a {@link Amity.Community}
4484
5305
  *
4485
5306
  * @param callback The function to call when the event was fired
4486
5307
  * @returns an {@link Amity.Unsubscriber} function to stop listening
4487
5308
  *
4488
5309
  * @category Community Events
4489
5310
  */
4490
- const onCommunityLeft = (callback) => {
4491
- const client = getActiveClient();
4492
- const filter = (payload) => {
4493
- decoratePayload(payload);
4494
- ingestInCache(payload);
4495
- callback(payload.communities[0]);
4496
- };
4497
- return createEventSubscriber(client, 'onCommunityLeft', 'v3.community.didLeave', filter);
4498
- };
5311
+ const onCommunityUserUnbanned = (callback) => createCommunityMemberEventSubscriber('community.userUnbanned', callback);
4499
5312
 
4500
5313
  /**
4501
5314
  * ```js
@@ -4519,19 +5332,22 @@ const observeCommunity = (communityId, callback) => {
4519
5332
  log(`observeCommunity(tmpid: ${timestamp}) > listen`);
4520
5333
  // wrapper function to make sure
4521
5334
  const router = (result, action) => {
4522
- var _a, _b, _c;
4523
- // filter function
4524
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.communityId) !== communityId)
4525
- return;
5335
+ var _a, _b;
4526
5336
  if (callback instanceof Function)
4527
5337
  return callback(result);
4528
5338
  if (action !== 'onFetch')
4529
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4530
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
5339
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
5340
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
5341
+ };
5342
+ const realtimeRouter = (result, action) => {
5343
+ var _a;
5344
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.communityId) !== communityId)
5345
+ return;
5346
+ router(result, action);
4531
5347
  };
4532
5348
  const disposers = [];
4533
- disposers.push(onCommunityUpdated(data => router({ data }, 'onUpdate')), onCommunityDeleted(data => router({ data }, 'onDelete')), onCommunityJoined(data => router({ data }, 'onJoin')), onCommunityLeft(data => router({ data }, 'onLeft')));
4534
- runQuery(createQuery(getCommunity, communityId), result => result.data && router(result, 'onFetch'));
5349
+ disposers.push(onCommunityUpdated(data => realtimeRouter({ data }, 'onUpdate')), onCommunityDeleted(data => realtimeRouter({ data }, 'onDelete')), onCommunityJoined(data => realtimeRouter({ data }, 'onJoin')), onCommunityLeft(data => realtimeRouter({ data }, 'onLeft')), onCommunityUserAdded(data => realtimeRouter({ data }, 'onUserAdded')), onCommunityUserRemoved(data => realtimeRouter({ data }, 'onUserRemoved')), onCommunityUserBanned(data => realtimeRouter({ data }, 'onUserBanned')), onCommunityUserUnbanned(data => realtimeRouter({ data }, 'onUserUnbanned')));
5350
+ runQuery(createQuery(getCommunity, communityId), result => router(result, 'onFetch'));
4535
5351
  return () => {
4536
5352
  log(`observeCommunity(tmpid: ${timestamp}) > dispose`);
4537
5353
  disposers.forEach(fn => fn());
@@ -4568,81 +5384,6 @@ const queryGlobalFeed = async (query) => {
4568
5384
  return { data: toRecord(posts), nextPage, prevPage };
4569
5385
  };
4570
5386
 
4571
- /**
4572
- * ```js
4573
- * import { onPostCreated } from '@amityco/ts-sdk'
4574
- * const dispose = onPostCreated(post => {
4575
- * // ...
4576
- * })
4577
- * ```
4578
- *
4579
- * Fired when an {@link Amity.Post} has been created
4580
- *
4581
- * @param callback The function to call when the event was fired
4582
- * @returns an {@link Amity.Unsubscriber} function to stop listening
4583
- *
4584
- * @category Post Events
4585
- */
4586
- const onPostCreated = (callback) => {
4587
- const client = getActiveClient();
4588
- const filter = (payload) => {
4589
- decoratePayload(payload);
4590
- ingestInCache(payload);
4591
- callback(payload.posts[0]);
4592
- };
4593
- return createEventSubscriber(client, 'message/onPostCreated', 'v3.post.didCreate', filter);
4594
- };
4595
-
4596
- /**
4597
- * ```js
4598
- * import { onPostUpdated } from '@amityco/ts-sdk'
4599
- * const dispose = onPostUpdated(post => {
4600
- * // ...
4601
- * })
4602
- * ```
4603
- *
4604
- * Fired when an {@link Amity.Post} has been updated
4605
- *
4606
- * @param callback The function to call when the event was fired
4607
- * @returns an {@link Amity.Unsubscriber} function to stop listening
4608
- *
4609
- * @category Post Events
4610
- */
4611
- const onPostUpdated = (callback) => {
4612
- const client = getActiveClient();
4613
- const filter = (payload) => {
4614
- decoratePayload(payload);
4615
- ingestInCache(payload);
4616
- callback(payload.posts[0]);
4617
- };
4618
- return createEventSubscriber(client, 'message/onPostUpdated', 'v3.post.didUpdate', filter);
4619
- };
4620
-
4621
- /**
4622
- * ```js
4623
- * import { onPostDeleted } from '@amityco/ts-sdk'
4624
- * const dispose = onPostDeleted(post => {
4625
- * // ...
4626
- * })
4627
- * ```
4628
- *
4629
- * Fired when an {@link Amity.Post} has been deleted
4630
- *
4631
- * @param callback The function to call when the event was fired
4632
- * @returns an {@link Amity.Unsubscriber} function to stop listening
4633
- *
4634
- * @category Post Events
4635
- */
4636
- const onPostDeleted = (callback) => {
4637
- const client = getActiveClient();
4638
- const filter = (payload) => {
4639
- decoratePayload(payload);
4640
- ingestInCache(payload);
4641
- callback(payload.posts[0]);
4642
- };
4643
- return createEventSubscriber(client, 'message/onPostDeleted', 'v3.post.didDelete', filter);
4644
- };
4645
-
4646
5387
  /**
4647
5388
  * ```js
4648
5389
  * import { observePosts } from '@amityco/ts-sdk'
@@ -4678,7 +5419,7 @@ const observePosts = (params, callback) => {
4678
5419
  (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, post);
4679
5420
  (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, post);
4680
5421
  };
4681
- disposers.push(onPostCreated(post => router(post, 'onCreate')), onPostUpdated(post => router(post, 'onUpdate')), onPostDeleted(post => router(post, 'onDelete')));
5422
+ disposers.push(onPostCreated(post => router(post, 'onCreate')), onPostUpdated(post => router(post, 'onUpdate')), onPostDeleted(post => router(post, 'onDelete')), onPostApproved(post => router(post, 'onApproved')), onPostDeclined(post => router(post, 'onDeclined')), onPostFlagged(post => router(post, 'onFlagged')), onPostUnflagged(post => router(post, 'onUnflagged')), onPostReactionAdded(post => router(post, 'onReactionAdded')), onPostReactionRemoved(post => router(post, 'onReactionRemoved')));
4682
5423
  return () => {
4683
5424
  log(`observePosts(tmpid: ${timestamp}) > dispose`);
4684
5425
  disposers.forEach(fn => fn());
@@ -4707,100 +5448,28 @@ const observePost = (postId, callback, policy = 'cache_then_server') => {
4707
5448
  log(`observePost(tmpid: ${timestamp}) > listen`);
4708
5449
  // wrapper function to make sure
4709
5450
  const router = (result, action) => {
4710
- var _a, _b, _c;
4711
- // filter function
4712
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.postId) !== postId)
4713
- return;
5451
+ var _a, _b;
4714
5452
  if (callback instanceof Function)
4715
5453
  return callback(result);
4716
5454
  if (action !== 'onFetch')
4717
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4718
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
5455
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
5456
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
5457
+ };
5458
+ const realtimeRouter = (result, action) => {
5459
+ var _a;
5460
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.postId) !== postId)
5461
+ return;
5462
+ router(result, action);
4719
5463
  };
4720
5464
  const disposers = [];
4721
- disposers.push(onPostUpdated(data => router({ data }, 'onUpdate')), onPostDeleted(data => router({ data }, 'onDelete')));
4722
- runQuery(createQuery(getPost, postId), (result) => result.data && router(result, 'onFetch'), queryOptions(policy));
5465
+ disposers.push(onPostUpdated(data => realtimeRouter({ data }, 'onUpdate')), onPostDeleted(data => realtimeRouter({ data }, 'onDelete')), onPostApproved(data => realtimeRouter({ data }, 'onApproved')), onPostDeclined(data => realtimeRouter({ data }, 'onDeclined')), onPostFlagged(data => realtimeRouter({ data }, 'onFlagged')), onPostUnflagged(data => realtimeRouter({ data }, 'onUnflagged')), onPostReactionAdded(data => realtimeRouter({ data }, 'onReactionAdded')), onPostReactionRemoved(data => realtimeRouter({ data }, 'onReactionRemoved')));
5466
+ runQuery(createQuery(getPost, postId), (result) => router(result, 'onFetch'), queryOptions(policy));
4723
5467
  return () => {
4724
5468
  log(`observePosts(tmpid: ${timestamp}) > dispose`);
4725
5469
  disposers.forEach(fn => fn());
4726
5470
  };
4727
5471
  };
4728
5472
 
4729
- /**
4730
- * ```js
4731
- * import { onCommentCreated } from '@amityco/ts-sdk'
4732
- * const dispose = onCommentCreated(comment => {
4733
- * // ...
4734
- * })
4735
- * ```
4736
- *
4737
- * Fired when an {@link Amity.Comment} has been created
4738
- *
4739
- * @param callback The function to call when the event was fired
4740
- * @returns an {@link Amity.Unsubscriber} function to stop listening
4741
- *
4742
- * @category Comment Events
4743
- */
4744
- const onCommentCreated = (callback) => {
4745
- const client = getActiveClient();
4746
- const filter = (payload) => {
4747
- decoratePayload(payload);
4748
- ingestInCache(payload);
4749
- callback(payload.comments[0]);
4750
- };
4751
- return createEventSubscriber(client, 'message/onCommentCreated', 'v3.comment.didCreate', filter);
4752
- };
4753
-
4754
- /**
4755
- * ```js
4756
- * import { onCommentUpdated } from '@amityco/ts-sdk'
4757
- * const dispose = onCommentUpdated(comment => {
4758
- * // ...
4759
- * })
4760
- * ```
4761
- *
4762
- * Fired when an {@link Amity.Comment} has been updated
4763
- *
4764
- * @param callback The function to call when the event was fired
4765
- * @returns an {@link Amity.Unsubscriber} function to stop listening
4766
- *
4767
- * @category Comment Events
4768
- */
4769
- const onCommentUpdated = (callback) => {
4770
- const client = getActiveClient();
4771
- const filter = (payload) => {
4772
- decoratePayload(payload);
4773
- ingestInCache(payload);
4774
- callback(payload.comments[0]);
4775
- };
4776
- return createEventSubscriber(client, 'message/onCommentUpdated', 'v3.comment.didUpdate', filter);
4777
- };
4778
-
4779
- /**
4780
- * ```js
4781
- * import { onCommentDeleted } from '@amityco/ts-sdk'
4782
- * const dispose = onCommentDeleted(comment => {
4783
- * // ...
4784
- * })
4785
- * ```
4786
- *
4787
- * Fired when an {@link Amity.Comment} has been deleted
4788
- *
4789
- * @param callback The function to call when the event was fired
4790
- * @returns an {@link Amity.Unsubscriber} function to stop listening
4791
- *
4792
- * @category Comment Events
4793
- */
4794
- const onCommentDeleted = (callback) => {
4795
- const client = getActiveClient();
4796
- const filter = (payload) => {
4797
- decoratePayload(payload);
4798
- ingestInCache(payload);
4799
- callback(payload.comments[0]);
4800
- };
4801
- return createEventSubscriber(client, 'message/onCommentDeleted', 'v3.comment.didDelete', filter);
4802
- };
4803
-
4804
5473
  /**
4805
5474
  * ```js
4806
5475
  * import { observeComments } from '@amityco/ts-sdk'
@@ -4831,7 +5500,7 @@ const observeComments = (postId, callback) => {
4831
5500
  (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, comment);
4832
5501
  (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, comment);
4833
5502
  };
4834
- disposers.push(onCommentCreated(comment => router(comment, 'onCreate')), onCommentUpdated(comment => router(comment, 'onUpdate')), onCommentDeleted(comment => router(comment, 'onDelete')));
5503
+ disposers.push(onCommentCreated(comment => router(comment, 'onCreate')), onCommentUpdated(comment => router(comment, 'onUpdate')), onCommentDeleted(comment => router(comment, 'onDelete')), onCommentFlagged(comment => router(comment, 'onFlagged')), onCommentUnflagged(comment => router(comment, 'onUnflagged')), onCommentReactionAdded(comment => router(comment, 'onReactionAdded')), onCommentReactionRemoved(comment => router(comment, 'onReactionRemoved')));
4835
5504
  return () => {
4836
5505
  log(`observeComments(tmpid: ${timestamp}) > dispose`);
4837
5506
  disposers.forEach(fn => fn());
@@ -4860,19 +5529,22 @@ const observeComment = (commentId, callback, policy = 'cache_then_server') => {
4860
5529
  log(`observeComment(tmpid: ${timestamp}) > listen`);
4861
5530
  // wrapper function to make sure
4862
5531
  const router = (result, action) => {
4863
- var _a, _b, _c;
4864
- // filter function
4865
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.commentId) !== commentId)
4866
- return;
5532
+ var _a, _b;
4867
5533
  if (callback instanceof Function)
4868
5534
  return callback(result);
4869
5535
  if (action !== 'onFetch')
4870
- (_b = callback.onEvent) === null || _b === void 0 ? void 0 : _b.call(callback, action, result);
4871
- (_c = callback[action]) === null || _c === void 0 ? void 0 : _c.call(callback, result);
5536
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
5537
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
5538
+ };
5539
+ const realtimeRouter = (result, action) => {
5540
+ var _a;
5541
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.commentId) !== commentId)
5542
+ return;
5543
+ router(result, action);
4872
5544
  };
4873
5545
  const disposers = [];
4874
- disposers.push(onCommentUpdated(data => router({ data }, 'onUpdate')), onCommentDeleted(data => router({ data }, 'onDelete')));
4875
- runQuery(createQuery(getComment, commentId), result => result.data && router(result, 'onFetch'), queryOptions(policy));
5546
+ disposers.push(onCommentUpdated(data => realtimeRouter({ data }, 'onUpdate')), onCommentDeleted(data => realtimeRouter({ data }, 'onDelete')), onCommentFlagged(data => realtimeRouter({ data }, 'onFlagged')), onCommentUnflagged(data => realtimeRouter({ data }, 'onUnflagged')), onCommentReactionAdded(data => realtimeRouter({ data }, 'onReactionAdded')), onCommentReactionRemoved(data => realtimeRouter({ data }, 'onReactionRemoved')));
5547
+ runQuery(createQuery(getComment, commentId), result => router(result, 'onFetch'), queryOptions(policy));
4876
5548
  return () => {
4877
5549
  log(`observeComment(tmpid: ${timestamp}) > dispose`);
4878
5550
  disposers.forEach(fn => fn());
@@ -5112,17 +5784,21 @@ exports.getActiveClient = getActiveClient;
5112
5784
  exports.getChannel = getChannel;
5113
5785
  exports.getChannels = getChannels;
5114
5786
  exports.getComment = getComment;
5787
+ exports.getCommentTopic = getCommentTopic;
5115
5788
  exports.getComments = getComments;
5116
5789
  exports.getCommunities = getCommunities;
5117
5790
  exports.getCommunity = getCommunity;
5791
+ exports.getCommunityTopic = getCommunityTopic;
5118
5792
  exports.getFile = getFile;
5119
5793
  exports.getMessage = getMessage;
5120
5794
  exports.getMessages = getMessages;
5121
5795
  exports.getPost = getPost;
5796
+ exports.getPostTopic = getPostTopic;
5122
5797
  exports.getPosts = getPosts;
5123
5798
  exports.getRole = getRole;
5124
5799
  exports.getStream = getStream;
5125
5800
  exports.getUser = getUser;
5801
+ exports.getUserTopic = getUserTopic;
5126
5802
  exports.getUsers = getUsers;
5127
5803
  exports.ingestInCache = ingestInCache;
5128
5804
  exports.isAfterBefore = isAfterBefore;
@@ -5163,22 +5839,39 @@ exports.onClientBanned = onClientBanned;
5163
5839
  exports.onClientDisconnected = onClientDisconnected;
5164
5840
  exports.onCommentCreated = onCommentCreated;
5165
5841
  exports.onCommentDeleted = onCommentDeleted;
5842
+ exports.onCommentFlagged = onCommentFlagged;
5843
+ exports.onCommentReactionAdded = onCommentReactionAdded;
5844
+ exports.onCommentReactionRemoved = onCommentReactionRemoved;
5845
+ exports.onCommentUnflagged = onCommentUnflagged;
5166
5846
  exports.onCommentUpdated = onCommentUpdated;
5167
5847
  exports.onCommunityCreated = onCommunityCreated;
5168
5848
  exports.onCommunityDeleted = onCommunityDeleted;
5169
5849
  exports.onCommunityJoined = onCommunityJoined;
5170
5850
  exports.onCommunityLeft = onCommunityLeft;
5171
5851
  exports.onCommunityUpdated = onCommunityUpdated;
5852
+ exports.onCommunityUserAdded = onCommunityUserAdded;
5853
+ exports.onCommunityUserBanned = onCommunityUserBanned;
5854
+ exports.onCommunityUserRemoved = onCommunityUserRemoved;
5855
+ exports.onCommunityUserUnbanned = onCommunityUserUnbanned;
5172
5856
  exports.onConnectionError = onConnectionError;
5173
5857
  exports.onMemberAdded = onMemberAdded;
5174
5858
  exports.onMemberRemoved = onMemberRemoved;
5175
5859
  exports.onMessageCreated = onMessageCreated;
5176
5860
  exports.onMessageDeleted = onMessageDeleted;
5177
5861
  exports.onMessageUpdated = onMessageUpdated;
5862
+ exports.onPostApproved = onPostApproved;
5178
5863
  exports.onPostCreated = onPostCreated;
5864
+ exports.onPostDeclined = onPostDeclined;
5179
5865
  exports.onPostDeleted = onPostDeleted;
5866
+ exports.onPostFlagged = onPostFlagged;
5867
+ exports.onPostReactionAdded = onPostReactionAdded;
5868
+ exports.onPostReactionRemoved = onPostReactionRemoved;
5869
+ exports.onPostUnflagged = onPostUnflagged;
5180
5870
  exports.onPostUpdated = onPostUpdated;
5181
5871
  exports.onReactionRemoved = onReactionRemoved;
5872
+ exports.onUserFlagCleared = onUserFlagCleared;
5873
+ exports.onUserFlagged = onUserFlagged;
5874
+ exports.onUserUnflagged = onUserUnflagged;
5182
5875
  exports.onUserUpdated = onUserUpdated;
5183
5876
  exports.persistentStore = persistentStore;
5184
5877
  exports.pullFromCache = pullFromCache;
@@ -5208,6 +5901,7 @@ exports.sortByFirstCreated = sortByFirstCreated;
5208
5901
  exports.sortByLastActivity = sortByLastActivity;
5209
5902
  exports.sortByLastCreated = sortByLastCreated;
5210
5903
  exports.sortBySegmentNumber = sortBySegmentNumber;
5904
+ exports.subscribeTopic = subscribeTopic;
5211
5905
  exports.syncInCache = syncInCache;
5212
5906
  exports.toPage = toPage;
5213
5907
  exports.toToken = toToken;