@amityco/ts-sdk 0.0.1-beta.27 → 0.0.1-beta.28

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 (185) hide show
  1. package/.eslintrc.json +1 -0
  2. package/dist/@types/core/payload.d.ts +12 -10
  3. package/dist/@types/core/payload.d.ts.map +1 -1
  4. package/dist/@types/domains/channel.d.ts +5 -1
  5. package/dist/@types/domains/channel.d.ts.map +1 -1
  6. package/dist/@types/domains/client.d.ts +13 -0
  7. package/dist/@types/domains/client.d.ts.map +1 -1
  8. package/dist/@types/domains/content.d.ts +26 -3
  9. package/dist/@types/domains/content.d.ts.map +1 -1
  10. package/dist/@types/domains/file.d.ts +36 -3
  11. package/dist/@types/domains/file.d.ts.map +1 -1
  12. package/dist/@types/domains/follow.d.ts +11 -0
  13. package/dist/@types/domains/follow.d.ts.map +1 -1
  14. package/dist/@types/domains/group.d.ts +1 -0
  15. package/dist/@types/domains/group.d.ts.map +1 -1
  16. package/dist/@types/domains/message.d.ts +13 -0
  17. package/dist/@types/domains/message.d.ts.map +1 -1
  18. package/dist/@types/global.d.ts +1 -0
  19. package/dist/@types/global.d.ts.map +1 -1
  20. package/dist/@types/index.d.ts +2 -2
  21. package/dist/@types/index.d.ts.map +1 -1
  22. package/dist/channel/api/addChannelMembers.d.ts.map +1 -1
  23. package/dist/channel/api/addChannelMembersRole.d.ts.map +1 -1
  24. package/dist/channel/api/banChannelMembers.d.ts.map +1 -1
  25. package/dist/channel/api/createChannel.d.ts.map +1 -1
  26. package/dist/channel/api/getChannel.d.ts.map +1 -1
  27. package/dist/channel/api/getChannels.d.ts.map +1 -1
  28. package/dist/channel/api/joinChannel.d.ts.map +1 -1
  29. package/dist/channel/api/leaveChannel.d.ts.map +1 -1
  30. package/dist/channel/api/queryChannelMembers.d.ts.map +1 -1
  31. package/dist/channel/api/queryChannels.d.ts.map +1 -1
  32. package/dist/channel/api/removeChannelMembers.d.ts.map +1 -1
  33. package/dist/channel/api/removeChannelMembersRole.d.ts.map +1 -1
  34. package/dist/channel/api/unbanChannelMembers.d.ts.map +1 -1
  35. package/dist/channel/api/updateChannel.d.ts.map +1 -1
  36. package/dist/channel/events/index.d.ts +1 -0
  37. package/dist/channel/events/index.d.ts.map +1 -1
  38. package/dist/channel/events/onChannelCreated.d.ts.map +1 -1
  39. package/dist/channel/events/onChannelDeleted.d.ts.map +1 -1
  40. package/dist/channel/events/onChannelJoined.d.ts.map +1 -1
  41. package/dist/channel/events/onChannelLeft.d.ts.map +1 -1
  42. package/dist/channel/events/onChannelMemberAdded.d.ts.map +1 -1
  43. package/dist/channel/events/onChannelMemberRemoved.d.ts.map +1 -1
  44. package/dist/channel/events/onChannelUpdated.d.ts.map +1 -1
  45. package/dist/channel/observers/index.d.ts +1 -0
  46. package/dist/channel/observers/index.d.ts.map +1 -1
  47. package/dist/channel/observers/observeChannel.d.ts +1 -1
  48. package/dist/channel/observers/observeChannel.d.ts.map +1 -1
  49. package/dist/channel/observers/observeChannels.d.ts +17 -0
  50. package/dist/channel/observers/observeChannels.d.ts.map +1 -0
  51. package/dist/channel/tests/utils/prepareChannelPayload.test.d.ts +2 -0
  52. package/dist/channel/tests/utils/prepareChannelPayload.test.d.ts.map +1 -0
  53. package/dist/channel/utils/index.d.ts +2 -0
  54. package/dist/channel/utils/index.d.ts.map +1 -0
  55. package/dist/channel/utils/prepareChannelPayload.d.ts +3 -0
  56. package/dist/channel/utils/prepareChannelPayload.d.ts.map +1 -0
  57. package/dist/client/api/connectClient.d.ts +1 -8
  58. package/dist/client/api/connectClient.d.ts.map +1 -1
  59. package/dist/client/api/createClient.d.ts +8 -1
  60. package/dist/client/api/createClient.d.ts.map +1 -1
  61. package/dist/client/api/getFeedSettings.d.ts +16 -0
  62. package/dist/client/api/getFeedSettings.d.ts.map +1 -0
  63. package/dist/client/api/index.d.ts +1 -0
  64. package/dist/client/api/index.d.ts.map +1 -1
  65. package/dist/core/events.d.ts +3 -3
  66. package/dist/core/events.d.ts.map +1 -1
  67. package/dist/core/query/query.d.ts +1 -1
  68. package/dist/core/tests/query/query/runQuery.test.d.ts +2 -0
  69. package/dist/core/tests/query/query/runQuery.test.d.ts.map +1 -0
  70. package/dist/file/api/createVideo.d.ts +2 -1
  71. package/dist/file/api/createVideo.d.ts.map +1 -1
  72. package/dist/follow/api/queryFollowers.d.ts +1 -5
  73. package/dist/follow/api/queryFollowers.d.ts.map +1 -1
  74. package/dist/follow/api/queryFollowings.d.ts +1 -5
  75. package/dist/follow/api/queryFollowings.d.ts.map +1 -1
  76. package/dist/follow/observers/index.d.ts +2 -0
  77. package/dist/follow/observers/index.d.ts.map +1 -1
  78. package/dist/follow/observers/liveFollowers.d.ts +20 -0
  79. package/dist/follow/observers/liveFollowers.d.ts.map +1 -0
  80. package/dist/follow/observers/liveFollowings.d.ts +20 -0
  81. package/dist/follow/observers/liveFollowings.d.ts.map +1 -0
  82. package/dist/index.cjs.js +553 -111
  83. package/dist/index.d.ts +1 -1
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.esm.js +543 -112
  86. package/dist/index.umd.js +4 -4
  87. package/dist/message/api/queryMessages.d.ts +1 -10
  88. package/dist/message/api/queryMessages.d.ts.map +1 -1
  89. package/dist/message/observers/index.d.ts +1 -0
  90. package/dist/message/observers/index.d.ts.map +1 -1
  91. package/dist/message/observers/liveMessages.d.ts +20 -0
  92. package/dist/message/observers/liveMessages.d.ts.map +1 -0
  93. package/dist/message/observers/observeMessages.d.ts +0 -1
  94. package/dist/message/observers/observeMessages.d.ts.map +1 -1
  95. package/dist/message/observers/tests/liveMessages.test.d.ts +2 -0
  96. package/dist/message/observers/tests/liveMessages.test.d.ts.map +1 -0
  97. package/dist/post/observers/livePosts.d.ts.map +1 -1
  98. package/dist/utils/constants.d.ts +1 -0
  99. package/dist/utils/constants.d.ts.map +1 -1
  100. package/dist/utils/tests/client.d.ts +5 -2
  101. package/dist/utils/tests/client.d.ts.map +1 -1
  102. package/dist/utils/tests/dummy/channel.d.ts +10 -0
  103. package/dist/utils/tests/dummy/channel.d.ts.map +1 -0
  104. package/dist/utils/tests/dummy/index.d.ts +10 -0
  105. package/dist/utils/tests/dummy/index.d.ts.map +1 -0
  106. package/dist/utils/tests/dummy/message.d.ts +8 -0
  107. package/dist/utils/tests/dummy/message.d.ts.map +1 -0
  108. package/dist/utils/tests/{dummy.d.ts → dummy/post.d.ts} +3 -2
  109. package/dist/utils/tests/dummy/post.d.ts.map +1 -0
  110. package/dist/utils/tests/dummy/user.d.ts +2 -0
  111. package/dist/utils/tests/dummy/user.d.ts.map +1 -0
  112. package/dist/utils/tests/index.d.ts +2 -2
  113. package/dist/utils/tests/index.d.ts.map +1 -1
  114. package/package.json +1 -1
  115. package/src/@types/core/payload.ts +16 -10
  116. package/src/@types/domains/channel.ts +16 -1
  117. package/src/@types/domains/client.ts +17 -0
  118. package/src/@types/domains/content.ts +34 -3
  119. package/src/@types/domains/file.ts +42 -3
  120. package/src/@types/domains/follow.ts +28 -0
  121. package/src/@types/domains/group.ts +1 -0
  122. package/src/@types/domains/message.ts +20 -0
  123. package/src/@types/global.ts +2 -0
  124. package/src/@types/index.ts +3 -2
  125. package/src/channel/api/addChannelMembers.ts +6 -5
  126. package/src/channel/api/addChannelMembersRole.ts +5 -1
  127. package/src/channel/api/banChannelMembers.ts +7 -3
  128. package/src/channel/api/createChannel.ts +6 -2
  129. package/src/channel/api/getChannel.ts +5 -1
  130. package/src/channel/api/getChannels.ts +5 -1
  131. package/src/channel/api/joinChannel.ts +5 -1
  132. package/src/channel/api/leaveChannel.ts +5 -1
  133. package/src/channel/api/queryChannelMembers.ts +16 -12
  134. package/src/channel/api/queryChannels.ts +9 -4
  135. package/src/channel/api/removeChannelMembers.ts +6 -5
  136. package/src/channel/api/removeChannelMembersRole.ts +5 -1
  137. package/src/channel/api/unbanChannelMembers.ts +7 -3
  138. package/src/channel/api/updateChannel.ts +5 -1
  139. package/src/channel/events/index.ts +1 -0
  140. package/src/channel/events/onChannelCreated.ts +6 -2
  141. package/src/channel/events/onChannelDeleted.ts +6 -2
  142. package/src/channel/events/onChannelJoined.ts +6 -2
  143. package/src/channel/events/onChannelLeft.ts +6 -2
  144. package/src/channel/events/onChannelMemberAdded.ts +6 -2
  145. package/src/channel/events/onChannelMemberRemoved.ts +6 -2
  146. package/src/channel/events/onChannelUpdated.ts +6 -2
  147. package/src/channel/observers/index.ts +1 -0
  148. package/src/channel/observers/observeChannel.ts +1 -11
  149. package/src/channel/observers/observeChannels.ts +59 -0
  150. package/src/channel/tests/utils/prepareChannelPayload.test.ts +120 -0
  151. package/src/channel/utils/index.ts +1 -0
  152. package/src/channel/utils/prepareChannelPayload.ts +31 -0
  153. package/src/client/api/connectClient.ts +4 -9
  154. package/src/client/api/createClient.ts +19 -4
  155. package/src/client/api/getFeedSettings.ts +29 -0
  156. package/src/client/api/index.ts +2 -0
  157. package/src/core/events.ts +2 -1
  158. package/src/core/query/query.ts +3 -3
  159. package/src/core/tests/query/query/runQuery.test.ts +182 -0
  160. package/src/file/api/createVideo.ts +6 -0
  161. package/src/follow/api/queryFollowers.ts +3 -5
  162. package/src/follow/api/queryFollowings.ts +3 -5
  163. package/src/follow/api/utils.ts +7 -3
  164. package/src/follow/observers/index.ts +3 -0
  165. package/src/follow/observers/liveFollowers.ts +149 -0
  166. package/src/follow/observers/liveFollowings.ts +149 -0
  167. package/src/index.ts +1 -1
  168. package/src/message/api/queryMessages.ts +3 -10
  169. package/src/message/observers/index.ts +1 -0
  170. package/src/message/observers/liveMessages.ts +141 -0
  171. package/src/message/observers/observeMessages.ts +0 -1
  172. package/src/message/observers/tests/liveMessages.test.ts +133 -0
  173. package/src/post/observers/livePosts.ts +2 -1
  174. package/src/post/tests/api/getPost.test.ts +3 -3
  175. package/src/post/tests/api/queryPosts.test.ts +4 -4
  176. package/src/utils/constants.ts +1 -0
  177. package/src/utils/tests/client.ts +31 -3
  178. package/src/utils/tests/dummy/channel.ts +52 -0
  179. package/src/utils/tests/dummy/index.ts +7 -0
  180. package/src/utils/tests/dummy/message.ts +21 -0
  181. package/src/utils/tests/dummy/post.ts +31 -0
  182. package/src/utils/tests/dummy/user.ts +11 -0
  183. package/src/utils/tests/index.ts +2 -2
  184. package/dist/utils/tests/dummy.d.ts.map +0 -1
  185. package/src/utils/tests/dummy.ts +0 -7
package/dist/index.esm.js CHANGED
@@ -7,6 +7,38 @@ import HttpAgent, { HttpsAgent } from 'agentkeepalive';
7
7
  import io from 'socket.io-client';
8
8
  import nativeIdGenerator from 'react-native-uuid';
9
9
 
10
+ const ContentFeedType = Object.freeze({
11
+ STORY: 'story',
12
+ CHIP: 'clip',
13
+ CHAT: 'chat',
14
+ POST: 'post',
15
+ });
16
+
17
+ const FileType = Object.freeze({
18
+ FILE: 'file',
19
+ IMAGE: 'image',
20
+ VIDEO: 'video',
21
+ });
22
+ const VideoResolution = Object.freeze({
23
+ '1080P': '1080p',
24
+ '720P': '720p',
25
+ '480P': '480p',
26
+ '360P': '360p',
27
+ ORIGINAL: 'original',
28
+ });
29
+ const VideoTranscodingStatus = Object.freeze({
30
+ UPLOADED: 'uploaded',
31
+ TRANSCODING: 'transcoding',
32
+ TRANSCODED: 'transcoded',
33
+ TRANSCODE_FAILED: 'transcodeFailed',
34
+ });
35
+ const VideoSize = Object.freeze({
36
+ LOW: 'low',
37
+ MEDIUM: 'medium',
38
+ HIGH: 'high',
39
+ ORIGINAL: 'original',
40
+ });
41
+
10
42
  var _a$1;
11
43
  /* eslint-disable no-undef */
12
44
  const theGlobal =
@@ -354,7 +386,7 @@ const isFresh = (model, lifeSpan = 0) => {
354
386
  * This wrapper is necessary to create for optimistically calls
355
387
  *
356
388
  *
357
- * @param fn A compatible API function from the ts sdk
389
+ * @param func A compatible API function from the ts sdk
358
390
  * @param args The arguments to pass to the function passed as `fn`
359
391
  * @returns A wrapper containing both the function and its future arguments
360
392
  *
@@ -640,8 +672,9 @@ const WS_EVENTS = [
640
672
  'connect_error',
641
673
  'reconnect_error',
642
674
  'reconnect_failed',
675
+ 'v3.channel.didCreate',
643
676
  'v3.channel.didUpdate',
644
- 'v3.channel.didUpdate',
677
+ 'v3.channel.didDelete',
645
678
  'v3.channel.didJoin',
646
679
  'v3.channel.didLeave',
647
680
  'v3.channel.didAddUsers',
@@ -20141,6 +20174,29 @@ const createMqttTransport = (endpoint) => {
20141
20174
  };
20142
20175
  };
20143
20176
 
20177
+ /**
20178
+ * ```js
20179
+ * import { getFeedSettings } from '@amityco/ts-sdk'
20180
+ * const feedSettings = await getFeedSettings()
20181
+ * const postFeedSetting = feedSettings.post
20182
+ * ```
20183
+ *
20184
+ * Fetches a {@link Amity.FeedSettings} object
20185
+ *
20186
+ * @returns A Promise of {@link Amity.FeedSettings} object
20187
+ *
20188
+ * @category Client API
20189
+ * @async
20190
+ */
20191
+ const getFeedSettings = async () => {
20192
+ const client = getActiveClient();
20193
+ const { data } = await client.http.get(`/api/v3/network-settings/feed-setting`);
20194
+ return Object.fromEntries(data.feedSettings.map(({ feedType, contentSettings }) => {
20195
+ return [feedType, contentSettings];
20196
+ }));
20197
+ };
20198
+
20199
+ const DEFAULT_DEBUG_SESSION = 'amity';
20144
20200
  /**
20145
20201
  * ```js
20146
20202
  * import { createClient } from '@amityco/ts-sdk'
@@ -20151,20 +20207,24 @@ const createMqttTransport = (endpoint) => {
20151
20207
  *
20152
20208
  * @param apiKey for the {@link Amity.Client} instance
20153
20209
  * @param apiRegion endpoint to connect to
20210
+ * @param apiEndpoint custom endpoint in case you don't want to use a preset endpoint
20154
20211
  * @param debugSession session's identifier for the client's logger instance
20155
20212
  * @returns A {@link Amity.Client} instance
20156
20213
  *
20157
20214
  * @category Client API
20158
20215
  * */
20159
- const createClient = (apiKey, apiRegion = API_REGIONS.SG, debugSession = 'amity') => {
20216
+ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAULT_DEBUG_SESSION, apiEndpoint, } = {}) => {
20217
+ var _a, _b;
20160
20218
  const log = createLogger(debugSession);
20161
20219
  log('client/api/createClient', {
20162
20220
  apiKey: apiKey.replace(/.{5}$/g, 'xxxxx'),
20163
20221
  apiRegion,
20164
20222
  });
20165
- const http = createHttpTransport(computeUrl('http', apiRegion));
20166
- const ws = createWebsocketTransport(computeUrl('http', apiRegion));
20167
- const mqtt = createMqttTransport(computeUrl('mqtt', apiRegion));
20223
+ const httpEndpoint = (_a = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.http) !== null && _a !== void 0 ? _a : computeUrl('http', apiRegion);
20224
+ const mqttEndpoint = (_b = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.mqtt) !== null && _b !== void 0 ? _b : computeUrl('mqtt', apiRegion);
20225
+ const http = createHttpTransport(httpEndpoint);
20226
+ const ws = createWebsocketTransport(httpEndpoint);
20227
+ const mqtt = createMqttTransport(mqttEndpoint);
20168
20228
  const emitter = createEventEmitter();
20169
20229
  const client = {
20170
20230
  version: `${VERSION$1}`,
@@ -20175,11 +20235,12 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, debugSession = 'amity'
20175
20235
  mqtt,
20176
20236
  emitter,
20177
20237
  use: () => setActiveClient(client),
20238
+ getFeedSettings,
20178
20239
  };
20179
20240
  try {
20180
20241
  getActiveClient();
20181
20242
  }
20182
- catch (_a) {
20243
+ catch (_c) {
20183
20244
  setActiveClient(client);
20184
20245
  }
20185
20246
  return client;
@@ -20248,6 +20309,58 @@ const getDeviceInfo = () => {
20248
20309
  };
20249
20310
  };
20250
20311
 
20312
+ /**
20313
+ * Ingest a payload (v3) into the cache
20314
+ *
20315
+ * @param payload a "backend v3" payload object
20316
+ * @param order the order of the keys to process (in case of need)
20317
+ *
20318
+ * @category Cache
20319
+ * @hidden
20320
+ */
20321
+ const ingestInCache = (payload = {}, options) => {
20322
+ Object.entries(payload).forEach(([key, models]) => {
20323
+ const type = PAYLOAD2MODEL[key];
20324
+ if (!type)
20325
+ return;
20326
+ const resolver = getResolver(type);
20327
+ models.forEach(model => {
20328
+ upsertInCache(
20329
+ // eslint-disable @typescript-eslint no-explicit-any
20330
+ [type, 'get', resolver(model)], // this 'any' cannot be avoided, sorry.
20331
+ model, options);
20332
+ });
20333
+ });
20334
+ };
20335
+
20336
+ const createUserEventSubscriber = (event, callback) => {
20337
+ const client = getActiveClient();
20338
+ const filter = (payload) => {
20339
+ if (client.cache) {
20340
+ ingestInCache(payload);
20341
+ }
20342
+ callback(payload.users[0]);
20343
+ };
20344
+ return createEventSubscriber(client, event, event, filter);
20345
+ };
20346
+
20347
+ /**
20348
+ * ```js
20349
+ * import { onUserDeleted } from '@amityco/ts-sdk'
20350
+ * const dispose = onUserDeleted(user => {
20351
+ * // ...
20352
+ * })
20353
+ * ```
20354
+ *
20355
+ * Fired when a {@link Amity.User} has been deleted
20356
+ *
20357
+ * @param callback The function to call when the event was fired
20358
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
20359
+ *
20360
+ * @category User Events
20361
+ */
20362
+ const onUserDeleted = (callback) => createUserEventSubscriber('user.deleted', callback);
20363
+
20251
20364
  /**
20252
20365
  * Retrieves a pair of {@link Amity.Tokens} necessary for connection
20253
20366
  *
@@ -20348,58 +20461,6 @@ const onClientBanned = (callback) => {
20348
20461
  });
20349
20462
  };
20350
20463
 
20351
- /**
20352
- * Ingest a payload (v3) into the cache
20353
- *
20354
- * @param payload a "backend v3" payload object
20355
- * @param order the order of the keys to process (in case of need)
20356
- *
20357
- * @category Cache
20358
- * @hidden
20359
- */
20360
- const ingestInCache = (payload = {}, options) => {
20361
- Object.entries(payload).forEach(([key, models]) => {
20362
- const type = PAYLOAD2MODEL[key];
20363
- if (!type)
20364
- return;
20365
- const resolver = getResolver(type);
20366
- models.forEach(model => {
20367
- upsertInCache(
20368
- // eslint-disable @typescript-eslint no-explicit-any
20369
- [type, 'get', resolver(model)], // this 'any' cannot be avoided, sorry.
20370
- model, options);
20371
- });
20372
- });
20373
- };
20374
-
20375
- const createUserEventSubscriber = (event, callback) => {
20376
- const client = getActiveClient();
20377
- const filter = (payload) => {
20378
- if (client.cache) {
20379
- ingestInCache(payload);
20380
- }
20381
- callback(payload.users[0]);
20382
- };
20383
- return createEventSubscriber(client, event, event, filter);
20384
- };
20385
-
20386
- /**
20387
- * ```js
20388
- * import { onUserDeleted } from '@amityco/ts-sdk'
20389
- * const dispose = onUserDeleted(user => {
20390
- * // ...
20391
- * })
20392
- * ```
20393
- *
20394
- * Fired when a {@link Amity.User} has been deleted
20395
- *
20396
- * @param callback The function to call when the event was fired
20397
- * @returns an {@link Amity.Unsubscriber} function to stop listening
20398
- *
20399
- * @category User Events
20400
- */
20401
- const onUserDeleted = (callback) => createUserEventSubscriber('user.deleted', callback);
20402
-
20403
20464
  /* eslint-disable no-param-reassign */
20404
20465
  /**
20405
20466
  * ```js
@@ -20967,17 +21028,21 @@ const fileUrlWithSize = (fileUrl, size) => {
20967
21028
  * Creates an {@link Amity.File<'video'>}
20968
21029
  *
20969
21030
  * @param formData The data necessary to create a new {@link Amity.File<'video'>}
21031
+ * @param feedType The {@link Amity.File<'video'>} feed type
20970
21032
  * @param onProgress The callback to track the upload progress
20971
21033
  * @returns The newly created {@link Amity.File<'video'>}
20972
21034
  *
20973
21035
  * @category File API
20974
21036
  * @async
20975
21037
  */
20976
- const createVideo = async (formData, onProgress) => {
21038
+ const createVideo = async (formData, feedType, onProgress) => {
20977
21039
  const client = getActiveClient();
20978
21040
  client.log('file/createVideo', formData);
20979
21041
  if (!formData.getAll('files').length)
20980
21042
  throw new Error('The formData object must have a `files` key.');
21043
+ if (feedType) {
21044
+ formData.append('feedType', feedType);
21045
+ }
20981
21046
  const headers = 'getHeaders' in formData
20982
21047
  ? formData.getHeaders()
20983
21048
  : { 'content-type': 'multipart/form-data' };
@@ -23751,7 +23816,8 @@ const onReactorRemoved = (referenceType, referenceId, callback) => {
23751
23816
  };
23752
23817
 
23753
23818
  const COLLECTION_DEFAULT_PAGINATION_LIMIT = 5;
23754
- const COLLECTION_DEFAULT_CACHING_POLICY = 'cache_then_server';
23819
+ const COLLECTION_DEFAULT_CACHING_POLICY = 'cache_then_server';
23820
+ const ENABLE_CACHE_MESSAGE = 'For using Live Collection feature you need to enable Cache!';
23755
23821
 
23756
23822
  /**
23757
23823
  * ```js
@@ -23953,6 +24019,23 @@ const isReportedByMe = async (referenceType, referenceId) => {
23953
24019
  return (_b = result !== null && result !== void 0 ? result : isFlagByMe) !== null && _b !== void 0 ? _b : false;
23954
24020
  };
23955
24021
 
24022
+ /** @hidden */
24023
+ const prepareChannelPayload = (payload) => {
24024
+ const client = getActiveClient();
24025
+ const channels = payload.channels.map(channel => {
24026
+ const channelUser = payload.channelUsers.find(channelUser => channelUser.userId === client.userId && channel.channelId === channelUser.channelId);
24027
+ const hasMention = channelUser
24028
+ ? channelUser.readToSegment < channelUser.lastMentionedSegment
24029
+ : false;
24030
+ const unreadCount = channelUser && channelUser.membership === 'member' && channel.messageCount
24031
+ ? Math.max(0, channel.messageCount - channelUser.readToSegment)
24032
+ : 0;
24033
+ return Object.assign(Object.assign({}, channel), { hasMention,
24034
+ unreadCount });
24035
+ });
24036
+ return Object.assign(Object.assign({}, payload), { channels });
24037
+ };
24038
+
23956
24039
  /**
23957
24040
  * ```js
23958
24041
  * import { queryChannels } from '@amityco/ts-sdk'
@@ -23976,16 +24059,17 @@ const queryChannels = async (query) => {
23976
24059
  // API-FIX: parameters should be querystring.
23977
24060
  // API-FIX: backend doesnt answer Amity.Response
23978
24061
  // const { data } = await client.http.get<Amity.Response<Amity.Paged<ChannelPayload>>>(
23979
- const { data } = await client.http.get(`/api/v3/channels`, {
24062
+ const { data: queryPayload } = await client.http.get(`/api/v3/channels`, {
23980
24063
  params: Object.assign(Object.assign({}, params), { keyword: displayName, filter: membership, options: {
23981
24064
  token: toToken(page, 'skiplimit'),
23982
24065
  } }),
23983
24066
  });
23984
- const { paging } = data, payload = __rest(data, ["paging"]);
23985
- const { channels } = payload;
24067
+ const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
24068
+ const data = prepareChannelPayload(payload);
24069
+ const { channels } = data;
23986
24070
  const cachedAt = client.cache && Date.now();
23987
24071
  if (client.cache) {
23988
- ingestInCache(payload, { cachedAt });
24072
+ ingestInCache(data, { cachedAt });
23989
24073
  const cacheKey = [
23990
24074
  'channel',
23991
24075
  'query',
@@ -24035,9 +24119,10 @@ const getChannels = async (channelIds) => {
24035
24119
  client.log('channel/getChannels', channelIds);
24036
24120
  const encodedChannelIds = channelIds.map(channelId => encodeURIComponent(channelId));
24037
24121
  // API-FIX: endpoint should not be /list, parameters should be querystring.
24038
- const { data } = await client.http.get(`/api/v3/channels/list`, {
24122
+ const { data: payload } = await client.http.get(`/api/v3/channels/list`, {
24039
24123
  params: { channelIds: encodedChannelIds },
24040
24124
  });
24125
+ const data = prepareChannelPayload(payload);
24041
24126
  const cachedAt = client.cache && Date.now();
24042
24127
  if (client.cache)
24043
24128
  ingestInCache(data, { cachedAt });
@@ -24096,7 +24181,8 @@ const getChannel = async (channelId) => {
24096
24181
  const client = getActiveClient();
24097
24182
  client.log('channel/getChannel', channelId);
24098
24183
  // API-FIX: endpoint should not be /list, parameters should be querystring.
24099
- const { data } = await client.http.get(`/api/v3/channels/${encodeURIComponent(channelId)}`);
24184
+ const { data: payload } = await client.http.get(`/api/v3/channels/${encodeURIComponent(channelId)}`);
24185
+ const data = prepareChannelPayload(payload);
24100
24186
  const cachedAt = client.cache && Date.now();
24101
24187
  if (client.cache)
24102
24188
  ingestInCache(data, { cachedAt });
@@ -24157,10 +24243,11 @@ const createChannel = async (bundle) => {
24157
24243
  else {
24158
24244
  payload = await client.http.post('/api/v3/channels', bundle);
24159
24245
  }
24246
+ const data = prepareChannelPayload(payload.data);
24160
24247
  const cachedAt = client.cache && Date.now();
24161
24248
  if (client.cache)
24162
- ingestInCache(payload.data, { cachedAt });
24163
- const { channels } = payload.data;
24249
+ ingestInCache(data, { cachedAt });
24250
+ const { channels } = data;
24164
24251
  return {
24165
24252
  data: channels[0],
24166
24253
  cachedAt,
@@ -24185,7 +24272,8 @@ const createChannel = async (bundle) => {
24185
24272
  const updateChannel = async (channelId, patch) => {
24186
24273
  const client = getActiveClient();
24187
24274
  client.log('channel/updateChannel', channelId, patch);
24188
- const { data } = await client.http.put(`/api/v3/channels/${encodeURIComponent(channelId)}`, patch);
24275
+ const { data: payload } = await client.http.put(`/api/v3/channels/${encodeURIComponent(channelId)}`, patch);
24276
+ const data = prepareChannelPayload(payload);
24189
24277
  const cachedAt = client.cache && Date.now();
24190
24278
  if (client.cache)
24191
24279
  ingestInCache(data, { cachedAt });
@@ -24236,7 +24324,8 @@ const deleteChannel = async (channelId) => {
24236
24324
  const joinChannel = async (channelId) => {
24237
24325
  const client = getActiveClient();
24238
24326
  client.log('channel/joinChannel', channelId);
24239
- const { data } = await client.http.post(`/api/v3/channels/${encodeURIComponent(channelId)}/join`);
24327
+ const { data: payload } = await client.http.post(`/api/v3/channels/${encodeURIComponent(channelId)}/join`);
24328
+ const data = prepareChannelPayload(payload);
24240
24329
  if (client.cache)
24241
24330
  ingestInCache(data);
24242
24331
  const { channelUsers } = data;
@@ -24260,7 +24349,8 @@ const joinChannel = async (channelId) => {
24260
24349
  const leaveChannel = async (channelId) => {
24261
24350
  const client = getActiveClient();
24262
24351
  client.log('channel/leaveChannel', channelId);
24263
- const { data } = await client.http.delete(`/api/v3/channels/${encodeURIComponent(channelId)}/leave`);
24352
+ const { data: payload } = await client.http.delete(`/api/v3/channels/${encodeURIComponent(channelId)}/leave`);
24353
+ const data = prepareChannelPayload(payload);
24264
24354
  if (client.cache)
24265
24355
  ingestInCache(data);
24266
24356
  const { channelUsers } = data;
@@ -24285,16 +24375,17 @@ const queryChannelMembers = async (query) => {
24285
24375
  const client = getActiveClient();
24286
24376
  client.log('channel/queryChannelMembers', query);
24287
24377
  const _a = query !== null && query !== void 0 ? query : {}, { page, channelId } = _a, params = __rest(_a, ["page", "channelId"]);
24288
- const { data } = await client.http.get(`/api/v4/channels/${encodeURIComponent(channelId)}/users`, {
24378
+ const { data: queryPayload } = await client.http.get(`/api/v4/channels/${encodeURIComponent(channelId)}/users`, {
24289
24379
  params: Object.assign(Object.assign({}, params), { options: {
24290
24380
  token: toToken(page, 'skiplimit'),
24291
24381
  } }),
24292
24382
  });
24293
- const { paging } = data, payload = __rest(data, ["paging"]);
24294
- const { channelUsers } = payload;
24383
+ const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
24384
+ const data = prepareChannelPayload(payload);
24385
+ const { channelUsers } = data;
24295
24386
  const cachedAt = client.cache && Date.now();
24296
24387
  if (client.cache) {
24297
- ingestInCache(payload);
24388
+ ingestInCache(data);
24298
24389
  }
24299
24390
  const nextPage = toPage(paging.next);
24300
24391
  const prevPage = toPage(paging.previous);
@@ -24337,13 +24428,11 @@ queryChannelMembers.locally = (query) => {
24337
24428
  const addChannelMembers = async (channelId, userIds) => {
24338
24429
  const client = getActiveClient();
24339
24430
  client.log('channel/addChannelMembers', channelId, userIds);
24340
- const { data } = await client.http.post(`/api/v3/channels/${encodeURIComponent(channelId)}/users`, { channelId, userIds });
24431
+ const { data: payload } = await client.http.post(`/api/v3/channels/${encodeURIComponent(channelId)}/users`, { channelId, userIds });
24432
+ const data = prepareChannelPayload(payload);
24341
24433
  if (client.cache)
24342
24434
  ingestInCache(data);
24343
- fireEvent('v3.channel.didAddUsers', {
24344
- channels: data.channels,
24345
- channelUsers: data.channelUsers,
24346
- });
24435
+ fireEvent('v3.channel.didAddUsers', data);
24347
24436
  const { channelUsers } = data;
24348
24437
  return !!channelUsers.find(channelUser => channelUser.channelId === channelId && channelUser.membership === 'member');
24349
24438
  };
@@ -24366,13 +24455,11 @@ const addChannelMembers = async (channelId, userIds) => {
24366
24455
  const removeChannelMembers = async (channelId, userIds) => {
24367
24456
  const client = getActiveClient();
24368
24457
  client.log('channel/removeChannelMembers', channelId, userIds);
24369
- const { data } = await client.http.delete(`/api/v3/channels/${encodeURIComponent(channelId)}/users`, { data: { channelId, userIds } });
24458
+ const { data: payload } = await client.http.delete(`/api/v3/channels/${encodeURIComponent(channelId)}/users`, { data: { channelId, userIds } });
24459
+ const data = prepareChannelPayload(payload);
24370
24460
  if (client.cache)
24371
24461
  ingestInCache(data);
24372
- fireEvent('v3.channel.didRemoveUsers', {
24373
- channels: data.channels,
24374
- channelUsers: data.channelUsers,
24375
- });
24462
+ fireEvent('v3.channel.didRemoveUsers', data);
24376
24463
  const { channelUsers } = data;
24377
24464
  return !!channelUsers.find(channelUser => channelUser.channelId === channelId && channelUser.membership !== 'member');
24378
24465
  };
@@ -24396,7 +24483,8 @@ const removeChannelMembers = async (channelId, userIds) => {
24396
24483
  const addChannelMembersRole = async (channelId, roleId, userIds) => {
24397
24484
  const client = getActiveClient();
24398
24485
  client.log('channel/addChannelMembersRole', channelId, roleId, userIds);
24399
- const { data } = await client.http.post(`/api/v3/channels/${encodeURIComponent(channelId)}/users/roles`, { channelId, role: roleId, userIds });
24486
+ const { data: payload } = await client.http.post(`/api/v3/channels/${encodeURIComponent(channelId)}/users/roles`, { channelId, role: roleId, userIds });
24487
+ const data = prepareChannelPayload(payload);
24400
24488
  if (client.cache)
24401
24489
  ingestInCache(data);
24402
24490
  const { channelUsers } = data;
@@ -24422,7 +24510,8 @@ const addChannelMembersRole = async (channelId, roleId, userIds) => {
24422
24510
  const removeChannelMembersRole = async (channelId, roleId, userIds) => {
24423
24511
  const client = getActiveClient();
24424
24512
  client.log('channel/removeChannelMembersRole', channelId, roleId, userIds);
24425
- const { data } = await client.http.delete(`/api/v3/channels/${encodeURIComponent(channelId)}/users/roles`, { data: { channelId, role: roleId, userIds } });
24513
+ const { data: payload } = await client.http.delete(`/api/v3/channels/${encodeURIComponent(channelId)}/users/roles`, { data: { channelId, role: roleId, userIds } });
24514
+ const data = prepareChannelPayload(payload);
24426
24515
  if (client.cache)
24427
24516
  ingestInCache(data);
24428
24517
  const { channelUsers } = data;
@@ -24446,13 +24535,14 @@ const removeChannelMembersRole = async (channelId, roleId, userIds) => {
24446
24535
  const banChannelMembers = async (channelId, userIds) => {
24447
24536
  const client = getActiveClient();
24448
24537
  client.log('channel/banChannelMembers', { userIds, channelId });
24449
- const payload = await client.http.put(`/api/v3/channels/${channelId}/users/ban`, {
24538
+ const { data: payload } = await client.http.put(`/api/v3/channels/${channelId}/users/ban`, {
24450
24539
  userIds,
24451
24540
  });
24541
+ const data = prepareChannelPayload(payload);
24452
24542
  const cachedAt = client.cache && Date.now();
24453
24543
  if (client.cache)
24454
- ingestInCache(payload.data, { cachedAt });
24455
- const { channelUsers } = payload.data;
24544
+ ingestInCache(data, { cachedAt });
24545
+ const { channelUsers } = data;
24456
24546
  return {
24457
24547
  data: channelUsers === null || channelUsers === void 0 ? void 0 : channelUsers.filter(user => user.membership === 'banned'),
24458
24548
  cachedAt,
@@ -24476,19 +24566,45 @@ const banChannelMembers = async (channelId, userIds) => {
24476
24566
  const unbanChannelMembers = async (channelId, userIds) => {
24477
24567
  const client = getActiveClient();
24478
24568
  client.log('channel/unbanChannelMembers', { userIds, channelId });
24479
- const payload = await client.http.put(`/api/v3/channels/${encodeURIComponent(channelId)}/users/unban`, {
24569
+ const { data: payload } = await client.http.put(`/api/v3/channels/${encodeURIComponent(channelId)}/users/unban`, {
24480
24570
  userIds,
24481
24571
  });
24572
+ const data = prepareChannelPayload(payload);
24482
24573
  const cachedAt = client.cache && Date.now();
24483
24574
  if (client.cache)
24484
- ingestInCache(payload.data, { cachedAt });
24485
- const { channelUsers } = payload.data;
24575
+ ingestInCache(data, { cachedAt });
24576
+ const { channelUsers } = data;
24486
24577
  return {
24487
24578
  data: channelUsers === null || channelUsers === void 0 ? void 0 : channelUsers.filter(user => user.membership === 'member'),
24488
24579
  cachedAt,
24489
24580
  };
24490
24581
  };
24491
24582
 
24583
+ /**
24584
+ * ```js
24585
+ * import { onChannelCreated } from '@amityco/ts-sdk'
24586
+ * const dispose = onChannelCreated(channel => {
24587
+ * // ...
24588
+ * })
24589
+ * ```
24590
+ *
24591
+ * Fired when any {@link Amity.Channel} have been created
24592
+ *
24593
+ * @param callback The function to call when the event was fired
24594
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
24595
+ *
24596
+ * @category Channel Events
24597
+ */
24598
+ const onChannelCreated = (callback) => {
24599
+ const client = getActiveClient();
24600
+ const filter = (payload) => {
24601
+ const data = prepareChannelPayload(payload);
24602
+ ingestInCache(data);
24603
+ callback(data.channels[0]);
24604
+ };
24605
+ return createEventSubscriber(client, 'onChannelCreated', 'v3.channel.didCreate', filter);
24606
+ };
24607
+
24492
24608
  /**
24493
24609
  * ```js
24494
24610
  * import { onChannelUpdated } from '@amityco/ts-sdk'
@@ -24507,8 +24623,9 @@ const unbanChannelMembers = async (channelId, userIds) => {
24507
24623
  const onChannelUpdated = (callback) => {
24508
24624
  const client = getActiveClient();
24509
24625
  const filter = (payload) => {
24510
- ingestInCache(payload);
24511
- callback(payload.channels[0]);
24626
+ const data = prepareChannelPayload(payload);
24627
+ ingestInCache(data);
24628
+ callback(data.channels[0]);
24512
24629
  };
24513
24630
  return createEventSubscriber(client, 'onChannelUpdated', 'v3.channel.didUpdate', filter);
24514
24631
  };
@@ -24531,8 +24648,9 @@ const onChannelUpdated = (callback) => {
24531
24648
  const onChannelDeleted = (callback) => {
24532
24649
  const client = getActiveClient();
24533
24650
  const filter = (payload) => {
24534
- ingestInCache(payload);
24535
- callback(payload.channels[0]);
24651
+ const data = prepareChannelPayload(payload);
24652
+ ingestInCache(data);
24653
+ callback(data.channels[0]);
24536
24654
  };
24537
24655
  return createEventSubscriber(client, 'onChannelDeleted', 'v3.channel.didDelete', filter);
24538
24656
  };
@@ -24555,8 +24673,9 @@ const onChannelDeleted = (callback) => {
24555
24673
  const onChannelJoined = (callback) => {
24556
24674
  const client = getActiveClient();
24557
24675
  const filter = (payload) => {
24558
- ingestInCache(payload);
24559
- callback(payload.channels[0]);
24676
+ const data = prepareChannelPayload(payload);
24677
+ ingestInCache(data);
24678
+ callback(data.channels[0]);
24560
24679
  };
24561
24680
  return createEventSubscriber(client, 'onChannelJoined', 'v3.channel.didJoin', filter);
24562
24681
  };
@@ -24579,8 +24698,9 @@ const onChannelJoined = (callback) => {
24579
24698
  const onChannelLeft = (callback) => {
24580
24699
  const client = getActiveClient();
24581
24700
  const filter = (payload) => {
24582
- ingestInCache(payload);
24583
- callback(payload.channels[0]);
24701
+ const data = prepareChannelPayload(payload);
24702
+ ingestInCache(data);
24703
+ callback(data.channels[0]);
24584
24704
  };
24585
24705
  return createEventSubscriber(client, 'onChannelLeft', 'v3.channel.didLeave', filter);
24586
24706
  };
@@ -24603,8 +24723,9 @@ const onChannelLeft = (callback) => {
24603
24723
  const onChannelMemberAdded = (callback) => {
24604
24724
  const client = getActiveClient();
24605
24725
  const filter = (payload) => {
24606
- ingestInCache(payload);
24607
- callback(payload.channels[0], payload.channelUsers[0]);
24726
+ const data = prepareChannelPayload(payload);
24727
+ ingestInCache(data);
24728
+ callback(data.channels[0], data.channelUsers[0]);
24608
24729
  };
24609
24730
  return createEventSubscriber(client, 'onChannelMemberAdded', 'v3.channel.didAddUsers', filter);
24610
24731
  };
@@ -24627,8 +24748,9 @@ const onChannelMemberAdded = (callback) => {
24627
24748
  const onChannelMemberRemoved = (callback) => {
24628
24749
  const client = getActiveClient();
24629
24750
  const filter = (payload) => {
24630
- ingestInCache(payload);
24631
- callback(payload.channels[0], payload.channelUsers[0]);
24751
+ const data = prepareChannelPayload(payload);
24752
+ ingestInCache(data);
24753
+ callback(data.channels[0], data.channelUsers[0]);
24632
24754
  };
24633
24755
  return createEventSubscriber(client, 'onChannelMemberRemoved', 'v3.channel.didRemoveUsers', filter);
24634
24756
  };
@@ -24674,6 +24796,40 @@ const observeChannel = (channelId, callback) => {
24674
24796
  };
24675
24797
  };
24676
24798
 
24799
+ /**
24800
+ * ```js
24801
+ * import { observeChannels } from '@amityco/ts-sdk'
24802
+ *
24803
+ * let channels = []
24804
+ * const unsub = observeChannels(channel => merge(channels, channel))
24805
+ * ```
24806
+ *
24807
+ * Observe all mutations on a list of {@link Amity.Channel} for a current user
24808
+ *
24809
+ * @param callback the function to call when new data are available
24810
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the channels
24811
+ *
24812
+ * @category Channel Observer
24813
+ */
24814
+ const observeChannels = (callback) => {
24815
+ const { log } = getActiveClient();
24816
+ const timestamp = Date.now();
24817
+ log(`observeChannels(tmpid: ${timestamp}) > listen`);
24818
+ const disposers = [];
24819
+ const router = (channel, action) => {
24820
+ var _a, _b;
24821
+ if (callback instanceof Function)
24822
+ return callback(channel);
24823
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, channel);
24824
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, channel);
24825
+ };
24826
+ disposers.push(onChannelCreated(data => router(data, 'onCreate')), onChannelUpdated(data => router(data, 'onUpdate')), onChannelDeleted(data => router(data, 'onDelete')), onChannelJoined(data => router(data, 'onJoin')), onChannelLeft(data => router(data, 'onLeft')), onChannelMemberAdded(data => router(data, 'onMemberAdded')), onChannelMemberRemoved(data => router(data, 'onMemberRemoved')));
24827
+ return () => {
24828
+ log(`observeChannels(tmpid: ${timestamp}) > dispose`);
24829
+ disposers.forEach(fn => fn());
24830
+ };
24831
+ };
24832
+
24677
24833
  /**
24678
24834
  * ```js
24679
24835
  * import { onMessageCreated } from '@amityco/ts-sdk'
@@ -24806,7 +24962,6 @@ const observeMessage = (messageId, callback, policy = 'cache_then_server') => {
24806
24962
  *
24807
24963
  * Observe all mutations on a list of {@link Amity.Message} for a given {@link Amity.Channel} object
24808
24964
  *
24809
- * @param client the client to observe the message with
24810
24965
  * @param channelId the ID of the channel where to observe the messages
24811
24966
  * @param callback the function to call when new data are available
24812
24967
  * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
@@ -24834,6 +24989,98 @@ const observeMessages = (channelId, callback) => {
24834
24989
  };
24835
24990
  };
24836
24991
 
24992
+ /**
24993
+ * ```js
24994
+ * import { liveMessages } from '@amityco/ts-sdk'
24995
+ *
24996
+ * let messages = []
24997
+ * const unsub = liveMessages({
24998
+ * channelId: Amity.Channel['channelId'];
24999
+ * }, response => merge(messages, response.data))
25000
+ * ```
25001
+ *
25002
+ * Observe all mutations on a list of {@link Amity.Message} for a given target object
25003
+ *
25004
+ * @param params for querying memssages from a channel
25005
+ * @param callback the function to call when new data are available
25006
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
25007
+ *
25008
+ * @category Messages Live Collection
25009
+ */
25010
+ const liveMessages = (params, callback, config) => {
25011
+ const { log, cache } = getActiveClient();
25012
+ if (!cache) {
25013
+ console.log(ENABLE_CACHE_MESSAGE);
25014
+ }
25015
+ const timestamp = Date.now();
25016
+ log(`liveMessages(tmpid: ${timestamp}) > listen`);
25017
+ const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
25018
+ const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
25019
+ const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
25020
+ const disposers = [];
25021
+ const cacheKey = ['message', 'collection', { channelId: params.channelId }];
25022
+ const responder = (data) => {
25023
+ var _a, _b;
25024
+ let messages = (_a = data.data
25025
+ .map(messageId => pullFromCache(['message', 'get', messageId]))
25026
+ .filter(Boolean)
25027
+ .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
25028
+ /*
25029
+ * for cases when message is deleted via RTE, this flag is used to get
25030
+ * items fro cache that are deleted | !deleted
25031
+ */
25032
+ messages = filterByPropEquality(messages, 'isDeleted', params.isDeleted);
25033
+ callback({
25034
+ onNextPage: onFetch,
25035
+ data: messages,
25036
+ hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
25037
+ loading: data.loading,
25038
+ error: data.error,
25039
+ });
25040
+ };
25041
+ const realtimeRouter = (message, action) => {
25042
+ var _a;
25043
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25044
+ if (params.channelId !== message.channelId || !collection)
25045
+ return;
25046
+ if (action === 'onCreate') {
25047
+ collection.data = [...new Set([message.messageId, ...collection.data])];
25048
+ }
25049
+ else if (['onDelete'].includes(action)) {
25050
+ collection.data = collection.data.filter(m => m !== message.messageId);
25051
+ }
25052
+ pushToCache(cacheKey, collection);
25053
+ responder(collection);
25054
+ };
25055
+ const onFetch = () => {
25056
+ var _a, _b, _c, _d, _e;
25057
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25058
+ const messages = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
25059
+ if (messages.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
25060
+ return;
25061
+ const query = createQuery(queryMessages, Object.assign(Object.assign({}, queryParams), { page: (_e = (_d = collection === null || collection === void 0 ? void 0 : collection.params) === null || _d === void 0 ? void 0 : _d.page) !== null && _e !== void 0 ? _e : { limit } }));
25062
+ runQuery(query, ({ data: result, error, loading, prevPage: page }) => {
25063
+ const data = {
25064
+ loading,
25065
+ error,
25066
+ params: { page },
25067
+ data: messages,
25068
+ };
25069
+ if (result) {
25070
+ data.data = [...new Set([...messages, ...result.map(getResolver('message'))])];
25071
+ }
25072
+ pushToCache(cacheKey, data);
25073
+ responder(data);
25074
+ }, queryOptions(policy));
25075
+ };
25076
+ disposers.push(onMessageCreated(message => realtimeRouter(message, 'onCreate')), onMessageDeleted(message => realtimeRouter(message, 'onDelete')), onMessageUpdated(message => realtimeRouter(message, 'onUpdate')));
25077
+ onFetch();
25078
+ return () => {
25079
+ log(`liveMessages(tmpid: ${timestamp}) > dispose`);
25080
+ disposers.forEach(fn => fn());
25081
+ };
25082
+ };
25083
+
24837
25084
  const createCommunityEventSubscriber = (event, callback) => {
24838
25085
  const client = getActiveClient();
24839
25086
  const filter = (payload) => {
@@ -25321,9 +25568,9 @@ const queryFollows = async (key, query) => {
25321
25568
  if (client.cache) {
25322
25569
  ingestInCache(payload, { cachedAt });
25323
25570
  const cacheKey = [
25324
- key,
25571
+ 'follow',
25325
25572
  'query',
25326
- Object.assign(Object.assign({}, params), { userId, options: Object.assign({}, page) }),
25573
+ Object.assign(Object.assign({}, params), { userId, options: Object.assign({}, page), type: key }),
25327
25574
  ];
25328
25575
  pushToCache(cacheKey, { follows: follows.map(getResolver('follow')), paging });
25329
25576
  }
@@ -25338,7 +25585,11 @@ queryFollows.locally = (key, query) => {
25338
25585
  if (!client.cache)
25339
25586
  return;
25340
25587
  const { page } = query, params = __rest(query, ["page"]);
25341
- const queryKey = [key, 'query', Object.assign(Object.assign({}, params), { options: Object.assign({}, page) })];
25588
+ const queryKey = [
25589
+ 'follow',
25590
+ 'query',
25591
+ Object.assign(Object.assign({}, params), { options: Object.assign({}, page), type: key }),
25592
+ ];
25342
25593
  const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
25343
25594
  if (!(data === null || data === void 0 ? void 0 : data.follows.length)) {
25344
25595
  return;
@@ -25884,6 +26135,186 @@ const observeFollowings = (userId, callback) => {
25884
26135
  };
25885
26136
  };
25886
26137
 
26138
+ /**
26139
+ * ```js
26140
+ * import { liveFollowers } from '@amityco/ts-sdk'
26141
+ *
26142
+ * let followers = []
26143
+ * const unsub = liveFollowers({
26144
+ * userId: Amity.User['userId'];
26145
+ * }, response => merge(followers, response.data))
26146
+ * ```
26147
+ *
26148
+ * Observe all mutations on a list of {@link Amity.FollowStatus} followers for a given userId
26149
+ *
26150
+ * @param userId the user
26151
+ * @param callback the function to call when new data are available
26152
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
26153
+ *
26154
+ * @category Followers Live Collection
26155
+ */
26156
+ const liveFollowers = (params, callback, config) => {
26157
+ const { log, cache } = getActiveClient();
26158
+ if (!cache) {
26159
+ console.log('For using Live Collection feature you need to enable Cache!');
26160
+ }
26161
+ const timestamp = Date.now();
26162
+ log(`liveFollowers(tmpid: ${timestamp}) > listen`);
26163
+ const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
26164
+ const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
26165
+ const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
26166
+ const disposers = [];
26167
+ const cacheKey = ['follow', 'collection', { userId: params.userId, type: 'follower' }];
26168
+ const responder = (data) => {
26169
+ var _a, _b;
26170
+ let followers = (_a = data.data
26171
+ .map(key => pullFromCache(['follow', 'get', key]))
26172
+ .filter(Boolean)
26173
+ .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
26174
+ if (params.status) {
26175
+ followers = filterByPropEquality(followers, 'status', params.status);
26176
+ }
26177
+ callback({
26178
+ onNextPage: onFetch,
26179
+ data: followers,
26180
+ hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
26181
+ loading: data.loading,
26182
+ error: data.error,
26183
+ });
26184
+ };
26185
+ const realtimeRouter = (followStatus, action) => {
26186
+ var _a;
26187
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26188
+ if (params.userId !== followStatus.to || !collection)
26189
+ return;
26190
+ if (['onDeclined', 'onCanceled', 'onUnfollowed', 'onDeleted'].includes(action)) {
26191
+ collection.data = collection.data.filter(p => p !== getResolver('follow')(followStatus));
26192
+ }
26193
+ else if (['onRequested', 'onAccepted', 'onFollowed'].includes(action)) {
26194
+ collection.data = [...new Set([getResolver('follow')(followStatus), ...collection.data])];
26195
+ }
26196
+ pushToCache(cacheKey, collection);
26197
+ responder(collection);
26198
+ };
26199
+ const onFetch = () => {
26200
+ var _a, _b, _c, _d, _e;
26201
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26202
+ const followers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
26203
+ if (followers.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
26204
+ return;
26205
+ const query = createQuery(queryFollowers, Object.assign(Object.assign({}, queryParams), { page: (_e = (_d = collection === null || collection === void 0 ? void 0 : collection.params) === null || _d === void 0 ? void 0 : _d.page) !== null && _e !== void 0 ? _e : { limit } }));
26206
+ runQuery(query, ({ data: result, error, loading, nextPage: page }) => {
26207
+ const data = {
26208
+ loading,
26209
+ error,
26210
+ params: { page },
26211
+ data: followers,
26212
+ };
26213
+ if (result) {
26214
+ data.data = [...new Set([...followers, ...result.map(getResolver('follow'))])];
26215
+ }
26216
+ pushToCache(cacheKey, data);
26217
+ responder(data);
26218
+ }, queryOptions(policy));
26219
+ };
26220
+ disposers.push(onFollowerRequested(followStatus => realtimeRouter(followStatus, 'onRequested')), onFollowRequestAccepted(followStatus => realtimeRouter(followStatus, 'onAccepted')), onFollowRequestDeclined(followStatus => realtimeRouter(followStatus, 'onDeclined')), onFollowRequestCanceled(followStatus => realtimeRouter(followStatus, 'onCanceled')), onUserFollowed(followStatus => realtimeRouter(followStatus, 'onFollowed')), onUserUnfollowed(followStatus => realtimeRouter(followStatus, 'onUnfollowed')), onFollowerDeleted(followStatus => realtimeRouter(followStatus, 'onDeleted')));
26221
+ onFetch();
26222
+ return () => {
26223
+ log(`liveFollowers(tmpid: ${timestamp}) > dispose`);
26224
+ disposers.forEach(fn => fn());
26225
+ };
26226
+ };
26227
+
26228
+ /**
26229
+ * ```js
26230
+ * import { liveFollowings } from '@amityco/ts-sdk'
26231
+ *
26232
+ * let followings = []
26233
+ * const unsub = liveFollowings({
26234
+ * userId: Amity.User['userId'];
26235
+ * }, response => merge(followings, response.data))
26236
+ * ```
26237
+ *
26238
+ * Observe all mutations on a list of {@link Amity.FollowStatus} followings for a given userId
26239
+ *
26240
+ * @param userId the user
26241
+ * @param callback the function to call when new data are available
26242
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
26243
+ *
26244
+ * @category Followings Live Collection
26245
+ */
26246
+ const liveFollowings = (params, callback, config) => {
26247
+ const { log, cache } = getActiveClient();
26248
+ if (!cache) {
26249
+ console.log('For using Live Collection feature you need to enable Cache!');
26250
+ }
26251
+ const timestamp = Date.now();
26252
+ log(`liveFollowings(tmpid: ${timestamp}) > listen`);
26253
+ const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
26254
+ const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
26255
+ const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
26256
+ const disposers = [];
26257
+ const cacheKey = ['follow', 'collection', { userId: params.userId, type: 'following' }];
26258
+ const responder = (data) => {
26259
+ var _a, _b;
26260
+ let followings = (_a = data.data
26261
+ .map(key => pullFromCache(['follow', 'get', key]))
26262
+ .filter(Boolean)
26263
+ .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
26264
+ if (params.status) {
26265
+ followings = filterByPropEquality(followings, 'status', params.status);
26266
+ }
26267
+ callback({
26268
+ onNextPage: onFetch,
26269
+ data: followings,
26270
+ hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
26271
+ loading: data.loading,
26272
+ error: data.error,
26273
+ });
26274
+ };
26275
+ const realtimeRouter = (followStatus, action) => {
26276
+ var _a;
26277
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26278
+ if (params.userId !== followStatus.from || !collection)
26279
+ return;
26280
+ if (['onDeclined', 'onCanceled', 'onUnfollowed', 'onDeleted'].includes(action)) {
26281
+ collection.data = collection.data.filter(p => p !== getResolver('follow')(followStatus));
26282
+ }
26283
+ else if (['onRequested', 'onAccepted', 'onFollowed'].includes(action)) {
26284
+ collection.data = [...new Set([getResolver('follow')(followStatus), ...collection.data])];
26285
+ }
26286
+ pushToCache(cacheKey, collection);
26287
+ responder(collection);
26288
+ };
26289
+ const onFetch = () => {
26290
+ var _a, _b, _c, _d, _e;
26291
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
26292
+ const followings = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
26293
+ if (followings.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
26294
+ return;
26295
+ const query = createQuery(queryFollowings, Object.assign(Object.assign({}, queryParams), { page: (_e = (_d = collection === null || collection === void 0 ? void 0 : collection.params) === null || _d === void 0 ? void 0 : _d.page) !== null && _e !== void 0 ? _e : { limit } }));
26296
+ runQuery(query, ({ data: result, error, loading, nextPage: page }) => {
26297
+ const data = {
26298
+ loading,
26299
+ error,
26300
+ params: { page },
26301
+ data: followings,
26302
+ };
26303
+ if (result) {
26304
+ data.data = [...new Set([...followings, ...result.map(getResolver('follow'))])];
26305
+ }
26306
+ pushToCache(cacheKey, data);
26307
+ responder(data);
26308
+ }, queryOptions(policy));
26309
+ };
26310
+ disposers.push(onFollowerRequested(followStatus => realtimeRouter(followStatus, 'onRequested')), onFollowRequestAccepted(followStatus => realtimeRouter(followStatus, 'onAccepted')), onFollowRequestDeclined(followStatus => realtimeRouter(followStatus, 'onDeclined')), onFollowRequestCanceled(followStatus => realtimeRouter(followStatus, 'onCanceled')), onUserFollowed(followStatus => realtimeRouter(followStatus, 'onFollowed')), onUserUnfollowed(followStatus => realtimeRouter(followStatus, 'onUnfollowed')), onFollowerDeleted(followStatus => realtimeRouter(followStatus, 'onDeleted')));
26311
+ onFetch();
26312
+ return () => {
26313
+ log(`liveFollowings(tmpid: ${timestamp}) > dispose`);
26314
+ disposers.forEach(fn => fn());
26315
+ };
26316
+ };
26317
+
25887
26318
  /**
25888
26319
  * ```js
25889
26320
  * import { observePosts } from '@amityco/ts-sdk'
@@ -25992,7 +26423,7 @@ const observePost = (postId, callback, policy = 'cache_then_server') => {
25992
26423
  const livePosts = (params, callback, config) => {
25993
26424
  const { log, cache } = getActiveClient();
25994
26425
  if (!cache) {
25995
- console.log('For using Live Collection feature you need to enable Cache!');
26426
+ console.log(ENABLE_CACHE_MESSAGE);
25996
26427
  }
25997
26428
  const timestamp = Date.now();
25998
26429
  log(`livePosts(tmpid: ${timestamp}) > listen`);
@@ -26830,4 +27261,4 @@ const createUserToken = async (apiKey, apiRegion, params) => {
26830
27261
  return { accessToken: data.accessToken };
26831
27262
  };
26832
27263
 
26833
- export { API_REGIONS, SubscriptionLevels, VERSION$1 as VERSION, acceptFollower, addChannelMembers, addChannelMembersRole, addCommunityMembers, addCommunityMembersRoles, addReaction, approvePost, backupCache, banChannelMembers, closePoll, connectClient, createChannel, createClient, createComment, createCommunity, createFile, createImage, createMessage, createPoll, createPost, createQuery, createReport, createStream, createUserToken, createVideo, declineFollower, declinePost, deleteChannel, deleteComment, deleteCommunity, deleteFile, deleteMessage, deletePoll, deletePost, deleteReport, deleteStream, disableCache, disconnectClient, disposeStream, dropFromCache, enableCache, fileUrlWithSize, filterByPropEquality, follow, getActiveClient, getCategory, getChannel, getChannels, getComment, getCommentTopic, getComments, getCommunities, getCommunity, getCommunityTopic, getFile, getFollowInfo, getMessage, getMessages, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPoll, getPost, getPostTopic, getPosts, getRecommendedCommunities, getRole, getStream, getTopTrendingCommunities, getUser, getUserTopic, getUsers, isAfterBefore, isAfterBeforeRaw, isCachable, isConnected, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkipLimit, joinChannel, joinCommunity, leaveChannel, leaveCommunity, liveComments, livePosts, liveReactions, mergeInCache, observeChannel, observeComment, observeComments, observeCommunity, observeFile, observeFollowInfo, observeFollowers, observeFollowings, observeMessage, observeMessages, observePoll, observePost, observePosts, observeUser, onChannelDeleted, onChannelJoined, onChannelLeft, onChannelMemberAdded, onChannelMemberRemoved, onChannelUpdated, onClientBanned, onClientDisconnected, onCommentCreated, onCommentDeleted, onCommentFlagged, onCommentReactionAdded, onCommentReactionRemoved, onCommentUnflagged, onCommentUpdated, onCommunityCreated, onCommunityDeleted, onCommunityJoined, onCommunityLeft, onCommunityUpdated, onCommunityUserAdded, onCommunityUserBanned, onCommunityUserRemoved, onCommunityUserUnbanned, onConnectionError, onFollowInfoUpdated, onFollowRequestAccepted, onFollowRequestCanceled, onFollowRequestDeclined, onFollowerDeleted, onFollowerRequested, onMessageCreated, onMessageDeleted, onMessageUpdated, onPollDeleted, onPollUpdated, onPostApproved, onPostCreated, onPostDeclined, onPostDeleted, onPostFlagged, onPostReactionAdded, onPostReactionRemoved, onPostUnflagged, onPostUpdated, onReactionAdded, onReactionRemoved, onReactorAdded, onReactorRemoved, onStreamRecorded, onStreamStarted, onStreamStopped, onUserDeleted, onUserFlagCleared, onUserFlagged, onUserFollowed, onUserUnflagged, onUserUnfollowed, onUserUpdated, pullFromCache, pushToCache, queryCache, queryCategories, queryChannelMembers, queryChannels, queryComments, queryCommunities, queryCommunityMembers, queryFollowers, queryFollowings, queryGlobalFeed, queryMessages, queryOptions, queryPosts, queryReactions, queryRoles, queryStreams, queryUsers, removeChannelMembers, removeChannelMembersRole, removeCommunityMembers, removeCommunityMembersRoles, removeReaction, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByLastActivity, sortByLastCreated, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, unbanChannelMembers, unfollow, updateChannel, updateComment, updateCommunity, updateMessage, updatePost, updateStream, updateUser, upsertInCache, votePoll, wipeCache };
27264
+ export { API_REGIONS, ContentFeedType, FileType, SubscriptionLevels, VERSION$1 as VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, acceptFollower, addChannelMembers, addChannelMembersRole, addCommunityMembers, addCommunityMembersRoles, addReaction, approvePost, backupCache, banChannelMembers, closePoll, connectClient, createChannel, createClient, createComment, createCommunity, createFile, createImage, createMessage, createPoll, createPost, createQuery, createReport, createStream, createUserToken, createVideo, declineFollower, declinePost, deleteChannel, deleteComment, deleteCommunity, deleteFile, deleteMessage, deletePoll, deletePost, deleteReport, deleteStream, disableCache, disconnectClient, disposeStream, dropFromCache, enableCache, fileUrlWithSize, filterByPropEquality, follow, getActiveClient, getCategory, getChannel, getChannels, getComment, getCommentTopic, getComments, getCommunities, getCommunity, getCommunityTopic, getFeedSettings, getFile, getFollowInfo, getMessage, getMessages, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPoll, getPost, getPostTopic, getPosts, getRecommendedCommunities, getRole, getStream, getTopTrendingCommunities, getUser, getUserTopic, getUsers, isAfterBefore, isAfterBeforeRaw, isCachable, isConnected, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkipLimit, joinChannel, joinCommunity, leaveChannel, leaveCommunity, liveComments, liveFollowers, liveFollowings, liveMessages, livePosts, liveReactions, mergeInCache, observeChannel, observeChannels, observeComment, observeComments, observeCommunity, observeFile, observeFollowInfo, observeFollowers, observeFollowings, observeMessage, observeMessages, observePoll, observePost, observePosts, observeUser, onChannelCreated, onChannelDeleted, onChannelJoined, onChannelLeft, onChannelMemberAdded, onChannelMemberRemoved, onChannelUpdated, onClientBanned, onClientDisconnected, onCommentCreated, onCommentDeleted, onCommentFlagged, onCommentReactionAdded, onCommentReactionRemoved, onCommentUnflagged, onCommentUpdated, onCommunityCreated, onCommunityDeleted, onCommunityJoined, onCommunityLeft, onCommunityUpdated, onCommunityUserAdded, onCommunityUserBanned, onCommunityUserRemoved, onCommunityUserUnbanned, onConnectionError, onFollowInfoUpdated, onFollowRequestAccepted, onFollowRequestCanceled, onFollowRequestDeclined, onFollowerDeleted, onFollowerRequested, onMessageCreated, onMessageDeleted, onMessageUpdated, onPollDeleted, onPollUpdated, onPostApproved, onPostCreated, onPostDeclined, onPostDeleted, onPostFlagged, onPostReactionAdded, onPostReactionRemoved, onPostUnflagged, onPostUpdated, onReactionAdded, onReactionRemoved, onReactorAdded, onReactorRemoved, onStreamRecorded, onStreamStarted, onStreamStopped, onUserDeleted, onUserFlagCleared, onUserFlagged, onUserFollowed, onUserUnflagged, onUserUnfollowed, onUserUpdated, pullFromCache, pushToCache, queryCache, queryCategories, queryChannelMembers, queryChannels, queryComments, queryCommunities, queryCommunityMembers, queryFollowers, queryFollowings, queryGlobalFeed, queryMessages, queryOptions, queryPosts, queryReactions, queryRoles, queryStreams, queryUsers, removeChannelMembers, removeChannelMembersRole, removeCommunityMembers, removeCommunityMembersRoles, removeReaction, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByLastActivity, sortByLastCreated, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, unbanChannelMembers, unfollow, updateChannel, updateComment, updateCommunity, updateMessage, updatePost, updateStream, updateUser, upsertInCache, votePoll, wipeCache };