@amityco/ts-sdk 7.22.0 → 7.22.1-1ee4cf76.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/dist/@types/core/errors.d.ts +2 -1
  2. package/dist/@types/core/errors.d.ts.map +1 -1
  3. package/dist/@types/core/events.d.ts +7 -1
  4. package/dist/@types/core/events.d.ts.map +1 -1
  5. package/dist/@types/core/model.d.ts +4 -0
  6. package/dist/@types/core/model.d.ts.map +1 -1
  7. package/dist/@types/core/payload.d.ts +16 -0
  8. package/dist/@types/core/payload.d.ts.map +1 -1
  9. package/dist/@types/core/transport.d.ts +1 -0
  10. package/dist/@types/core/transport.d.ts.map +1 -1
  11. package/dist/@types/domains/analytics.d.ts +3 -2
  12. package/dist/@types/domains/analytics.d.ts.map +1 -1
  13. package/dist/@types/domains/block.d.ts +5 -0
  14. package/dist/@types/domains/block.d.ts.map +1 -1
  15. package/dist/@types/domains/channel.d.ts +20 -0
  16. package/dist/@types/domains/channel.d.ts.map +1 -1
  17. package/dist/@types/domains/client.d.ts +8 -2
  18. package/dist/@types/domains/client.d.ts.map +1 -1
  19. package/dist/@types/domains/comment.d.ts +1 -0
  20. package/dist/@types/domains/comment.d.ts.map +1 -1
  21. package/dist/@types/domains/feed.d.ts +14 -0
  22. package/dist/@types/domains/feed.d.ts.map +1 -1
  23. package/dist/@types/domains/message.d.ts +16 -0
  24. package/dist/@types/domains/message.d.ts.map +1 -1
  25. package/dist/@types/domains/notificationSettings.d.ts +101 -0
  26. package/dist/@types/domains/notificationSettings.d.ts.map +1 -0
  27. package/dist/@types/domains/post.d.ts +2 -0
  28. package/dist/@types/domains/post.d.ts.map +1 -1
  29. package/dist/@types/domains/sharableContentType.d.ts +9 -0
  30. package/dist/@types/domains/sharableContentType.d.ts.map +1 -0
  31. package/dist/@types/index.d.ts +3 -1
  32. package/dist/@types/index.d.ts.map +1 -1
  33. package/dist/analytic/service/analytic/AnalyticsEngine.d.ts +1 -0
  34. package/dist/analytic/service/analytic/AnalyticsEngine.d.ts.map +1 -1
  35. package/dist/analytic/service/analytic/AnalyticsEventCapturer.d.ts +2 -1
  36. package/dist/analytic/service/analytic/AnalyticsEventCapturer.d.ts.map +1 -1
  37. package/dist/analytic/service/analytic/AnalyticsService.d.ts +1 -0
  38. package/dist/analytic/service/analytic/AnalyticsService.d.ts.map +1 -1
  39. package/dist/channelRepository/api/archiveChannel.d.ts +16 -0
  40. package/dist/channelRepository/api/archiveChannel.d.ts.map +1 -0
  41. package/dist/channelRepository/api/getArchivedChannelIds.d.ts +13 -0
  42. package/dist/channelRepository/api/getArchivedChannelIds.d.ts.map +1 -0
  43. package/dist/channelRepository/api/index.d.ts +3 -0
  44. package/dist/channelRepository/api/index.d.ts.map +1 -1
  45. package/dist/channelRepository/api/unarchiveChannel.d.ts +16 -0
  46. package/dist/channelRepository/api/unarchiveChannel.d.ts.map +1 -0
  47. package/dist/channelRepository/api/updateChannel.d.ts +1 -1
  48. package/dist/channelRepository/api/updateChannel.d.ts.map +1 -1
  49. package/dist/channelRepository/channelMembership/observers/getMembers/ChannelMemberQueryStreamController.d.ts.map +1 -1
  50. package/dist/channelRepository/channelModeration/api/banMembers.d.ts.map +1 -1
  51. package/dist/channelRepository/channelModeration/api/muteMembers.d.ts.map +1 -1
  52. package/dist/channelRepository/channelModeration/api/unbanMembers.d.ts.map +1 -1
  53. package/dist/channelRepository/channelModeration/api/unmuteMembers.d.ts.map +1 -1
  54. package/dist/channelRepository/events/index.d.ts +2 -0
  55. package/dist/channelRepository/events/index.d.ts.map +1 -1
  56. package/dist/channelRepository/events/onChannelArchived.d.ts +10 -0
  57. package/dist/channelRepository/events/onChannelArchived.d.ts.map +1 -0
  58. package/dist/channelRepository/events/onChannelMemberRoleRemoved.d.ts.map +1 -1
  59. package/dist/channelRepository/events/onChannelUnarchived.d.ts +11 -0
  60. package/dist/channelRepository/events/onChannelUnarchived.d.ts.map +1 -0
  61. package/dist/channelRepository/observers/getArchivedChannels/ArchivedChannelLiveCollectionController.d.ts +12 -0
  62. package/dist/channelRepository/observers/getArchivedChannels/ArchivedChannelLiveCollectionController.d.ts.map +1 -0
  63. package/dist/channelRepository/observers/getArchivedChannels/ArchivedChannelPaginationController.d.ts +11 -0
  64. package/dist/channelRepository/observers/getArchivedChannels/ArchivedChannelPaginationController.d.ts.map +1 -0
  65. package/dist/channelRepository/observers/getArchivedChannels/ArchivedChannelQueryStreamController.d.ts +13 -0
  66. package/dist/channelRepository/observers/getArchivedChannels/ArchivedChannelQueryStreamController.d.ts.map +1 -0
  67. package/dist/channelRepository/observers/getArchivedChannels/getArchivedChannels.d.ts +20 -0
  68. package/dist/channelRepository/observers/getArchivedChannels/getArchivedChannels.d.ts.map +1 -0
  69. package/dist/channelRepository/observers/getArchivedChannels/index.d.ts +2 -0
  70. package/dist/channelRepository/observers/getArchivedChannels/index.d.ts.map +1 -0
  71. package/dist/channelRepository/observers/getChannels/ChannelLiveCollectionController.d.ts.map +1 -1
  72. package/dist/channelRepository/observers/getChannels/ChannelQueryStreamController.d.ts.map +1 -1
  73. package/dist/channelRepository/observers/index.d.ts +1 -0
  74. package/dist/channelRepository/observers/index.d.ts.map +1 -1
  75. package/dist/channelRepository/utils/prepareChannelPayload.d.ts.map +1 -1
  76. package/dist/client/api/autoSubscription.d.ts +50 -0
  77. package/dist/client/api/autoSubscription.d.ts.map +1 -0
  78. package/dist/client/api/getShareableLinkConfiguration.d.ts +2 -2
  79. package/dist/client/api/getShareableLinkConfiguration.d.ts.map +1 -1
  80. package/dist/client/api/index.d.ts +3 -0
  81. package/dist/client/api/index.d.ts.map +1 -1
  82. package/dist/client/api/notifications.d.ts +27 -0
  83. package/dist/client/api/notifications.d.ts.map +1 -0
  84. package/dist/client/api/setupLoginSubscriptions.d.ts.map +1 -1
  85. package/dist/client/api/tests/ShareableLinkConfiguration.test.d.ts +2 -0
  86. package/dist/client/api/tests/ShareableLinkConfiguration.test.d.ts.map +1 -0
  87. package/dist/client/api/tests/notifications.integration.test.d.ts +2 -0
  88. package/dist/client/api/tests/notifications.integration.test.d.ts.map +1 -0
  89. package/dist/client/services/ReadReceiptSync/readReceiptSyncEngine.d.ts.map +1 -1
  90. package/dist/client/utils/autoSubscriptionManager.d.ts +41 -0
  91. package/dist/client/utils/autoSubscriptionManager.d.ts.map +1 -0
  92. package/dist/client/utils/subscribeGlobalTopic.d.ts +6 -1
  93. package/dist/client/utils/subscribeGlobalTopic.d.ts.map +1 -1
  94. package/dist/client/utils/tests/autoSubscriptionManager.test.d.ts +2 -0
  95. package/dist/client/utils/tests/autoSubscriptionManager.test.d.ts.map +1 -0
  96. package/dist/commentRepository/observers/getComments/CommentLiveCollectionController.d.ts.map +1 -1
  97. package/dist/commentRepository/observers/tests/integrations/getCommentsExcludeBlockUser.integration.test.d.ts +2 -0
  98. package/dist/commentRepository/observers/tests/integrations/getCommentsExcludeBlockUser.integration.test.d.ts.map +1 -0
  99. package/dist/core/events.d.ts +3 -3
  100. package/dist/core/events.d.ts.map +1 -1
  101. package/dist/core/model/idResolvers.d.ts.map +1 -1
  102. package/dist/core/model/index.d.ts.map +1 -1
  103. package/dist/core/query/filtering.d.ts +32 -0
  104. package/dist/core/query/filtering.d.ts.map +1 -1
  105. package/dist/core/query/paging.d.ts +1 -0
  106. package/dist/core/query/paging.d.ts.map +1 -1
  107. package/dist/core/subscription.d.ts +3 -0
  108. package/dist/core/subscription.d.ts.map +1 -1
  109. package/dist/feedRepository/errors/AmityForYouFeedDisabledError.d.ts +13 -0
  110. package/dist/feedRepository/errors/AmityForYouFeedDisabledError.d.ts.map +1 -0
  111. package/dist/feedRepository/index.d.ts +2 -1
  112. package/dist/feedRepository/index.d.ts.map +1 -1
  113. package/dist/feedRepository/observers/getForYouFeed/CursorController.d.ts +17 -0
  114. package/dist/feedRepository/observers/getForYouFeed/CursorController.d.ts.map +1 -0
  115. package/dist/feedRepository/observers/getForYouFeed/LiveCollectionController.d.ts +13 -0
  116. package/dist/feedRepository/observers/getForYouFeed/LiveCollectionController.d.ts.map +1 -0
  117. package/dist/feedRepository/observers/getForYouFeed/PaginationController.d.ts +12 -0
  118. package/dist/feedRepository/observers/getForYouFeed/PaginationController.d.ts.map +1 -0
  119. package/dist/feedRepository/observers/getForYouFeed/QueryStreamController.d.ts +15 -0
  120. package/dist/feedRepository/observers/getForYouFeed/QueryStreamController.d.ts.map +1 -0
  121. package/dist/feedRepository/observers/getForYouFeed.d.ts +19 -0
  122. package/dist/feedRepository/observers/getForYouFeed.d.ts.map +1 -0
  123. package/dist/feedRepository/observers/index.d.ts +1 -0
  124. package/dist/feedRepository/observers/index.d.ts.map +1 -1
  125. package/dist/feedRepository/observers/tests/integration/getForYouFeed.integration.test.d.ts +2 -0
  126. package/dist/feedRepository/observers/tests/integration/getForYouFeed.integration.test.d.ts.map +1 -0
  127. package/dist/feedRepository/observers/tests/unit/CursorController.test.d.ts +2 -0
  128. package/dist/feedRepository/observers/tests/unit/CursorController.test.d.ts.map +1 -0
  129. package/dist/index.cjs.js +1817 -195
  130. package/dist/index.esm.js +1814 -196
  131. package/dist/index.umd.js +3 -3
  132. package/dist/messagePreview/utils/getChannelMessagePreviewWithUser.d.ts +1 -0
  133. package/dist/messagePreview/utils/getChannelMessagePreviewWithUser.d.ts.map +1 -1
  134. package/dist/messagePreview/utils/updateChannelMessagePreviewCache.d.ts.map +1 -1
  135. package/dist/messageRepository/events/onMessageCreated.d.ts.map +1 -1
  136. package/dist/messageRepository/observers/index.d.ts +1 -0
  137. package/dist/messageRepository/observers/index.d.ts.map +1 -1
  138. package/dist/messageRepository/observers/searchMessage/SearchMessageLiveCollectionController.d.ts +12 -0
  139. package/dist/messageRepository/observers/searchMessage/SearchMessageLiveCollectionController.d.ts.map +1 -0
  140. package/dist/messageRepository/observers/searchMessage/SearchMessagePaginationController.d.ts +10 -0
  141. package/dist/messageRepository/observers/searchMessage/SearchMessagePaginationController.d.ts.map +1 -0
  142. package/dist/messageRepository/observers/searchMessage/SearchMessageQueryStreamController.d.ts +8 -0
  143. package/dist/messageRepository/observers/searchMessage/SearchMessageQueryStreamController.d.ts.map +1 -0
  144. package/dist/messageRepository/observers/searchMessage/index.d.ts +2 -0
  145. package/dist/messageRepository/observers/searchMessage/index.d.ts.map +1 -0
  146. package/dist/messageRepository/observers/searchMessage/searchMessage.d.ts +24 -0
  147. package/dist/messageRepository/observers/searchMessage/searchMessage.d.ts.map +1 -0
  148. package/dist/postRepository/observers/getPosts/PostLiveCollectionController.d.ts.map +1 -1
  149. package/dist/postRepository/observers/tests/getPostsExcludeBlockUser.test.d.ts +2 -0
  150. package/dist/postRepository/observers/tests/getPostsExcludeBlockUser.test.d.ts.map +1 -0
  151. package/dist/postRepository/tests/integration/postAnalytics.integration.test.d.ts +2 -0
  152. package/dist/postRepository/tests/integration/postAnalytics.integration.test.d.ts.map +1 -0
  153. package/dist/postRepository/tests/integration/setup.d.ts +6 -0
  154. package/dist/postRepository/tests/integration/setup.d.ts.map +1 -0
  155. package/dist/reactionRepository/internalApi/addReaction.d.ts.map +1 -1
  156. package/dist/reactionRepository/internalApi/removeReaction.d.ts.map +1 -1
  157. package/dist/streamRepository/observers/getStreams/GetStreamsPageController.d.ts +1 -0
  158. package/dist/streamRepository/observers/getStreams/GetStreamsPageController.d.ts.map +1 -1
  159. package/dist/userRepository/observers/getBlockedUsers/BlockedUserLiveCollectionController.d.ts.map +1 -1
  160. package/dist/userRepository/observers/getBlockedUsers/BlockedUserQueryStreamController.d.ts +4 -3
  161. package/dist/userRepository/observers/getBlockedUsers/BlockedUserQueryStreamController.d.ts.map +1 -1
  162. package/dist/userRepository/observers/getBlockingUsers/LiveCollectionController.d.ts +13 -0
  163. package/dist/userRepository/observers/getBlockingUsers/LiveCollectionController.d.ts.map +1 -0
  164. package/dist/userRepository/observers/getBlockingUsers/PaginationController.d.ts +5 -0
  165. package/dist/userRepository/observers/getBlockingUsers/PaginationController.d.ts.map +1 -0
  166. package/dist/userRepository/observers/getBlockingUsers/QueryStreamController.d.ts +16 -0
  167. package/dist/userRepository/observers/getBlockingUsers/QueryStreamController.d.ts.map +1 -0
  168. package/dist/userRepository/observers/getBlockingUsers.d.ts +17 -0
  169. package/dist/userRepository/observers/getBlockingUsers.d.ts.map +1 -0
  170. package/dist/userRepository/observers/index.d.ts +1 -0
  171. package/dist/userRepository/observers/index.d.ts.map +1 -1
  172. package/dist/userRepository/observers/tests/integrations/getBlockingUsers.integration.test.d.ts +2 -0
  173. package/dist/userRepository/observers/tests/integrations/getBlockingUsers.integration.test.d.ts.map +1 -0
  174. package/dist/userRepository/relationship/block/enum/index.d.ts +5 -0
  175. package/dist/userRepository/relationship/block/enum/index.d.ts.map +1 -0
  176. package/dist/userRepository/relationship/block/events/index.d.ts +3 -0
  177. package/dist/userRepository/relationship/block/events/index.d.ts.map +1 -0
  178. package/dist/userRepository/relationship/block/events/onUserDidBlock.d.ts +20 -0
  179. package/dist/userRepository/relationship/block/events/onUserDidBlock.d.ts.map +1 -0
  180. package/dist/userRepository/relationship/block/events/onUserDidUnblock.d.ts +20 -0
  181. package/dist/userRepository/relationship/block/events/onUserDidUnblock.d.ts.map +1 -0
  182. package/dist/userRepository/relationship/block/index.d.ts +1 -0
  183. package/dist/userRepository/relationship/block/index.d.ts.map +1 -1
  184. package/dist/userRepository/relationship/block/utils/createBlockEventSubscriber.d.ts +11 -0
  185. package/dist/userRepository/relationship/block/utils/createBlockEventSubscriber.d.ts.map +1 -0
  186. package/dist/userRepository/utils/prepareBlockingUserPayload.d.ts +2 -0
  187. package/dist/userRepository/utils/prepareBlockingUserPayload.d.ts.map +1 -0
  188. package/dist/utils/constants.d.ts +4 -0
  189. package/dist/utils/constants.d.ts.map +1 -1
  190. package/dist/utils/linkedObject/channelLinkedObject.d.ts.map +1 -1
  191. package/dist/utils/linkedObject/postLinkedObject.d.ts.map +1 -1
  192. package/dist/utils/tests/dummy/community.d.ts +2 -0
  193. package/dist/utils/tests/dummy/community.d.ts.map +1 -1
  194. package/dist/utils/tests/dummy/post.d.ts.map +1 -1
  195. package/package.json +1 -1
package/dist/index.cjs.js CHANGED
@@ -74,6 +74,13 @@ exports.FileAccessTypeEnum = void 0;
74
74
  FileAccessTypeEnum["NETWORK"] = "network";
75
75
  })(exports.FileAccessTypeEnum || (exports.FileAccessTypeEnum = {}));
76
76
 
77
+ exports.AmityChannelNotificationModeEnum = void 0;
78
+ (function (AmityChannelNotificationModeEnum) {
79
+ AmityChannelNotificationModeEnum["Default"] = "default";
80
+ AmityChannelNotificationModeEnum["Silent"] = "silent";
81
+ AmityChannelNotificationModeEnum["Subscribe"] = "subscribe";
82
+ })(exports.AmityChannelNotificationModeEnum || (exports.AmityChannelNotificationModeEnum = {}));
83
+
77
84
  const CommunityPostSettings = Object.freeze({
78
85
  ONLY_ADMIN_CAN_POST: 'ONLY_ADMIN_CAN_POST',
79
86
  ADMIN_REVIEW_POST_REQUIRED: 'ADMIN_REVIEW_POST_REQUIRED',
@@ -249,12 +256,54 @@ exports.AmityEventOrderOption = void 0;
249
256
  AmityEventOrderOption["Descending"] = "desc";
250
257
  })(exports.AmityEventOrderOption || (exports.AmityEventOrderOption = {}));
251
258
 
259
+ exports.AmitySharableContentType = void 0;
260
+ (function (AmitySharableContentType) {
261
+ AmitySharableContentType["POST"] = "post";
262
+ AmitySharableContentType["COMMUNITY"] = "community";
263
+ AmitySharableContentType["USER"] = "user";
264
+ AmitySharableContentType["LIVESTREAM"] = "livestream";
265
+ AmitySharableContentType["EVENT"] = "event";
266
+ })(exports.AmitySharableContentType || (exports.AmitySharableContentType = {}));
267
+
252
268
  exports.AnalyticsSourceTypeEnum = void 0;
253
269
  (function (AnalyticsSourceTypeEnum) {
254
270
  AnalyticsSourceTypeEnum["POST"] = "post";
255
271
  AnalyticsSourceTypeEnum["ROOM"] = "room";
256
272
  })(exports.AnalyticsSourceTypeEnum || (exports.AnalyticsSourceTypeEnum = {}));
257
273
 
274
+ exports.UserNotificationModuleNameEnum = void 0;
275
+ (function (UserNotificationModuleNameEnum) {
276
+ UserNotificationModuleNameEnum["CHAT"] = "chat";
277
+ UserNotificationModuleNameEnum["SOCIAL"] = "social";
278
+ UserNotificationModuleNameEnum["VIDEO_STREAMING"] = "video-streaming";
279
+ })(exports.UserNotificationModuleNameEnum || (exports.UserNotificationModuleNameEnum = {}));
280
+ exports.CommunityNotificationEventNameEnum = void 0;
281
+ (function (CommunityNotificationEventNameEnum) {
282
+ CommunityNotificationEventNameEnum["POST_CREATED"] = "post.created";
283
+ CommunityNotificationEventNameEnum["POST_REACTED"] = "post.reacted";
284
+ CommunityNotificationEventNameEnum["COMMENT_CREATED"] = "comment.created";
285
+ CommunityNotificationEventNameEnum["COMMENT_REPLIED"] = "comment.replied";
286
+ CommunityNotificationEventNameEnum["COMMENT_REACTED"] = "comment.reacted";
287
+ CommunityNotificationEventNameEnum["STORY_CREATED"] = "story.created";
288
+ CommunityNotificationEventNameEnum["STORY_REACTED"] = "story.reacted";
289
+ CommunityNotificationEventNameEnum["STORY_COMMENT_CREATED"] = "story-comment.created";
290
+ CommunityNotificationEventNameEnum["LIVESTREAM_START"] = "video-streaming.didStart";
291
+ })(exports.CommunityNotificationEventNameEnum || (exports.CommunityNotificationEventNameEnum = {}));
292
+ exports.NotificationSettingsLevelEnum = void 0;
293
+ (function (NotificationSettingsLevelEnum) {
294
+ NotificationSettingsLevelEnum["USER"] = "user";
295
+ NotificationSettingsLevelEnum["COMMUNITY"] = "community";
296
+ NotificationSettingsLevelEnum["CHANNEL"] = "channel";
297
+ })(exports.NotificationSettingsLevelEnum || (exports.NotificationSettingsLevelEnum = {}));
298
+ /**
299
+ * `NOT` variant is intentionally excluded from public API (internal server-side use only).
300
+ */
301
+ exports.NotificationRolesFilterTypeEnum = void 0;
302
+ (function (NotificationRolesFilterTypeEnum) {
303
+ NotificationRolesFilterTypeEnum["ALL"] = "all";
304
+ NotificationRolesFilterTypeEnum["ONLY"] = "only";
305
+ })(exports.NotificationRolesFilterTypeEnum || (exports.NotificationRolesFilterTypeEnum = {}));
306
+
258
307
  function getVersion() {
259
308
  try {
260
309
  // the string ''v7.22.0-cjs'' should be replaced by actual value by @rollup/plugin-replace
@@ -267,6 +316,7 @@ function getVersion() {
267
316
  const VERSION = getVersion();
268
317
 
269
318
  const COLLECTION_DEFAULT_PAGINATION_LIMIT = 5;
319
+ const COLLECTION_DEFAULT_PAGINATION_SIZE = 20;
270
320
  const COLLECTION_DEFAULT_CACHING_POLICY = 'cache_then_server';
271
321
  const ENABLE_CACHE_MESSAGE = 'For using Live Collection feature you need to enable Cache!';
272
322
  const LIVE_OBJECT_ENABLE_CACHE_MESSAGE = 'For using Live Object feature you need to enable Cache!';
@@ -279,6 +329,9 @@ const DAY = 24 * HOUR;
279
329
  const WEEK = 7 * DAY;
280
330
  const YEAR = 365 * DAY;
281
331
  const ACCESS_TOKEN_WATCHER_INTERVAL = 10 * MINUTE;
332
+ const API_ENDPOINTS = {
333
+ forYouFeed: '/api/v1/feeds/for-you',
334
+ };
282
335
 
283
336
  // cache constants
284
337
  const CACHE_KEY_GET = 'get';
@@ -659,6 +712,95 @@ function createSnapshot(data, options) {
659
712
  return Object.assign(Object.assign({}, options), { data });
660
713
  }
661
714
 
715
+ /* eslint-disable max-classes-per-file */
716
+ /**
717
+ * Generic ASC error
718
+ * @category Errors
719
+ */
720
+ class ASCError extends Error {
721
+ /**
722
+ * @param message A custom error message
723
+ * @param code A normalized error code
724
+ * @param level A normalized failure level descriptor
725
+ */
726
+ constructor(message, code, level) {
727
+ super(`Amity SDK (${code}): ${message}`);
728
+ this.code = code;
729
+ this.level = level;
730
+ this.type = 'ASC';
731
+ this.timestamp = Date.now();
732
+ if (Error.captureStackTrace)
733
+ Error.captureStackTrace(this, ASCError);
734
+ }
735
+ }
736
+ /**
737
+ * API level error
738
+ * @category Errors
739
+ */
740
+ class ASCApiError extends ASCError {
741
+ /**
742
+ * @param code A normalized error code
743
+ * @param level A normalized failure level descriptor
744
+ */
745
+ // eslint-disable-next-line no-useless-constructor
746
+ constructor(message, code, level) {
747
+ super(message, code, level);
748
+ }
749
+ }
750
+ /**
751
+ * Unexpected error
752
+ * @category Errors
753
+ */
754
+ class ASCUnknownError extends ASCError {
755
+ /**
756
+ * @param code A normalized error code
757
+ * @param level A normalized failure level descriptor
758
+ */
759
+ constructor(code = 800000 /* Amity.ClientError.UNKNOWN_ERROR */, level = "fatal" /* Amity.ErrorLevel.FATAL */) {
760
+ super('Unexpected error', code, level);
761
+ }
762
+ }
763
+ /**
764
+ * Network related error
765
+ * @category Errors
766
+ */
767
+ class ASCConnectionError extends ASCError {
768
+ /**
769
+ * @param message A custom error message
770
+ */
771
+ constructor(event, message = 'SDK client is having connection issues') {
772
+ super(`${message} (${event})`, event === 'disconnected'
773
+ ? 800211 /* Amity.ClientError.DISCONNECTED */
774
+ : 800210 /* Amity.ClientError.CONNECTION_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
775
+ this.event = event;
776
+ }
777
+ }
778
+
779
+ let activeClient = null;
780
+ /**
781
+ * Get the active client
782
+ *
783
+ * @returns the active client instance
784
+ *
785
+ * @hidden
786
+ */
787
+ const getActiveClient = () => {
788
+ if (!activeClient) {
789
+ throw new ASCError('There is no active client', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "fatal" /* Amity.ErrorLevel.FATAL */);
790
+ }
791
+ return activeClient;
792
+ };
793
+ /**
794
+ * Sets the active client
795
+ *
796
+ * @param client the client to assume as currently active client
797
+ *
798
+ * @hidden
799
+ */
800
+ const setActiveClient = (client) => {
801
+ activeClient = client;
802
+ };
803
+
662
804
  /** @hidden */
663
805
  const idResolvers = {
664
806
  user: ({ userId }) => userId,
@@ -667,6 +809,7 @@ const idResolvers = {
667
809
  channel: ({ channelInternalId }) => channelInternalId,
668
810
  subChannel: ({ subChannelId }) => subChannelId,
669
811
  channelUsers: ({ channelId, userId }) => `${channelId}#${userId}`,
812
+ archivedChannel: ({ channelId }) => channelId,
670
813
  message: ({ messageId, referenceId }) => referenceId !== null && referenceId !== void 0 ? referenceId : messageId,
671
814
  messagePreviewChannel: ({ channelId }) => `${channelId}`,
672
815
  messagePreviewSubChannel: ({ subChannelId }) => `${subChannelId}`,
@@ -708,6 +851,7 @@ const idResolvers = {
708
851
  event: ({ eventId }) => eventId,
709
852
  eventResponse: ({ userId }) => userId,
710
853
  product: ({ productId }) => productId,
854
+ feedMetadata: ({ postId }) => postId,
711
855
  };
712
856
  /**
713
857
  * Retrieve the id resolver matching a domain name
@@ -730,6 +874,7 @@ const PAYLOAD2MODEL = {
730
874
  channels: 'channel',
731
875
  messageFeeds: 'subChannel',
732
876
  channelUsers: 'channelUsers',
877
+ archives: 'archivedChannel',
733
878
  messages: 'message',
734
879
  messagePreviewChannel: 'messagePreviewChannel',
735
880
  messagePreviewSubChannel: 'messagePreviewSubChannel',
@@ -768,6 +913,7 @@ const PAYLOAD2MODEL = {
768
913
  viewers: 'viewer',
769
914
  eventResponses: 'eventResponse',
770
915
  products: 'product',
916
+ feedMetadata: 'feedMetadata',
771
917
  };
772
918
  /** hidden */
773
919
  const isOutdated = (prevData, nextData) => {
@@ -782,95 +928,6 @@ function getFutureDate(date = new Date().toISOString()) {
782
928
  return new Date(new Date(date).getTime() + 1).toISOString();
783
929
  }
784
930
 
785
- /* eslint-disable max-classes-per-file */
786
- /**
787
- * Generic ASC error
788
- * @category Errors
789
- */
790
- class ASCError extends Error {
791
- /**
792
- * @param message A custom error message
793
- * @param code A normalized error code
794
- * @param level A normalized failure level descriptor
795
- */
796
- constructor(message, code, level) {
797
- super(`Amity SDK (${code}): ${message}`);
798
- this.code = code;
799
- this.level = level;
800
- this.type = 'ASC';
801
- this.timestamp = Date.now();
802
- if (Error.captureStackTrace)
803
- Error.captureStackTrace(this, ASCError);
804
- }
805
- }
806
- /**
807
- * API level error
808
- * @category Errors
809
- */
810
- class ASCApiError extends ASCError {
811
- /**
812
- * @param code A normalized error code
813
- * @param level A normalized failure level descriptor
814
- */
815
- // eslint-disable-next-line no-useless-constructor
816
- constructor(message, code, level) {
817
- super(message, code, level);
818
- }
819
- }
820
- /**
821
- * Unexpected error
822
- * @category Errors
823
- */
824
- class ASCUnknownError extends ASCError {
825
- /**
826
- * @param code A normalized error code
827
- * @param level A normalized failure level descriptor
828
- */
829
- constructor(code = 800000 /* Amity.ClientError.UNKNOWN_ERROR */, level = "fatal" /* Amity.ErrorLevel.FATAL */) {
830
- super('Unexpected error', code, level);
831
- }
832
- }
833
- /**
834
- * Network related error
835
- * @category Errors
836
- */
837
- class ASCConnectionError extends ASCError {
838
- /**
839
- * @param message A custom error message
840
- */
841
- constructor(event, message = 'SDK client is having connection issues') {
842
- super(`${message} (${event})`, event === 'disconnected'
843
- ? 800211 /* Amity.ClientError.DISCONNECTED */
844
- : 800210 /* Amity.ClientError.CONNECTION_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
845
- this.event = event;
846
- }
847
- }
848
-
849
- let activeClient = null;
850
- /**
851
- * Get the active client
852
- *
853
- * @returns the active client instance
854
- *
855
- * @hidden
856
- */
857
- const getActiveClient = () => {
858
- if (!activeClient) {
859
- throw new ASCError('There is no active client', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "fatal" /* Amity.ErrorLevel.FATAL */);
860
- }
861
- return activeClient;
862
- };
863
- /**
864
- * Sets the active client
865
- *
866
- * @param client the client to assume as currently active client
867
- *
868
- * @hidden
869
- */
870
- const setActiveClient = (client) => {
871
- activeClient = client;
872
- };
873
-
874
931
  /**
875
932
  * ```js
876
933
  * import { enableCache } from '@amityco/ts-sdk'
@@ -1378,6 +1435,65 @@ const filterBySearchTerm = (collection, searchTerm) => {
1378
1435
  return m.user && ((_a = m.user.displayName) === null || _a === void 0 ? void 0 : _a.match(containsMatcher));
1379
1436
  });
1380
1437
  };
1438
+ /**
1439
+ * The ids of users in a block relationship with the current user — in BOTH
1440
+ * directions — derived synchronously from the local follow cache. For every
1441
+ * `status === 'blocked'` row that involves the current user, the OTHER party
1442
+ * is collected: `from === me` (users I blocked, outgoing) contributes `to`;
1443
+ * `to === me` (users who blocked me, incoming) contributes `from`.
1444
+ *
1445
+ * @returns a set of block-related user ids (both directions)
1446
+ *
1447
+ * @hidden
1448
+ */
1449
+ const getBlockUsersId = () => {
1450
+ var _a;
1451
+ const { userId } = getActiveClient();
1452
+ const ids = new Set();
1453
+ ((_a = queryCache(['follow', 'get'])) !== null && _a !== void 0 ? _a : [])
1454
+ .map(entry => entry.data)
1455
+ .filter(follow => (follow === null || follow === void 0 ? void 0 : follow.status) === 'blocked' && (follow.from === userId || follow.to === userId))
1456
+ .forEach(follow => {
1457
+ ids.add(follow.from === userId ? follow.to : follow.from);
1458
+ });
1459
+ return ids;
1460
+ };
1461
+ /**
1462
+ * Filter out posts whose author or any mentionee is in a block relationship
1463
+ * with the current user, in either direction (see {@link getBlockUsersId}).
1464
+ *
1465
+ * @param collection the post collection to filter
1466
+ * @returns a filtered collection excluding posts involving block-related users
1467
+ *
1468
+ * @hidden
1469
+ */
1470
+ const filterPostsByBlockUsers = (collection) => {
1471
+ const blockUsersId = getBlockUsersId();
1472
+ if (blockUsersId.size === 0)
1473
+ return collection;
1474
+ return collection.filter(post => {
1475
+ var _a, _b;
1476
+ if (blockUsersId.has(post.postedUserId))
1477
+ return false;
1478
+ const mentionedUserIds = (_b = (_a = post.mentionees) === null || _a === void 0 ? void 0 : _a.flatMap(mention => (mention.type === 'user' ? mention.userIds : []))) !== null && _b !== void 0 ? _b : [];
1479
+ return !mentionedUserIds.some(id => blockUsersId.has(id));
1480
+ });
1481
+ };
1482
+ /**
1483
+ * Filter out comments whose creator is in a block relationship with the
1484
+ * current user, in either direction (see {@link getBlockUsersId}).
1485
+ *
1486
+ * @param collection the comment collection to filter
1487
+ * @returns a filtered collection excluding comments from block-related users
1488
+ *
1489
+ * @hidden
1490
+ */
1491
+ const filterCommentsByBlockUsers = (collection) => {
1492
+ const blockUsersId = getBlockUsersId();
1493
+ if (blockUsersId.size === 0)
1494
+ return collection;
1495
+ return collection.filter(comment => !blockUsersId.has(comment.userId));
1496
+ };
1381
1497
 
1382
1498
  // Note:
1383
1499
  // this file should contain a suite of sorting utilities to help the
@@ -1848,13 +1964,13 @@ class NetworkActivitiesWatcher {
1848
1964
  this._listener.clear();
1849
1965
  }
1850
1966
  }
1851
- let instance$9;
1967
+ let instance$a;
1852
1968
  var NetworkActivitiesWatcher$1 = {
1853
1969
  getInstance: () => {
1854
- if (!instance$9) {
1855
- instance$9 = new NetworkActivitiesWatcher();
1970
+ if (!instance$a) {
1971
+ instance$a = new NetworkActivitiesWatcher();
1856
1972
  }
1857
- return instance$9;
1973
+ return instance$a;
1858
1974
  },
1859
1975
  };
1860
1976
 
@@ -4602,18 +4718,161 @@ walker=walker.next;}if(i===n&&walker!==null){return walker.value;}};Yallist.prot
4602
4718
  walker=walker.prev;}if(i===n&&walker!==null){return walker.value;}};Yallist.prototype.map=function(fn,thisp){thisp=thisp||this;var res=new Yallist();for(var walker=this.head;walker!==null;){res.push(fn.call(thisp,walker.value,this));walker=walker.next;}return res;};Yallist.prototype.mapReverse=function(fn,thisp){thisp=thisp||this;var res=new Yallist();for(var walker=this.tail;walker!==null;){res.push(fn.call(thisp,walker.value,this));walker=walker.prev;}return res;};Yallist.prototype.reduce=function(fn,initial){var acc;var walker=this.head;if(arguments.length>1){acc=initial;}else if(this.head){walker=this.head.next;acc=this.head.value;}else {throw new TypeError('Reduce of empty list with no initial value');}for(var i=0;walker!==null;i++){acc=fn(acc,walker.value,i);walker=walker.next;}return acc;};Yallist.prototype.reduceReverse=function(fn,initial){var acc;var walker=this.tail;if(arguments.length>1){acc=initial;}else if(this.tail){walker=this.tail.prev;acc=this.tail.value;}else {throw new TypeError('Reduce of empty list with no initial value');}for(var i=this.length-1;walker!==null;i--){acc=fn(acc,walker.value,i);walker=walker.prev;}return acc;};Yallist.prototype.toArray=function(){var arr=new Array(this.length);for(var i=0,walker=this.head;walker!==null;i++){arr[i]=walker.value;walker=walker.next;}return arr;};Yallist.prototype.toArrayReverse=function(){var arr=new Array(this.length);for(var i=0,walker=this.tail;walker!==null;i++){arr[i]=walker.value;walker=walker.prev;}return arr;};Yallist.prototype.slice=function(from,to){to=to||this.length;if(to<0){to+=this.length;}from=from||0;if(from<0){from+=this.length;}var ret=new Yallist();if(to<from||to<0){return ret;}if(from<0){from=0;}if(to>this.length){to=this.length;}for(var i=0,walker=this.head;walker!==null&&i<from;i++){walker=walker.next;}for(;walker!==null&&i<to;i++,walker=walker.next){ret.push(walker.value);}return ret;};Yallist.prototype.sliceReverse=function(from,to){to=to||this.length;if(to<0){to+=this.length;}from=from||0;if(from<0){from+=this.length;}var ret=new Yallist();if(to<from||to<0){return ret;}if(from<0){from=0;}if(to>this.length){to=this.length;}for(var i=this.length,walker=this.tail;walker!==null&&i>to;i--){walker=walker.prev;}for(;walker!==null&&i>from;i--,walker=walker.prev){ret.push(walker.value);}return ret;};Yallist.prototype.splice=function(start,deleteCount){if(start>this.length){start=this.length-1;}if(start<0){start=this.length+start;}for(var i=0,walker=this.head;walker!==null&&i<start;i++){walker=walker.next;}var ret=[];for(var i=0;walker&&i<deleteCount;i++){ret.push(walker.value);walker=this.removeNode(walker);}if(walker===null){walker=this.tail;}if(walker!==this.head&&walker!==this.tail){walker=walker.prev;}for(var i=0;i<(arguments.length<=2?0:arguments.length-2);i++){walker=insert(this,walker,i+2<2||arguments.length<=i+2?undefined:arguments[i+2]);}return ret;};Yallist.prototype.reverse=function(){var head=this.head;var tail=this.tail;for(var walker=head;walker!==null;walker=walker.prev){var p=walker.prev;walker.prev=walker.next;walker.next=p;}this.head=tail;this.tail=head;return this;};function insert(self,node,value){var inserted=node===self.head?new Node(value,null,node,self):new Node(value,node,node.next,self);if(inserted.next===null){self.tail=inserted;}if(inserted.prev===null){self.head=inserted;}self.length++;return inserted;}function push(self,item){self.tail=new Node(item,self.tail,null,self);if(!self.head){self.head=self.tail;}self.length++;}function unshift(self,item){self.head=new Node(item,null,self.head,self);if(!self.tail){self.tail=self.head;}self.length++;}function Node(value,prev,next,list){if(!(this instanceof Node)){return new Node(value,prev,next,list);}this.list=list;this.value=value;if(prev){prev.next=this;this.prev=prev;}else {this.prev=null;}if(next){next.prev=this;this.next=next;}else {this.next=null;}}try{// add if support for Symbol.iterator is present
4603
4719
  require('./iterator.js')(Yallist);}catch(er){}},{"./iterator.js":82}]},{},[12])(12);});})(mqtt$1);var mqtt = /*@__PURE__*/getDefaultExportFromCjs(mqtt$1.exports);
4604
4720
 
4721
+ class SessionWatcher {
4722
+ constructor() {
4723
+ this._sessionState = "notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */;
4724
+ this._listener = new Map();
4725
+ }
4726
+ onSessionStateChange(callback) {
4727
+ this._listener.set(callback, callback);
4728
+ return () => {
4729
+ this._listener.delete(callback);
4730
+ };
4731
+ }
4732
+ setSessionState(state, reason) {
4733
+ if (this._sessionState === state)
4734
+ return;
4735
+ this._sessionState = state;
4736
+ this._listener.forEach(cb => cb(state, reason));
4737
+ }
4738
+ destroy() {
4739
+ this._listener.clear();
4740
+ }
4741
+ }
4742
+ let instance$9;
4743
+ var SessionWatcher$1 = {
4744
+ getInstance: () => {
4745
+ if (!instance$9) {
4746
+ instance$9 = new SessionWatcher();
4747
+ }
4748
+ return instance$9;
4749
+ },
4750
+ };
4751
+
4752
+ /**
4753
+ * ```js
4754
+ * import { onSessionStateChange } from '@amityco/ts-sdk'
4755
+ * const dispose = onSessionStateChange((state: Amity.SessionStates) => {
4756
+ * // ...
4757
+ * })
4758
+ * ```
4759
+ *
4760
+ * Fired when any {@link Amity.Client} has a session state change
4761
+ *
4762
+ * @param callback The function to call when the event was fired
4763
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
4764
+ *
4765
+ * @category Client Events
4766
+ */
4767
+ const onSessionStateChange = (callback) => SessionWatcher$1.getInstance().onSessionStateChange(callback);
4768
+
4769
+ /** Feature-grouped real-time handles; all default-on, toggleable per handle. */
4770
+ var AutoSubscription;
4771
+ (function (AutoSubscription) {
4772
+ /** SMART_CHANNEL + SMART_MESSAGE + SMART_MESSAGE_FEED — chat "smart" real-time. */
4773
+ AutoSubscription["CHAT"] = "chat";
4774
+ /** Network-wide events (e.g. global ban). */
4775
+ AutoSubscription["NETWORK"] = "network";
4776
+ /** Livestream state events. */
4777
+ AutoSubscription["LIVESTREAM"] = "livestream";
4778
+ /** Both membership wildcards (followers + followings) — block real-time. */
4779
+ AutoSubscription["BLOCK"] = "block";
4780
+ })(AutoSubscription || (AutoSubscription = {}));
4781
+ const TOPICS = {
4782
+ [AutoSubscription.NETWORK]: [getNetworkTopic],
4783
+ [AutoSubscription.CHAT]: [
4784
+ getSmartFeedChannelTopic,
4785
+ getSmartFeedSubChannelTopic,
4786
+ getSmartFeedMessageTopic,
4787
+ ],
4788
+ [AutoSubscription.LIVESTREAM]: [getLiveStreamTopic],
4789
+ [AutoSubscription.BLOCK]: [getMyFollowersTopic, getMyFollowingsTopic],
4790
+ };
4791
+ const DEFAULT_TOPICS = [
4792
+ AutoSubscription.CHAT,
4793
+ AutoSubscription.NETWORK,
4794
+ AutoSubscription.LIVESTREAM,
4795
+ AutoSubscription.BLOCK,
4796
+ ];
4797
+ const ALL_FEATURES = Object.values(AutoSubscription);
4798
+ /** Ref-counted, reconnect-resilient registry of the managed auto-subscriptions. */
4799
+ class AutoSubscriptionManager {
4800
+ constructor() {
4801
+ this.refCountByFeature = new Map();
4802
+ this.disposers = new Map();
4803
+ this.seed();
4804
+ }
4805
+ seed() {
4806
+ this.refCountByFeature.clear();
4807
+ DEFAULT_TOPICS.forEach(feature => this.refCountByFeature.set(feature, 1));
4808
+ }
4809
+ isActive(feature) {
4810
+ var _a;
4811
+ return ((_a = this.refCountByFeature.get(feature)) !== null && _a !== void 0 ? _a : 0) > 0;
4812
+ }
4813
+ subscribeTopics(feature) {
4814
+ this.unsubscribeTopics(feature);
4815
+ this.disposers.set(feature, TOPICS[feature].map(buildTopic => subscribeTopic(buildTopic())));
4816
+ }
4817
+ unsubscribeTopics(feature) {
4818
+ var _a;
4819
+ ((_a = this.disposers.get(feature)) !== null && _a !== void 0 ? _a : []).forEach(dispose => dispose());
4820
+ this.disposers.delete(feature);
4821
+ }
4822
+ /** Subscribe every enabled handle's topics, converging the broker to the registry. Called on each (re)connect. */
4823
+ initialize() {
4824
+ ALL_FEATURES.forEach(feature => {
4825
+ if (this.isActive(feature))
4826
+ this.subscribeTopics(feature);
4827
+ });
4828
+ }
4829
+ subscribe(feature) {
4830
+ var _a;
4831
+ const next = ((_a = this.refCountByFeature.get(feature)) !== null && _a !== void 0 ? _a : 0) + 1;
4832
+ this.refCountByFeature.set(feature, next);
4833
+ if (next === 1)
4834
+ this.subscribeTopics(feature);
4835
+ }
4836
+ unsubscribe(feature) {
4837
+ var _a;
4838
+ const next = Math.max(0, ((_a = this.refCountByFeature.get(feature)) !== null && _a !== void 0 ? _a : 0) - 1);
4839
+ this.refCountByFeature.set(feature, next);
4840
+ if (next === 0)
4841
+ this.unsubscribeTopics(feature);
4842
+ }
4843
+ subscriptions() {
4844
+ return ALL_FEATURES.map(feature => ({
4845
+ feature,
4846
+ isActive: this.isActive(feature),
4847
+ isSystem: true,
4848
+ topicCount: TOPICS[feature].length,
4849
+ }));
4850
+ }
4851
+ reset() {
4852
+ ALL_FEATURES.forEach(feature => this.unsubscribeTopics(feature));
4853
+ this.disposers.clear();
4854
+ this.seed();
4855
+ }
4856
+ }
4857
+ let instance$8 = null;
4858
+ const getAutoSubscriptionManager = () => {
4859
+ if (!instance$8)
4860
+ instance$8 = new AutoSubscriptionManager();
4861
+ return instance$8;
4862
+ };
4863
+ /** Resets the registry to its default baseline when the session ends. */
4864
+ const resetAutoSubscriptionsOnLogout = () => onSessionStateChange(state => {
4865
+ if (state !== "established" /* Amity.SessionStates.ESTABLISHED */)
4866
+ getAutoSubscriptionManager().reset();
4867
+ });
4868
+
4869
+ /**
4870
+ * (Re)subscribes the managed auto-subscription registry on every (re)connect.
4871
+ * The hardcoded topic list was promoted to the toggleable, ref-counted registry
4872
+ * in {@link getAutoSubscriptionManager} — see `client.manageAutoSubscriptions`.
4873
+ */
4605
4874
  const subscribeGlobalTopic = () => {
4606
- const disposers = [
4607
- subscribeTopic(getNetworkTopic()),
4608
- subscribeTopic(getSmartFeedChannelTopic()),
4609
- subscribeTopic(getSmartFeedSubChannelTopic()),
4610
- subscribeTopic(getSmartFeedMessageTopic()),
4611
- // subscribing to user topic is necessary to handle ban event
4612
- subscribeTopic(getUserTopic(getActiveUser())),
4613
- subscribeTopic(getMarkerUserFeedTopic()),
4614
- subscribeTopic(getLiveStreamTopic()),
4615
- ];
4616
- return () => disposers.forEach(fn => fn());
4875
+ getAutoSubscriptionManager().initialize();
4617
4876
  };
4618
4877
 
4619
4878
  class OnMemoryStorage {
@@ -5133,8 +5392,12 @@ const getChannelMessagePreviewWithUser = (channel) => {
5133
5392
  return Object.assign(Object.assign({}, channel), { messagePreview: messagePreviewWithUser });
5134
5393
  };
5135
5394
 
5395
+ const convertDateStringToTimestamp = (dateString) => {
5396
+ return new Date(dateString).getTime();
5397
+ };
5398
+
5136
5399
  const updateChannelMessagePreviewCache = (rawPayload) => {
5137
- var _a, _b;
5400
+ var _a;
5138
5401
  const withMessageFeedInfo = (messagePreview) => {
5139
5402
  var _a;
5140
5403
  const messageFeedInfo = (_a = rawPayload.messageFeedsInfo) === null || _a === void 0 ? void 0 : _a.find(messageFeed => {
@@ -5156,10 +5419,26 @@ const updateChannelMessagePreviewCache = (rawPayload) => {
5156
5419
  subChannelUpdatedAt: messageFeedInfo === null || messageFeedInfo === void 0 ? void 0 : messageFeedInfo.updatedAt,
5157
5420
  };
5158
5421
  };
5159
- const newData = {
5160
- messagePreviewChannel: (_b = (_a = rawPayload.messagePreviews) === null || _a === void 0 ? void 0 : _a.map(messagePreview => withMessageFeedInfo(messagePreview))) !== null && _b !== void 0 ? _b : [],
5161
- };
5162
- ingestInCache(newData);
5422
+ // Skip server previews older than what's cached — the cache may carry a newer
5423
+ // preview written by handleMessageCreated from an MQTT message that the server
5424
+ // payload hasn't surfaced yet. Mirrors isLastestMessageOnChannel.
5425
+ const newPreviews = ((_a = rawPayload.messagePreviews) !== null && _a !== void 0 ? _a : [])
5426
+ .map(withMessageFeedInfo)
5427
+ .filter(preview => {
5428
+ var _a;
5429
+ const cached = (_a = pullFromCache([
5430
+ 'messagePreviewChannel',
5431
+ 'get',
5432
+ preview.channelId,
5433
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5434
+ if (!cached)
5435
+ return true;
5436
+ return (convertDateStringToTimestamp(cached.createdAt) <=
5437
+ convertDateStringToTimestamp(preview.createdAt));
5438
+ });
5439
+ if (newPreviews.length === 0)
5440
+ return;
5441
+ ingestInCache({ messagePreviewChannel: newPreviews });
5163
5442
  };
5164
5443
 
5165
5444
  const getSubChannelMessagePreview = (subChannelId) => {
@@ -5787,10 +6066,6 @@ getSubChannel$1.locally = (subChannelId) => {
5787
6066
  };
5788
6067
  };
5789
6068
 
5790
- const convertDateStringToTimestamp = (dateString) => {
5791
- return new Date(dateString).getTime();
5792
- };
5793
-
5794
6069
  const getMessagePreviewSetting$1 = async () => {
5795
6070
  const client = getActiveClient();
5796
6071
  return client.getMessagePreviewSetting(false);
@@ -5998,24 +6273,41 @@ const preUpdateChannelCache = (rawPayload, options = { isMessagePreviewUpdated:
5998
6273
  });
5999
6274
  };
6000
6275
  const updateChannelUnread = ({ currentUserId, channels, channelUsers, }) => {
6276
+ var _a, _b;
6001
6277
  const channelsUnread = [];
6002
6278
  for (let i = 0; i < channels.length; i += 1) {
6003
6279
  if (isUnreadCountSupport(channels[i])) {
6004
6280
  const cacheKey = ['channelUnread', 'get', channels[i].channelId];
6005
6281
  const channelUser = channelUsers.find(channelUser => channelUser.channelId === channels[i].channelId && channelUser.userId === currentUserId);
6006
- let unreadCount = 0;
6282
+ // readToSegment, lastMentionedSegment and lastSegment are monotonically non-decreasing;
6283
+ // prefer cached values when ahead of the server so a refetch returning stale data cannot
6284
+ const cached = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
6285
+ const lastSegment = Math.max((_b = cached === null || cached === void 0 ? void 0 : cached.lastSegment) !== null && _b !== void 0 ? _b : 0, channels[i].messageCount);
6007
6286
  let readToSegment = null;
6008
6287
  let lastMentionedSegment = null;
6288
+ let unreadCount = 0;
6009
6289
  let isMentioned = false;
6010
6290
  if (channelUser) {
6011
- readToSegment = channelUser.readToSegment;
6012
- lastMentionedSegment = channelUser.lastMentionedSegment;
6013
- unreadCount = Math.max(channels[i].messageCount - readToSegment, 0);
6014
- isMentioned = lastMentionedSegment > readToSegment;
6291
+ const serverRead = channelUser.readToSegment;
6292
+ const serverMention = channelUser.lastMentionedSegment;
6293
+ readToSegment =
6294
+ typeof (cached === null || cached === void 0 ? void 0 : cached.readToSegment) === 'number' &&
6295
+ (typeof serverRead !== 'number' || cached.readToSegment > serverRead)
6296
+ ? cached.readToSegment
6297
+ : serverRead !== null && serverRead !== void 0 ? serverRead : null;
6298
+ lastMentionedSegment =
6299
+ typeof (cached === null || cached === void 0 ? void 0 : cached.lastMentionedSegment) === 'number' &&
6300
+ (typeof serverMention !== 'number' || cached.lastMentionedSegment > serverMention)
6301
+ ? cached.lastMentionedSegment
6302
+ : serverMention !== null && serverMention !== void 0 ? serverMention : null;
6303
+ const readForCalc = readToSegment !== null && readToSegment !== void 0 ? readToSegment : 0;
6304
+ unreadCount = Math.max(lastSegment - readForCalc, 0);
6305
+ isMentioned =
6306
+ typeof lastMentionedSegment === 'number' && readForCalc < lastMentionedSegment;
6015
6307
  }
6016
6308
  const cacheChannelUnread = {
6017
6309
  channelId: channels[i].channelId,
6018
- lastSegment: channels[i].messageCount,
6310
+ lastSegment,
6019
6311
  readToSegment,
6020
6312
  lastMentionedSegment,
6021
6313
  unreadCount,
@@ -6025,6 +6317,8 @@ const updateChannelUnread = ({ currentUserId, channels, channelUsers, }) => {
6025
6317
  pushToCache(cacheKey, cacheChannelUnread);
6026
6318
  channelsUnread.push(cacheChannelUnread);
6027
6319
  }
6320
+ }
6321
+ if (channelsUnread.length > 0) {
6028
6322
  fireEvent('local.channelUnread.updated', channelsUnread);
6029
6323
  }
6030
6324
  };
@@ -6724,7 +7018,7 @@ const onChannelMemberRoleRemoved = (callback) => {
6724
7018
  const client = getActiveClient();
6725
7019
  const filter = async (payload) => {
6726
7020
  const { channels, channelUsers } = payload;
6727
- callback(channels[0], channelUsers.find(channelUser => channelUser.membership === 'member'));
7021
+ callbacks$1.forEach(cb => cb(channels[0], channelUsers.find(channelUser => channelUser.membership === 'member')));
6728
7022
  };
6729
7023
  mainDisposer$1 = createEventSubscriber(client, 'onChannelMemberRoleRemoved', 'local.channel-moderator.role-removed', filter);
6730
7024
  }
@@ -6732,6 +7026,39 @@ const onChannelMemberRoleRemoved = (callback) => {
6732
7026
  return () => dispose$1(callback);
6733
7027
  };
6734
7028
 
7029
+ /**
7030
+ * Fired when a {@link Amity.Channel} has been archived by the active user.
7031
+ *
7032
+ * @param callback The function to call when the event was fired
7033
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
7034
+ *
7035
+ * @category Channel Events
7036
+ */
7037
+ const onChannelArchived = (callback) => {
7038
+ const client = getActiveClient();
7039
+ const filter = async (payload) => {
7040
+ callback(payload);
7041
+ };
7042
+ return createEventSubscriber(client, 'onChannelArchived', 'local.channel.archived', filter);
7043
+ };
7044
+
7045
+ /**
7046
+ * Fired when a previously archived {@link Amity.Channel} has been unarchived
7047
+ * by the active user.
7048
+ *
7049
+ * @param callback The function to call when the event was fired
7050
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
7051
+ *
7052
+ * @category Channel Events
7053
+ */
7054
+ const onChannelUnarchived = (callback) => {
7055
+ const client = getActiveClient();
7056
+ const filter = async (payload) => {
7057
+ callback(payload);
7058
+ };
7059
+ return createEventSubscriber(client, 'onChannelUnarchived', 'local.channel.unarchived', filter);
7060
+ };
7061
+
6735
7062
  const callbacks = [];
6736
7063
  let mainDisposer = null;
6737
7064
  const dispose = (cb) => {
@@ -6845,6 +7172,17 @@ const channelLinkedObject = (channel) => {
6845
7172
  markAsRead: () => markAsRead(channel.channelInternalId),
6846
7173
  previewMembers,
6847
7174
  myMembership: (callback) => getMyMembership(channel.channelId, callback),
7175
+ get avatar() {
7176
+ var _a;
7177
+ if (!channel.avatarFileId)
7178
+ return undefined;
7179
+ const avatar = (_a = pullFromCache([
7180
+ 'file',
7181
+ 'get',
7182
+ `${channel.avatarFileId}`,
7183
+ ])) === null || _a === void 0 ? void 0 : _a.data;
7184
+ return avatar;
7185
+ },
6848
7186
  });
6849
7187
  };
6850
7188
 
@@ -6943,54 +7281,6 @@ getChannelByIds$1.locally = (channelIds) => {
6943
7281
  };
6944
7282
  };
6945
7283
 
6946
- class SessionWatcher {
6947
- constructor() {
6948
- this._sessionState = "notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */;
6949
- this._listener = new Map();
6950
- }
6951
- onSessionStateChange(callback) {
6952
- this._listener.set(callback, callback);
6953
- return () => {
6954
- this._listener.delete(callback);
6955
- };
6956
- }
6957
- setSessionState(state, reason) {
6958
- if (this._sessionState === state)
6959
- return;
6960
- this._sessionState = state;
6961
- this._listener.forEach(cb => cb(state, reason));
6962
- }
6963
- destroy() {
6964
- this._listener.clear();
6965
- }
6966
- }
6967
- let instance$8;
6968
- var SessionWatcher$1 = {
6969
- getInstance: () => {
6970
- if (!instance$8) {
6971
- instance$8 = new SessionWatcher();
6972
- }
6973
- return instance$8;
6974
- },
6975
- };
6976
-
6977
- /**
6978
- * ```js
6979
- * import { onSessionStateChange } from '@amityco/ts-sdk'
6980
- * const dispose = onSessionStateChange((state: Amity.SessionStates) => {
6981
- * // ...
6982
- * })
6983
- * ```
6984
- *
6985
- * Fired when any {@link Amity.Client} has a session state change
6986
- *
6987
- * @param callback The function to call when the event was fired
6988
- * @returns an {@link Amity.Unsubscriber} function to stop listening
6989
- *
6990
- * @category Client Events
6991
- */
6992
- const onSessionStateChange = (callback) => SessionWatcher$1.getInstance().onSessionStateChange(callback);
6993
-
6994
7284
  const setIntervalTask = (handler, timeout) => {
6995
7285
  const timer = setInterval(handler, timeout);
6996
7286
  return () => clearInterval(timer);
@@ -7784,7 +8074,7 @@ class AnalyticsEventSyncer {
7784
8074
 
7785
8075
  class AnalyticsEventCapturer {
7786
8076
  constructor() {
7787
- this._expireTime = 5 * MINUTE;
8077
+ this._expireTime = 5 * SECOND$1;
7788
8078
  this._poolLimit = 1000;
7789
8079
  this._recentViewed = {};
7790
8080
  this._recentHighPriorityViewed = {};
@@ -7838,12 +8128,36 @@ class AnalyticsEventCapturer {
7838
8128
  }
7839
8129
  markPostAsViewed(postId) {
7840
8130
  this.markAs({
7841
- uniqueId: postId,
8131
+ uniqueId: `post.${postId}`,
7842
8132
  contentId: postId,
7843
8133
  contentType: "post" /* Amity.AnalyticEventContentType.Post */,
7844
8134
  activityType: "view" /* Amity.AnalyticEventActivityType.View */,
7845
8135
  });
7846
8136
  }
8137
+ markPostAsMeaningfullyViewed(postId, feedRenderPosition) {
8138
+ var _a;
8139
+ const cached = (_a = pullFromCache(['feedMetadata', 'get', postId])) === null || _a === void 0 ? void 0 : _a.data;
8140
+ const metadata = {};
8141
+ if (feedRenderPosition !== undefined)
8142
+ metadata.feedRenderPosition = feedRenderPosition;
8143
+ if (cached) {
8144
+ metadata.feedSnapshotPosition = cached.feedSnapshotPosition;
8145
+ metadata.feedInjectionType = cached.feedInjectionType;
8146
+ metadata.feedRelevanceScore = cached.feedRelevanceScore;
8147
+ metadata.feedPopularityScore = cached.feedPopularityScore;
8148
+ metadata.feedFreshnessScore = cached.feedFreshnessScore;
8149
+ metadata.feedAffinityScore = cached.feedAffinityScore;
8150
+ metadata.feedFinalScore = cached.feedFinalScore;
8151
+ metadata.feedMmrPenalty = cached.feedMmrPenalty;
8152
+ }
8153
+ this.markAs({
8154
+ uniqueId: `post.${postId}.meaningfulView`,
8155
+ contentId: postId,
8156
+ contentType: "post" /* Amity.AnalyticEventContentType.Post */,
8157
+ activityType: "meaningfulView" /* Amity.AnalyticEventActivityType.MeaningfulView */,
8158
+ metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
8159
+ });
8160
+ }
7847
8161
  markStory(story, activityType) {
7848
8162
  if (!story.expiresAt)
7849
8163
  return;
@@ -7983,6 +8297,12 @@ class AnalyticsEngine {
7983
8297
  this._eventCapturer.markPostAsViewed(postId);
7984
8298
  }
7985
8299
  }
8300
+ markPostAsMeaningfullyViewed(postId, feedRenderPosition) {
8301
+ if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
8302
+ this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
8303
+ this._eventCapturer.markPostAsMeaningfullyViewed(postId, feedRenderPosition);
8304
+ }
8305
+ }
7986
8306
  markStoryAsViewed(story) {
7987
8307
  if (this._client.sessionState === "established" /* Amity.SessionStates.ESTABLISHED */ ||
7988
8308
  this._client.sessionState === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */ // For case token_expired, we assume token is expired and gonna re-connect soon
@@ -8207,9 +8527,8 @@ class MessageReadReceiptSyncEngine {
8207
8527
  // Step 1: Optimistic update of channelUnread.readToSegment to message.segment and update unreadCount value
8208
8528
  const cacheKey = ['channelUnread', 'get', channelId];
8209
8529
  const channelUnread = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
8210
- if (typeof (channelUnread === null || channelUnread === void 0 ? void 0 : channelUnread.readToSegment) === 'number' &&
8211
- channelUnread &&
8212
- segment > channelUnread.readToSegment) {
8530
+ if (channelUnread &&
8531
+ (typeof channelUnread.readToSegment !== 'number' || segment > channelUnread.readToSegment)) {
8213
8532
  channelUnread.readToSegment = segment;
8214
8533
  channelUnread.unreadCount = Math.max(channelUnread.lastSegment - segment, 0);
8215
8534
  pushToCache(cacheKey, channelUnread);
@@ -9103,6 +9422,59 @@ var blockedUserSyncEngineOnLoginHandler = () => {
9103
9422
  };
9104
9423
  };
9105
9424
 
9425
+ class CursorController {
9426
+ constructor(networkId, userId) {
9427
+ this.networkId = networkId;
9428
+ this.userId = userId;
9429
+ }
9430
+ static current() {
9431
+ try {
9432
+ const user = getCurrentUser();
9433
+ if (!user)
9434
+ return null;
9435
+ const networkId = getNetworkId(user);
9436
+ const { userId } = user;
9437
+ return networkId && userId ? new CursorController(networkId, userId) : null;
9438
+ }
9439
+ catch (_a) {
9440
+ return null;
9441
+ }
9442
+ }
9443
+ static isExpired(expiredAt) {
9444
+ return Date.now() >= expiredAt;
9445
+ }
9446
+ static clearOnLogout() {
9447
+ return onSessionStateChange(state => {
9448
+ var _a;
9449
+ if (state === "terminated" /* Amity.SessionStates.TERMINATED */)
9450
+ (_a = CursorController.current()) === null || _a === void 0 ? void 0 : _a.clear();
9451
+ });
9452
+ }
9453
+ get key() {
9454
+ return `amity:forYouFeed:cursor:${this.networkId}:${this.userId}`;
9455
+ }
9456
+ async get() {
9457
+ const raw = await getItem(this.key);
9458
+ if (!raw)
9459
+ return null;
9460
+ try {
9461
+ const parsed = JSON.parse(raw);
9462
+ if (typeof (parsed === null || parsed === void 0 ? void 0 : parsed.cursor) !== 'string' || typeof (parsed === null || parsed === void 0 ? void 0 : parsed.expiredAt) !== 'number')
9463
+ return null;
9464
+ return { cursor: parsed.cursor, expiredAt: parsed.expiredAt };
9465
+ }
9466
+ catch (_a) {
9467
+ return null;
9468
+ }
9469
+ }
9470
+ async set(value) {
9471
+ await setItem(this.key, JSON.stringify(value));
9472
+ }
9473
+ async clear() {
9474
+ await setItem(this.key, '');
9475
+ }
9476
+ }
9477
+
9106
9478
  const EVENTS = [
9107
9479
  'disconnected',
9108
9480
  'error',
@@ -9292,7 +9664,7 @@ const setupLoginSubscriptions = (unsubWatcher) => {
9292
9664
  // NOTE: This is a temporary solution to handle the channel marker when the user is forced to leave
9293
9665
  // the channel because currently backend can't handle this, so every time a user is banned from
9294
9666
  // a channel or the channel is deleted the channel's unread count will not be reset to zero
9295
- onChannelDeleted(removeChannelMarkerCache), onChannelMemberBanned(removeChannelMarkerCache), markReadEngineOnLoginHandler(), analyticsEngineOnLoginHandler(), objectResolverEngineOnLoginHandler(), reactionSyncEngineOnLoginHandler(), blockedUserSyncEngineOnLoginHandler());
9667
+ onChannelDeleted(removeChannelMarkerCache), onChannelMemberBanned(removeChannelMarkerCache), markReadEngineOnLoginHandler(), analyticsEngineOnLoginHandler(), objectResolverEngineOnLoginHandler(), reactionSyncEngineOnLoginHandler(), blockedUserSyncEngineOnLoginHandler(), resetAutoSubscriptionsOnLogout(), CursorController.clearOnLogout());
9296
9668
  if (client.useLegacyUnreadCount) {
9297
9669
  subscriptions.push(readReceiptSyncEngineOnLoginHandler());
9298
9670
  }
@@ -9991,16 +10363,13 @@ const onMessageCreatedMqtt = (callback) => {
9991
10363
  }
9992
10364
  if (client.useLegacyUnreadCount) {
9993
10365
  rawPayload.messages.forEach(message => {
9994
- var _a, _b;
10366
+ var _a, _b, _c;
9995
10367
  const channelUnread = (_a = pullFromCache([
9996
10368
  'channelUnread',
9997
10369
  'get',
9998
10370
  message.channelId,
9999
10371
  ])) === null || _a === void 0 ? void 0 : _a.data;
10000
- if (!channelUnread ||
10001
- channelUnread.lastSegment >= message.segment ||
10002
- typeof channelUnread.readToSegment !== 'number' ||
10003
- typeof channelUnread.lastMentionedSegment !== 'number')
10372
+ if (!channelUnread || channelUnread.lastSegment >= message.segment)
10004
10373
  return;
10005
10374
  const lastSegment = message.segment;
10006
10375
  const isMentionedInMessage = (_b = message.mentionedUsers) === null || _b === void 0 ? void 0 : _b.some(mention => {
@@ -10012,7 +10381,8 @@ const onMessageCreatedMqtt = (callback) => {
10012
10381
  const lastMentionedSegment = isMentionedInMessage
10013
10382
  ? message.segment
10014
10383
  : channelUnread.lastMentionedSegment;
10015
- const updatedChannelUnread = Object.assign(Object.assign({}, channelUnread), { lastSegment, unreadCount: Math.max(lastSegment - channelUnread.readToSegment, 0), lastMentionedSegment, isMentioned: !(channelUnread.readToSegment >= lastMentionedSegment) });
10384
+ const readToSegment = (_c = channelUnread.readToSegment) !== null && _c !== void 0 ? _c : 0;
10385
+ const updatedChannelUnread = Object.assign(Object.assign({}, channelUnread), { lastSegment, unreadCount: Math.max(lastSegment - readToSegment, 0), lastMentionedSegment, isMentioned: typeof lastMentionedSegment === 'number' && readToSegment < lastMentionedSegment });
10016
10386
  pushToCache(['channelUnread', 'get', message.channelId], updatedChannelUnread);
10017
10387
  fireEvent('local.channelUnread.updated', [updatedChannelUnread]);
10018
10388
  });
@@ -10650,11 +11020,18 @@ const getLinkPreviewMetadata = async (url) => {
10650
11020
  return data;
10651
11021
  };
10652
11022
 
11023
+ const CONTENT_TYPE_CONFIG = {
11024
+ [exports.AmitySharableContentType.POST]: { key: 'posts', placeholder: 'postId' },
11025
+ [exports.AmitySharableContentType.COMMUNITY]: { key: 'communities', placeholder: 'communityId' },
11026
+ [exports.AmitySharableContentType.USER]: { key: 'users', placeholder: 'userId' },
11027
+ [exports.AmitySharableContentType.LIVESTREAM]: { key: 'livestream', placeholder: 'livestream' },
11028
+ [exports.AmitySharableContentType.EVENT]: { key: 'events', placeholder: 'eventId' },
11029
+ };
10653
11030
  /**
10654
11031
  * ```js
10655
11032
  * import Client from '@amityco/ts-sdk'
10656
- * const shareableLinkConfiguration = await Client.getShareableLinkConfiguration()
10657
- * const postLinkPattern = shareableLinkConfiguration.post
11033
+ * const config = await Client.getShareableLinkConfiguration()
11034
+ * const link = config.generateLink(AmitySharableContentType.EVENT, eventId)
10658
11035
  * ```
10659
11036
  *
10660
11037
  * Fetches a {@link Amity.ShareableLinkConfiguration} object
@@ -10665,9 +11042,29 @@ const getLinkPreviewMetadata = async (url) => {
10665
11042
  * @async
10666
11043
  */
10667
11044
  const getShareableLinkConfiguration = async () => {
11045
+ var _a, _b;
10668
11046
  const client = getActiveClient();
10669
11047
  const { data } = await client.http.get(`/api/v3/network-settings/shareable-deep-links`);
10670
- return data;
11048
+ const domain = (_a = data.domain) !== null && _a !== void 0 ? _a : '';
11049
+ const patterns = (_b = data.patterns) !== null && _b !== void 0 ? _b : {};
11050
+ return {
11051
+ domain,
11052
+ patterns,
11053
+ isEnabled(contentType) {
11054
+ const { key } = CONTENT_TYPE_CONFIG[contentType];
11055
+ return !!domain && !!patterns[key];
11056
+ },
11057
+ getPattern(contentType) {
11058
+ const { key } = CONTENT_TYPE_CONFIG[contentType];
11059
+ return patterns[key] || null;
11060
+ },
11061
+ generateLink(contentType, referenceId) {
11062
+ const { key, placeholder } = CONTENT_TYPE_CONFIG[contentType];
11063
+ if (!domain || !patterns[key])
11064
+ return null;
11065
+ return domain + patterns[key].replace(`{${placeholder}}`, referenceId);
11066
+ },
11067
+ };
10671
11068
  };
10672
11069
 
10673
11070
  /**
@@ -10858,6 +11255,205 @@ const setAccessTokenHandler = (accessTokenHandler) => {
10858
11255
  client.accessTokenHandler = accessTokenHandler;
10859
11256
  };
10860
11257
 
11258
+ function parseRolesFilter(listenFromRoleIds, ignoreFromRoleIds) {
11259
+ if (ignoreFromRoleIds && ignoreFromRoleIds.length > 0) {
11260
+ return { type: 'not', roleIds: ignoreFromRoleIds };
11261
+ }
11262
+ if (listenFromRoleIds && listenFromRoleIds.length > 0) {
11263
+ return { type: exports.NotificationRolesFilterTypeEnum.ONLY, roleIds: listenFromRoleIds };
11264
+ }
11265
+ return { type: exports.NotificationRolesFilterTypeEnum.ALL };
11266
+ }
11267
+ function serializeRolesFilter(rolesFilter) {
11268
+ if ((rolesFilter === null || rolesFilter === void 0 ? void 0 : rolesFilter.type) === exports.NotificationRolesFilterTypeEnum.ONLY) {
11269
+ return { listenFromRoleIds: rolesFilter.roleIds };
11270
+ }
11271
+ return { listenFromRoleIds: [] };
11272
+ }
11273
+ class ChannelNotifications {
11274
+ constructor(channelId) {
11275
+ this.channelId = channelId;
11276
+ }
11277
+ async enable() {
11278
+ const client = getActiveClient();
11279
+ const body = {
11280
+ level: exports.NotificationSettingsLevelEnum.CHANNEL,
11281
+ channelId: this.channelId,
11282
+ isPushNotifiable: true,
11283
+ };
11284
+ await client.http.post('/api/v3/notification/setting', body);
11285
+ }
11286
+ async disable() {
11287
+ const client = getActiveClient();
11288
+ const body = {
11289
+ level: exports.NotificationSettingsLevelEnum.CHANNEL,
11290
+ channelId: this.channelId,
11291
+ isPushNotifiable: false,
11292
+ };
11293
+ await client.http.post('/api/v3/notification/setting', body);
11294
+ }
11295
+ async getSettings() {
11296
+ const client = getActiveClient();
11297
+ const { data } = await client.http.get(`/api/v3/notification/setting?level=${exports.NotificationSettingsLevelEnum.CHANNEL}&channelId=${encodeURIComponent(this.channelId)}`);
11298
+ return { isEnabled: data.isPushNotifiable };
11299
+ }
11300
+ }
11301
+ class UserNotifications {
11302
+ async enable(modules) {
11303
+ var _a;
11304
+ const client = getActiveClient();
11305
+ const notifiableEvents = (_a = modules === null || modules === void 0 ? void 0 : modules.map(module => (Object.assign({ moduleName: module.moduleName, isPushNotifiable: module.isEnabled }, serializeRolesFilter(module.rolesFilter))))) !== null && _a !== void 0 ? _a : [];
11306
+ const body = {
11307
+ level: exports.NotificationSettingsLevelEnum.USER,
11308
+ isPushNotifiable: true,
11309
+ notifiableEvents,
11310
+ };
11311
+ await client.http.post('/api/v3/notification/setting', body);
11312
+ }
11313
+ async disableAllNotifications() {
11314
+ const client = getActiveClient();
11315
+ const body = {
11316
+ level: exports.NotificationSettingsLevelEnum.USER,
11317
+ isPushNotifiable: false,
11318
+ notifiableEvents: [],
11319
+ };
11320
+ await client.http.post('/api/v3/notification/setting', body);
11321
+ }
11322
+ async getSettings() {
11323
+ var _a;
11324
+ const client = getActiveClient();
11325
+ const { data } = await client.http.get(`/api/v3/notification/setting?level=${exports.NotificationSettingsLevelEnum.USER}`);
11326
+ const validModuleNames = Object.values(exports.UserNotificationModuleNameEnum);
11327
+ const modules = ((_a = data.notifiableEvents) !== null && _a !== void 0 ? _a : [])
11328
+ .filter(e => e.moduleName != null && validModuleNames.includes(e.moduleName))
11329
+ .map(e => ({
11330
+ moduleName: e.moduleName,
11331
+ isEnabled: e.isPushNotifiable,
11332
+ rolesFilter: parseRolesFilter(e.listenFromRoleIds, e.ignoreFromRoleIds),
11333
+ }));
11334
+ return { isEnabled: data.isPushNotifiable, modules };
11335
+ }
11336
+ }
11337
+ class CommunityNotifications {
11338
+ constructor(communityId) {
11339
+ this.communityId = communityId;
11340
+ }
11341
+ async enable(events) {
11342
+ var _a;
11343
+ const client = getActiveClient();
11344
+ const notifiableEvents = (_a = events === null || events === void 0 ? void 0 : events.map(event => (Object.assign({ moduleName: exports.UserNotificationModuleNameEnum.SOCIAL, name: event.eventName, isPushNotifiable: event.isEnabled }, serializeRolesFilter(event.rolesFilter))))) !== null && _a !== void 0 ? _a : [];
11345
+ const body = {
11346
+ level: exports.NotificationSettingsLevelEnum.COMMUNITY,
11347
+ communityId: this.communityId,
11348
+ isPushNotifiable: true,
11349
+ notifiableEvents,
11350
+ };
11351
+ await client.http.post('/api/v3/notification/setting', body);
11352
+ }
11353
+ async disable() {
11354
+ const client = getActiveClient();
11355
+ const body = {
11356
+ level: exports.NotificationSettingsLevelEnum.COMMUNITY,
11357
+ communityId: this.communityId,
11358
+ isPushNotifiable: false,
11359
+ notifiableEvents: [],
11360
+ };
11361
+ await client.http.post('/api/v3/notification/setting', body);
11362
+ }
11363
+ async getSettings() {
11364
+ var _a;
11365
+ const client = getActiveClient();
11366
+ const { data } = await client.http.get(`/api/v3/notification/setting?level=${exports.NotificationSettingsLevelEnum.COMMUNITY}&communityId=${encodeURIComponent(this.communityId)}`);
11367
+ const validEventNames = Object.values(exports.CommunityNotificationEventNameEnum);
11368
+ const events = ((_a = data.notifiableEvents) !== null && _a !== void 0 ? _a : [])
11369
+ .filter(e => e.name != null && validEventNames.includes(e.name))
11370
+ .map(e => ({
11371
+ eventName: e.name,
11372
+ isEnabled: e.isPushNotifiable,
11373
+ isNetworkEnabled: e.isNetworkEnabled,
11374
+ rolesFilter: parseRolesFilter(e.listenFromRoleIds, e.ignoreFromRoleIds),
11375
+ }));
11376
+ return { isEnabled: data.isPushNotifiable, events };
11377
+ }
11378
+ }
11379
+ class Notifications {
11380
+ user() {
11381
+ return new UserNotifications();
11382
+ }
11383
+ community(communityId) {
11384
+ return new CommunityNotifications(communityId);
11385
+ }
11386
+ channel(channelId) {
11387
+ return new ChannelNotifications(channelId);
11388
+ }
11389
+ }
11390
+ const notifications = () => new Notifications();
11391
+
11392
+ /* begin_public_function
11393
+ id: client.enable_auto_subscriptions
11394
+ */
11395
+ /**
11396
+ * ```js
11397
+ * import { Client } from '@amityco/ts-sdk'
11398
+ * Client.enableAutoSubscriptions([Client.AutoSubscription.BLOCK])
11399
+ * ```
11400
+ *
11401
+ * Enables one or more managed auto-subscription handles. Managed handles are
11402
+ * re-applied on every (re)connect and ref-counted. All handles are on by
11403
+ * default; use this to re-enable handles previously turned off via
11404
+ * {@link disableAutoSubscriptions}. Synchronous fire-and-forget — the registry
11405
+ * updates immediately and the broker subscribe is retried on reconnect.
11406
+ *
11407
+ * @param features the {@link AutoSubscription} handles to enable
11408
+ *
11409
+ * @category Client API
11410
+ */
11411
+ const enableAutoSubscriptions = (features) => {
11412
+ const manager = getAutoSubscriptionManager();
11413
+ features.forEach(feature => manager.subscribe(feature));
11414
+ };
11415
+ /* end_public_function */
11416
+ /* begin_public_function
11417
+ id: client.disable_auto_subscriptions
11418
+ */
11419
+ /**
11420
+ * ```js
11421
+ * import { Client } from '@amityco/ts-sdk'
11422
+ * Client.disableAutoSubscriptions([Client.AutoSubscription.LIVESTREAM])
11423
+ * ```
11424
+ *
11425
+ * Disables one or more managed auto-subscription handles. The change persists
11426
+ * across reconnect (it is not silently re-enabled) until
11427
+ * {@link enableAutoSubscriptions} is called again. Synchronous fire-and-forget.
11428
+ *
11429
+ * @param features the {@link AutoSubscription} handles to disable
11430
+ *
11431
+ * @category Client API
11432
+ */
11433
+ const disableAutoSubscriptions = (features) => {
11434
+ const manager = getAutoSubscriptionManager();
11435
+ features.forEach(feature => manager.unsubscribe(feature));
11436
+ };
11437
+ /* end_public_function */
11438
+ /* begin_public_function
11439
+ id: client.auto_subscriptions
11440
+ */
11441
+ /**
11442
+ * ```js
11443
+ * import { Client } from '@amityco/ts-sdk'
11444
+ * Client.autoSubscriptions().forEach(s => console.log(s.feature, s.isActive, s.topicCount))
11445
+ * ```
11446
+ *
11447
+ * Inspects the managed auto-subscription registry — each handle's `isActive`,
11448
+ * `isSystem`, and `topicCount`.
11449
+ *
11450
+ * @returns a snapshot of the managed subscription registry
11451
+ *
11452
+ * @category Client API
11453
+ */
11454
+ const autoSubscriptions = () => getAutoSubscriptionManager().subscriptions();
11455
+ /* end_public_function */
11456
+
10861
11457
  /**
10862
11458
  * ```js
10863
11459
  * import { onChannelMarkerFetched } from '@amityco/ts-sdk'
@@ -11238,6 +11834,12 @@ var index$s = /*#__PURE__*/Object.freeze({
11238
11834
  getCurrentUserType: getCurrentUserType,
11239
11835
  setCurrentUserType: setCurrentUserType,
11240
11836
  setAccessTokenHandler: setAccessTokenHandler,
11837
+ getChatSettings: getChatSettings,
11838
+ notifications: notifications,
11839
+ get AutoSubscription () { return AutoSubscription; },
11840
+ enableAutoSubscriptions: enableAutoSubscriptions,
11841
+ disableAutoSubscriptions: disableAutoSubscriptions,
11842
+ autoSubscriptions: autoSubscriptions,
11241
11843
  onConnectionError: onConnectionError,
11242
11844
  onClientDisconnected: onClientDisconnected,
11243
11845
  onClientBanned: onClientBanned,
@@ -11343,6 +11945,67 @@ const unBlockUser = async (userId) => {
11343
11945
  };
11344
11946
  /* end_public_function */
11345
11947
 
11948
+ /**
11949
+ * Subscribes to a block MQTT event (`user.didBlock` / `user.didUnblock`),
11950
+ * ingests the carried `FollowersPayload` (follows + users) into the cache so
11951
+ * the block-relationship rows (`['follow', 'get', from#to]`) and user rows are
11952
+ * kept current, then forwards the affected {@link Amity.FollowStatus} to the
11953
+ * caller.
11954
+ *
11955
+ * @hidden
11956
+ */
11957
+ const createBlockEventSubscriber = (event, callback) => {
11958
+ const client = getActiveClient();
11959
+ const filter = (data) => {
11960
+ const payload = prepareFollowersPayload(data);
11961
+ if (client.cache) {
11962
+ ingestInCache(payload);
11963
+ }
11964
+ callback(payload.follows[0]);
11965
+ };
11966
+ return createEventSubscriber(client, event, event, filter);
11967
+ };
11968
+
11969
+ /**
11970
+ * ```js
11971
+ * import { onUserDidBlock } from '@amityco/ts-sdk'
11972
+ * const dispose = onUserDidBlock(status => {
11973
+ * // ...
11974
+ * })
11975
+ * ```
11976
+ *
11977
+ * Fired when a block relationship is created in real time — either a user
11978
+ * blocks the current user (incoming) or the current user blocks someone on
11979
+ * another device (outgoing). The local block-relationship store is updated
11980
+ * before the callback runs.
11981
+ *
11982
+ * @param callback The function to call when the event was fired
11983
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
11984
+ *
11985
+ * @category Block Events
11986
+ */
11987
+ const onUserDidBlock = (callback) => createBlockEventSubscriber('user.didBlock', callback);
11988
+
11989
+ /**
11990
+ * ```js
11991
+ * import { onUserDidUnblock } from '@amityco/ts-sdk'
11992
+ * const dispose = onUserDidUnblock(status => {
11993
+ * // ...
11994
+ * })
11995
+ * ```
11996
+ *
11997
+ * Fired when a block relationship is removed in real time — either a user
11998
+ * unblocks the current user (incoming) or the current user unblocks someone on
11999
+ * another device (outgoing). The local block-relationship store is updated
12000
+ * before the callback runs.
12001
+ *
12002
+ * @param callback The function to call when the event was fired
12003
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
12004
+ *
12005
+ * @category Block Events
12006
+ */
12007
+ const onUserDidUnblock = (callback) => createBlockEventSubscriber('user.didUnblock', callback);
12008
+
11346
12009
  /* begin_public_function
11347
12010
  id: user.relationship.follow
11348
12011
  */
@@ -12445,6 +13108,8 @@ var index$r = /*#__PURE__*/Object.freeze({
12445
13108
  __proto__: null,
12446
13109
  blockUser: blockUser,
12447
13110
  unBlockUser: unBlockUser,
13111
+ onUserDidBlock: onUserDidBlock,
13112
+ onUserDidUnblock: onUserDidUnblock,
12448
13113
  follow: follow,
12449
13114
  unfollow: unfollow,
12450
13115
  acceptMyFollower: acceptMyFollower,
@@ -13274,7 +13939,7 @@ const getWatchSessionStorage = () => {
13274
13939
  return storageInstance;
13275
13940
  };
13276
13941
 
13277
- const privateKey = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHo80SecH7FuF2\nhFYnb+l26/VN8UMLXAQFLnxciNTEwkGVFMpdezlH8rU2HtUJL4RETogbAOLVY0XM\njs6sPn8G1nALmh9qeDpUtVqFOVtBHxEZ910TLOtQiunjqJKO5nWdqZ71EC3OFluR\niGQkO84BiIFbv37ub7xl3S8XarbtKoLcyVpkDHi+1wx1pgCAn6gtBUgckPL5NR8j\nLseabl3HAXQfhTCKo4tmOFM2Dxwl1IUMmIJrJg/aIU/U0tj/1Eoo7mG0JcNWX19l\nW3EecCbi0ncCJOrkUdwlBrcjaMayaX/ubEwyUeTGiLdyc4L3GRLHjyK8xgVNXRMH\nbZWJ2a5NAgMBAAECggEASxuE+35zTFO/XydKgmvIGcWL9FbgMlXb7Vcf0nBoG945\nbiz0NVc2paraIhJXc608xbYF3qLmtAE1MVBI0ORyRdBHNxY024l/6H6SH60Ed+uI\nM4ysp5ourY6Vj+DLwpdRiI9YDjqYAQDIUmhNxJP7XPhOMoZI6st+xZQBM34ic/bv\nAMSJm9OZphSp3+qXVkFZztr2mxD2EZSJJLYxi8BCdgM2qhazalbcJ6zDKHCZWVWm\n8RRxDGldyMb/237JxETzP40tAlzOZDmBAbUgEnurDJ93RVDIE3rbZUshwgeQd18a\nem096mWgvB1AIKYgsTAR3pw+V19YWAjq/glP6fz8wQKBgQD/oQq+ukKF0PRgBeM5\ngeTjSwsdGppQLmf5ndujvoiz/TpdjDEPu6R8kigQr1rG2t4K/yfdZoI8RdmJD1al\n3Q7N9hofooSy4rj6E3txzWZCHJjHad2cnCp/O26HiReGAl7wTcfTmNdiFHhZQzm5\nJBkvWAiwuvQMNfEbnXxw6/vIDwKBgQDH7fX8gsc77JLvAWgp1MaQN/sbqVb6JeT1\nFQfR8E/WFCSmzQBtNzd5KgYuCeelwr/8DyYytvN2BzCYZXp73gI1jF3YlW5jVn74\nOY6TwQ095digwo6Z0yuxopdIOApKgAkL9PRKgNrqAf3NAyMua6lOGifzjDojC3KU\nfylQmxMn4wKBgHp2B9O/H0dEBw5JQ8W0+JX6yWQz7mEjGiR2/1W+XXb8hQ1zr709\nw1r6Gb+EghRpnZ3fBpYGGbYOMFx8wKHM+N6qW3F0ReX8v2juFGE8aRSa5oYBrWzt\nU16Idjbv8hj84cZ1PJmdyvDtpYn9rpWHOZl4rxEbPvbqkIsOMyNVqdT5AoGAOSge\nmwIIU2le2FVeohbibXiToWTYKMuMmURZ5/r72AgKMmWJKbAPe+Q3wBG01/7FRBpQ\noU8Ma0HC8s6QJbliiEyIx9JwrJWd1vkdecBHONrtA4ibm/5zD2WcOllLF+FitLhi\n3qnX6+6F0IaFGFBPJrTzlv0P4dTz/OAdv52V7GECgYEA2TttOKBAqWllgOaZOkql\nLVMJVmgR7s6tLi1+cEP8ZcapV9aRbRzTAKXm4f8AEhtlG9F9kCOvHYCYGi6JaiWJ\nZkHjeex3T+eE6Di6y5Bm/Ift5jtVhJ4jCVwHOKTMej79NPUFTJfv8hCo29haBDv6\nRXFrv+T21KCcw8k3sJeJWWQ=\n-----END PRIVATE KEY-----";
13942
+ const privateKey = "MIIEpQIBAAKCAQEAwAEc/oZgYIvKSUG/C3mONYLR4ZPgAjMEX4bJ+xqqakUDRtqlNO+eZs2blQ1Ko0DBkqPExyQezvjibH5W2UZBV5RaBTlTcNVKTToMBEGesAfaEcM3qUyQHxdbFYZv6P4sb14dcwxTQ8usmaV8ooiR1Fcaso5ZWYcZ8Hb46FbQ7OoVumsBtPWwfZ4f003o5VCl6AIM6lcLv9UDLlFVYhE+PeXpRHtfWlGqxMvqC9oinlwhL6nWv6VjQXW4nhcib72dPBzfHT7k/PMKto2SxALYdb68ENiAGuJLWi3AUHSyYCJK2w7wIlWfJUAI0v26ub10IpExr6D5QuW2577jjP93iwIDAQABAoIBAFWfqXhwIIatkFY+9Z1+ZcbDQimgsmMIsUiQaX6Lk7e0cxOj6czDlxYtVtaPiNtow2pLkjNkjkCqiP7tEHnwdK9DvylZOTa2R15NJpK3WLcTqVIGhsn/FL5owfvFah6zSsmXZParZm5zY9NZE03ALZhOB9/cz0e3kf/EbpfeL2mW7MApyiUt5i09ycchroOpcWp73ipIxvgigtZyUGFmsQicWhUs28F0D7w4Qfk76yG3nqXeb+BAMhCaIaa/k/aAxhiZG/ygEQWQrcC8gfe+jyicMAQPDEVS9YuUMGsLjIjKuVLZzp2xirQnhc2i2zVNEIvG6soprPOBEMQugzrtX5ECgYEA3b7KAbBIbDl1e4ZSCWhHdHkiWVZHaopsR/LhqDDNhXjWjq3AesgV6k0j9EdziMn/HmmOso0bz99GTV3JZf4A9ztTLumJlkHbdVtlgOqSjrFLj12rH9KXTheyIhWSpUmm8+WB1xasFbqpvJaGo7F3pd2Fqj1XR4mp5BO7c/t7LJ0CgYEA3aouEzXQ9THRKYocdfY69EI1Il1t/d/RSqqd9BxEjxBgxkM13ZiYIn/R4WW/nCUrlmhxG44Aa2Gob4Ahfsui2xKTg/g/3Zk/rAxAEGkfOLGoenaJMD41fH4wUq3FRYwkvnaMb9Hd6f/TlBHslIRa2NN58bSBGJCyBP2b59+2+EcCgYEAixDVRXvV37GlYUOa/XVdosk5Zoe6oDGRuQm0xbNdoUBoZvDHDvme7ONWEiQha/8qtVsD+CyQ7awcPfb8kK9c0bBt+bTS6d4BkTcxkEkMgtrkBVR8Nqfu5jXsLH4VCv4G61zbMhZw8+ut+az5YX2yCN7Frj9sFlxapMRPQmzMEe0CgYEAumsAzM8ZqNv4mAK65Mnr0rhLj1cbxcKRdUYACOgtEFQpzxN/HZnTeFAe5nx3pI3uFlRHq3DFEYnT6dHMWaJQmAULYpVIwMi9L6gtyJ9fzoI6uqMtxRDMUqKdaSsTGOY/kJ6KhQ/unXi1K3XXjR+yd1+C0q+HUm1+CYxvrZYLfskCgYEArsEy+IQOiqniJ0NE2vVUF+UK/IRZaic9YKcpov5Ot7Vvzm/MnnW4N1ljVskocETBWMmPUvNSExVjPebi+rxd8fa5kY8BJScPTzMFbunZn/wjtGdcM10qdlVQ9doG61A/9P3ezFKCfS4AvF/H/59LcSx2Bh28fp3/efiVIOpVd4Y=";
13278
13943
  /*
13279
13944
  * The crypto algorithm used for importing key and signing string
13280
13945
  */
@@ -14596,6 +15261,10 @@ const postLinkedObject = (post) => {
14596
15261
  const analyticsEngineInstance = AnalyticsEngine$1.getInstance();
14597
15262
  analyticsEngineInstance.markPostAsViewed(post.postId);
14598
15263
  },
15264
+ markAsMeaningfullyViewed: (feedRenderPosition) => {
15265
+ const analyticsEngineInstance = AnalyticsEngine$1.getInstance();
15266
+ analyticsEngineInstance.markPostAsMeaningfullyViewed(post.postId, feedRenderPosition);
15267
+ },
14599
15268
  },
14600
15269
  get productTags() {
14601
15270
  var _a, _b;
@@ -14785,6 +15454,11 @@ const addReaction$1 = async (referenceType, referenceId, reactionName, reference
14785
15454
  });
14786
15455
  return true;
14787
15456
  }
15457
+ if (referenceType === 'message') {
15458
+ upsertInCache(['message', 'get', referenceId], updatedModel);
15459
+ fireEvent('local.message.updated', { messages: [updatedModel] });
15460
+ return true;
15461
+ }
14788
15462
  }
14789
15463
  return true;
14790
15464
  };
@@ -14863,7 +15537,7 @@ const removeReaction$1 = async (referenceType, referenceId, reactionName, refere
14863
15537
  return true;
14864
15538
  }
14865
15539
  if (referenceType === 'story') {
14866
- fireEvent('local.story.reactionAdded', {
15540
+ fireEvent('local.story.reactionRemoved', {
14867
15541
  story: updatedModel,
14868
15542
  reactor: {
14869
15543
  userId: client.userId,
@@ -14873,6 +15547,11 @@ const removeReaction$1 = async (referenceType, referenceId, reactionName, refere
14873
15547
  });
14874
15548
  return true;
14875
15549
  }
15550
+ if (referenceType === 'message') {
15551
+ upsertInCache(['message', 'get', referenceId], updatedModel);
15552
+ fireEvent('local.message.updated', { messages: [updatedModel] });
15553
+ return true;
15554
+ }
14876
15555
  }
14877
15556
  return true;
14878
15557
  };
@@ -16192,6 +16871,12 @@ class BlockedUserPaginationController extends PaginationController {
16192
16871
  }
16193
16872
  }
16194
16873
 
16874
+ var EnumBlockActions;
16875
+ (function (EnumBlockActions) {
16876
+ EnumBlockActions["OnBlocked"] = "onBlocked";
16877
+ EnumBlockActions["OnUnblocked"] = "onUnblocked";
16878
+ })(EnumBlockActions || (EnumBlockActions = {}));
16879
+
16195
16880
  class BlockedUserQueryStreamController extends QueryStreamController {
16196
16881
  constructor(query, cacheKey, notifyChange, preparePayload) {
16197
16882
  super(query, cacheKey);
@@ -16221,11 +16906,16 @@ class BlockedUserQueryStreamController extends QueryStreamController {
16221
16906
  }
16222
16907
  reactor(action) {
16223
16908
  return (targetUser) => {
16224
- var _a;
16225
- if (action === EnumFollowActions.OnFollowed) {
16909
+ var _a, _b;
16910
+ const isRemoval = action === EnumFollowActions.OnFollowed || action === EnumBlockActions.OnUnblocked;
16911
+ const isAddition = action === EnumBlockActions.OnBlocked;
16912
+ if (isRemoval || isAddition) {
16226
16913
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
16227
- const updatedCollection = collection === null || collection === void 0 ? void 0 : collection.data.filter(id => id !== targetUser.userId);
16228
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: updatedCollection }));
16914
+ const ids = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
16915
+ const data = isAddition
16916
+ ? [...new Set([...ids, targetUser.userId])]
16917
+ : ids.filter(id => id !== targetUser.userId);
16918
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data }));
16229
16919
  }
16230
16920
  this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
16231
16921
  };
@@ -16280,7 +16970,6 @@ class BlockedUserLiveCollectionController extends LiveCollectionController {
16280
16970
  fn: onUserDeleted$2,
16281
16971
  action: EnumUserActions.OnUserDeleted,
16282
16972
  },
16283
- // In the case of unblocking a user, we need to subscribe to the follow events
16284
16973
  {
16285
16974
  fn: convertEventPayload(onLocalUserFollowed, 'to', 'user'),
16286
16975
  action: EnumFollowActions.OnFollowed,
@@ -16289,6 +16978,28 @@ class BlockedUserLiveCollectionController extends LiveCollectionController {
16289
16978
  fn: convertEventPayload(onUserFollowed, 'to', 'user'),
16290
16979
  action: EnumFollowActions.OnFollowed,
16291
16980
  },
16981
+ {
16982
+ fn: (reactor) => onUserDidBlock(status => {
16983
+ var _a;
16984
+ if (status.from !== getActiveClient().userId)
16985
+ return;
16986
+ const blocked = (_a = pullFromCache(['user', 'get', status.to])) === null || _a === void 0 ? void 0 : _a.data;
16987
+ if (blocked)
16988
+ reactor(blocked);
16989
+ }),
16990
+ action: EnumBlockActions.OnBlocked,
16991
+ },
16992
+ {
16993
+ fn: (reactor) => onUserDidUnblock(status => {
16994
+ var _a;
16995
+ if (status.from !== getActiveClient().userId)
16996
+ return;
16997
+ const blocked = (_a = pullFromCache(['user', 'get', status.to])) === null || _a === void 0 ? void 0 : _a.data;
16998
+ if (blocked)
16999
+ reactor(blocked);
17000
+ }),
17001
+ action: EnumBlockActions.OnUnblocked,
17002
+ },
16292
17003
  ]);
16293
17004
  }
16294
17005
  notifyChange({ origin, loading, error }) {
@@ -16356,6 +17067,192 @@ const getBlockedUsers = (params, callback, config) => {
16356
17067
  };
16357
17068
  /* end_public_function */
16358
17069
 
17070
+ function prepareBlockingUserPayload(response) {
17071
+ const { users, follows } = response, rest = __rest(response, ["users", "follows"]);
17072
+ return Object.assign(Object.assign({}, rest), { follows: follows.map(follow => {
17073
+ const followUser = users.find(user => user.userId === follow.from);
17074
+ return Object.assign(Object.assign({}, follow), { user: convertRawUserToInternalUser(followUser) });
17075
+ }), users: users.map(convertRawUserToInternalUser) });
17076
+ }
17077
+
17078
+ class BlockingUserQueryStreamController extends QueryStreamController {
17079
+ constructor(query, cacheKey, notifyChange, preparePayload) {
17080
+ super(query, cacheKey);
17081
+ this.notifyChange = notifyChange;
17082
+ this.preparePayload = preparePayload;
17083
+ }
17084
+ async saveToMainDB(response) {
17085
+ const processedPayload = await this.preparePayload(response);
17086
+ const client = getActiveClient();
17087
+ const cachedAt = client.cache && Date.now();
17088
+ if (client.cache) {
17089
+ ingestInCache(processedPayload, { cachedAt });
17090
+ }
17091
+ }
17092
+ appendToQueryStream(response, direction, refresh = false) {
17093
+ var _a, _b;
17094
+ if (refresh) {
17095
+ pushToCache(this.cacheKey, {
17096
+ data: response.users.map(getResolver('user')),
17097
+ });
17098
+ }
17099
+ else {
17100
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
17101
+ const users = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
17102
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...users, ...response.users.map(getResolver('user'))])] }));
17103
+ }
17104
+ }
17105
+ reactor(action) {
17106
+ return (user) => {
17107
+ var _a, _b;
17108
+ if (user &&
17109
+ (action === EnumBlockActions.OnBlocked || action === EnumBlockActions.OnUnblocked)) {
17110
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
17111
+ const ids = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
17112
+ const data = action === EnumBlockActions.OnBlocked
17113
+ ? [...new Set([...ids, user.userId])]
17114
+ : ids.filter(id => id !== user.userId);
17115
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data }));
17116
+ }
17117
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
17118
+ };
17119
+ }
17120
+ subscribeRTE(createSubscriber) {
17121
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
17122
+ }
17123
+ }
17124
+
17125
+ class BlockingUserPaginationController extends PaginationController {
17126
+ async getRequest(queryParams, token) {
17127
+ const { limit = COLLECTION_DEFAULT_PAGINATION_SIZE } = queryParams, params = __rest(queryParams, ["limit"]);
17128
+ const options = token ? { token } : { limit };
17129
+ const { data: queryResponse } = await this.http.get('/api/v4/me/blockers', {
17130
+ params: Object.assign(Object.assign({}, params), { options, isDeleted: false }),
17131
+ });
17132
+ return queryResponse;
17133
+ }
17134
+ }
17135
+
17136
+ class BlockingUserLiveCollectionController extends LiveCollectionController {
17137
+ constructor(callback) {
17138
+ const queryStreamId = `blocking-users-${getActiveClient().userId}`;
17139
+ const query = {};
17140
+ const cacheKey = ['blockingUsers', 'collection', queryStreamId];
17141
+ const paginationController = new BlockingUserPaginationController(query);
17142
+ super(paginationController, queryStreamId, cacheKey, callback);
17143
+ this.queryStreamController = new BlockingUserQueryStreamController(query, this.cacheKey, this.notifyChange.bind(this), prepareBlockingUserPayload);
17144
+ this.callback = callback.bind(this);
17145
+ this.loadPage({ initial: true });
17146
+ }
17147
+ setup() {
17148
+ var _a;
17149
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
17150
+ if (!collection) {
17151
+ pushToCache(this.cacheKey, {
17152
+ data: [],
17153
+ params: {},
17154
+ });
17155
+ }
17156
+ }
17157
+ async persistModel(queryPayload) {
17158
+ await this.queryStreamController.saveToMainDB(queryPayload);
17159
+ }
17160
+ persistQueryStream({ response, direction, refresh, }) {
17161
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
17162
+ }
17163
+ startSubscription() {
17164
+ return this.queryStreamController.subscribeRTE([
17165
+ {
17166
+ fn: onUserDeleted$2,
17167
+ action: EnumUserActions.OnUserDeleted,
17168
+ },
17169
+ {
17170
+ fn: (reactor) => onUserDidBlock(status => {
17171
+ var _a;
17172
+ if (status.to !== getActiveClient().userId)
17173
+ return;
17174
+ const blocker = (_a = pullFromCache(['user', 'get', status.from])) === null || _a === void 0 ? void 0 : _a.data;
17175
+ if (blocker)
17176
+ reactor(blocker);
17177
+ }),
17178
+ action: EnumBlockActions.OnBlocked,
17179
+ },
17180
+ {
17181
+ fn: (reactor) => onUserDidUnblock(status => {
17182
+ var _a;
17183
+ if (status.to !== getActiveClient().userId)
17184
+ return;
17185
+ const blocker = (_a = pullFromCache(['user', 'get', status.from])) === null || _a === void 0 ? void 0 : _a.data;
17186
+ if (blocker)
17187
+ reactor(blocker);
17188
+ }),
17189
+ action: EnumBlockActions.OnUnblocked,
17190
+ },
17191
+ ]);
17192
+ }
17193
+ notifyChange({ origin, loading, error }) {
17194
+ var _a, _b;
17195
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
17196
+ if (!collection)
17197
+ return;
17198
+ const data = this.applyFilter((_b = collection.data
17199
+ .map(id => pullFromCache(['user', 'get', id]))
17200
+ .filter(isNonNullable)
17201
+ .map(({ data }) => data)
17202
+ .map(LinkedObject.user)) !== null && _b !== void 0 ? _b : []);
17203
+ if (!this.shouldNotify(data) && origin === 'event')
17204
+ return;
17205
+ this.callback({
17206
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
17207
+ data,
17208
+ hasNextPage: !!this.paginationController.getNextToken(),
17209
+ loading,
17210
+ error,
17211
+ });
17212
+ }
17213
+ applyFilter(data) {
17214
+ let users = data;
17215
+ users = users.filter(user => user.isDeleted == null || user.isDeleted === false);
17216
+ return users;
17217
+ }
17218
+ }
17219
+
17220
+ /* begin_public_function
17221
+ id: user.get_blocking_users
17222
+ */
17223
+ /**
17224
+ * ```js
17225
+ * import { UserRepository } from '@amityco/ts-sdk'
17226
+ * const unsubscribe = UserRepository.getBlockingUsers(({ data: users }) => {
17227
+ * console.log(users)
17228
+ * })
17229
+ * ```
17230
+ *
17231
+ * Observe the {@link Amity.User}s who have blocked the current user
17232
+ *
17233
+ * @param callback to receive updates on the blocking {@link Amity.User}s
17234
+ * @returns {@link Amity.Unsubscriber} to unsubscribe from collection
17235
+ *
17236
+ * @category User API
17237
+ */
17238
+ const getBlockingUsers = (callback) => {
17239
+ const { log, cache } = getActiveClient();
17240
+ if (!cache)
17241
+ console.log(ENABLE_CACHE_MESSAGE);
17242
+ const timestamp = Date.now();
17243
+ log(`getBlockingUsers(tmpid: ${timestamp}) > listen`);
17244
+ const blockingUserLiveCollection = new BlockingUserLiveCollectionController(callback);
17245
+ const disposers = blockingUserLiveCollection.startSubscription();
17246
+ const cacheKey = blockingUserLiveCollection.getCacheKey();
17247
+ disposers.push(() => dropFromCache(cacheKey));
17248
+ return () => {
17249
+ log(`getBlockingUsers(tmpid: ${timestamp}) > dispose`);
17250
+ disposers.forEach(fn => fn());
17251
+ dropFromCache(cacheKey);
17252
+ };
17253
+ };
17254
+ /* end_public_function */
17255
+
16359
17256
  class SearchUserPaginationController extends PaginationController {
16360
17257
  async getRequest(queryParams, token) {
16361
17258
  const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, displayName } = queryParams, params = __rest(queryParams, ["limit", "displayName"]);
@@ -16630,6 +17527,7 @@ var index$q = /*#__PURE__*/Object.freeze({
16630
17527
  getUser: getUser,
16631
17528
  getUsers: getUsers,
16632
17529
  getBlockedUsers: getBlockedUsers,
17530
+ getBlockingUsers: getBlockingUsers,
16633
17531
  searchUserByDisplayName: searchUserByDisplayName,
16634
17532
  getReachedUsers: getReachedUsers,
16635
17533
  get AmityUserSearchMatchType () { return AmityUserSearchMatchType; }
@@ -17796,7 +18694,7 @@ const removeReaction = async (referenceType, referenceId, reactionName) => {
17796
18694
  return true;
17797
18695
  }
17798
18696
  if (referenceType === 'story') {
17799
- fireEvent('local.story.reactionAdded', {
18697
+ fireEvent('local.story.reactionRemoved', {
17800
18698
  story: updatedModel,
17801
18699
  reactor: {
17802
18700
  userId: client.userId,
@@ -19380,6 +20278,104 @@ const unmuteChannel = async (channelId) => {
19380
20278
  };
19381
20279
  /* end_public_function */
19382
20280
 
20281
+ /* begin_public_function
20282
+ id: channel.archive
20283
+ */
20284
+ /**
20285
+ * ```js
20286
+ * import { ChannelRepository } from '@amityco/ts-sdk'
20287
+ * const success = await ChannelRepository.archiveChannel('foobar')
20288
+ * ```
20289
+ *
20290
+ * Archive a {@link Amity.Channel}.
20291
+ *
20292
+ * @param channelId The id of the {@link Amity.Channel} to archive
20293
+ * @returns A success boolean
20294
+ *
20295
+ * @category Channel API
20296
+ * @async
20297
+ */
20298
+ const archiveChannel = async (channelId) => {
20299
+ const client = getActiveClient();
20300
+ client.log('channel/archiveChannel', channelId);
20301
+ await client.http.post(`/api/v1/archives/channels/${encodeURIComponent(channelId)}`);
20302
+ const archive = {
20303
+ channelId,
20304
+ archivedAt: new Date().toISOString(),
20305
+ };
20306
+ if (client.cache) {
20307
+ pushToCache(['archivedChannel', 'get', getResolver('archivedChannel')(archive)], archive);
20308
+ }
20309
+ fireEvent('local.channel.archived', { archives: [archive] });
20310
+ };
20311
+ /* end_public_function */
20312
+
20313
+ /* begin_public_function
20314
+ id: channel.unarchive
20315
+ */
20316
+ /**
20317
+ * ```js
20318
+ * import { ChannelRepository } from '@amityco/ts-sdk'
20319
+ * const success = await ChannelRepository.unarchiveChannel('foobar')
20320
+ * ```
20321
+ *
20322
+ * Unarchive a previously archived {@link Amity.Channel}.
20323
+ *
20324
+ * @param channelId The id of the {@link Amity.Channel} to unarchive
20325
+ * @returns A success boolean
20326
+ *
20327
+ * @category Channel API
20328
+ * @async
20329
+ */
20330
+ const unarchiveChannel = async (channelId) => {
20331
+ var _a;
20332
+ const client = getActiveClient();
20333
+ client.log('channel/unarchiveChannel', channelId);
20334
+ await client.http.delete(`/api/v1/archives/channels/${encodeURIComponent(channelId)}`);
20335
+ const cached = (_a = pullFromCache(['archivedChannel', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
20336
+ const archive = cached !== null && cached !== void 0 ? cached : {
20337
+ channelId,
20338
+ archivedAt: new Date().toISOString(),
20339
+ };
20340
+ if (client.cache) {
20341
+ dropFromCache(['archivedChannel', 'get', channelId], true);
20342
+ }
20343
+ fireEvent('local.channel.unarchived', { archives: [archive] });
20344
+ };
20345
+ /* end_public_function */
20346
+
20347
+ /* begin_public_function
20348
+ id: channel.archive.ids
20349
+ */
20350
+ /**
20351
+ * ```js
20352
+ * import { ChannelRepository } from '@amityco/ts-sdk'
20353
+ * const ids = await ChannelRepository.getArchivedChannelIds()
20354
+ * ```
20355
+ *
20356
+ * @returns A list of archived channel ids sorted by `archivedAt` descending.
20357
+ *
20358
+ * @category Channel API
20359
+ * @async
20360
+ */
20361
+ const getArchivedChannelIds = async () => {
20362
+ var _a;
20363
+ const client = getActiveClient();
20364
+ client.log('channel/getArchivedChannelIds');
20365
+ const { data: payload } = await client.http.get(`/api/v1/archives/channels`);
20366
+ const archives = (_a = payload.archives) !== null && _a !== void 0 ? _a : [];
20367
+ if (client.cache) {
20368
+ dropFromCache(['archivedChannel', 'get']);
20369
+ archives.forEach(archive => {
20370
+ if (!archive.channelId)
20371
+ return;
20372
+ pushToCache(['archivedChannel', 'get', archive.channelId], archive);
20373
+ });
20374
+ }
20375
+ return archives.map(entry => entry.channelId).filter(channelId => !!channelId);
20376
+ };
20377
+ /* end_public_function */
20378
+
19383
20379
  /**
19384
20380
  * ```js
19385
20381
  * import { onMessageUpdated } from '@amityco/ts-sdk'
@@ -20758,6 +21754,160 @@ const getMessages = (params, callback, config) => {
20758
21754
  };
20759
21755
  /* end_public_function */
20760
21756
 
21757
+ class SearchMessagePaginationController extends PaginationController {
21758
+ async getRequest(queryParams, token) {
21759
+ const { query, exactMatch, channelId, messageFeedId, userIds, tags, types, sortBy, orderBy, limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, } = queryParams;
21760
+ const options = token ? { token } : { limit, sortBy, orderBy };
21761
+ const { data: queryResponse } = await this.http.get(`/api/v2/search/messages`, {
21762
+ params: {
21763
+ query,
21764
+ exactMatch,
21765
+ channelId,
21766
+ messageFeedId,
21767
+ userIds,
21768
+ tags,
21769
+ types,
21770
+ options,
21771
+ },
21772
+ });
21773
+ return queryResponse;
21774
+ }
21775
+ }
21776
+
21777
+ class SearchMessageQueryStreamController extends QueryStreamController {
21778
+ constructor(query, cacheKey, notifyChange) {
21779
+ super(query, cacheKey);
21780
+ this.notifyChange = notifyChange;
21781
+ }
21782
+ async saveToMainDB(response) {
21783
+ var _a;
21784
+ const processedPayload = await prepareMessagePayload(response);
21785
+ const client = getActiveClient();
21786
+ const cachedAt = client.cache && Date.now();
21787
+ if (client.cache) {
21788
+ ingestInCache(processedPayload, { cachedAt });
21789
+ if ((_a = response.channels) === null || _a === void 0 ? void 0 : _a.length) {
21790
+ response.channels.forEach(channel => {
21791
+ pushToCache(['channel', 'get', channel.channelId], channel, { cachedAt });
21792
+ });
21793
+ }
21794
+ }
21795
+ }
21796
+ appendToQueryStream(response, direction, refresh = false) {
21797
+ var _a, _b;
21798
+ if (refresh) {
21799
+ pushToCache(this.cacheKey, {
21800
+ data: response.messages.map(getResolver('message')),
21801
+ });
21802
+ return;
21803
+ }
21804
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21805
+ const existing = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
21806
+ const incoming = response.messages.map(getResolver('message'));
21807
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */
21808
+ ? [...new Set([...incoming, ...existing])]
21809
+ : [...new Set([...existing, ...incoming])] }));
21810
+ }
21811
+ }
21812
+
21813
+ class SearchMessageLiveCollectionController extends LiveCollectionController {
21814
+ constructor(query, callback) {
21815
+ const queryStreamId = hash__default["default"](query);
21816
+ const cacheKey = ['message', 'search', queryStreamId];
21817
+ const paginationController = new SearchMessagePaginationController(query);
21818
+ super(paginationController, queryStreamId, cacheKey, callback);
21819
+ this.queryStreamController = new SearchMessageQueryStreamController(query, this.cacheKey, this.notifyChange.bind(this));
21820
+ this.callback = callback.bind(this);
21821
+ this.loadPage({ initial: true });
21822
+ }
21823
+ startSubscription() {
21824
+ return [];
21825
+ }
21826
+ notifyChange({ origin, loading, error }) {
21827
+ var _a, _b;
21828
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21829
+ if (!collection)
21830
+ return;
21831
+ const data = (_b = collection.data
21832
+ .map(messageId => getMessageFromMainDB(messageId))
21833
+ .filter(isNonNullable)
21834
+ .map(message => LinkedObject.message(message))) !== null && _b !== void 0 ? _b : [];
21835
+ if (!this.shouldNotify(data) && origin === 'event')
21836
+ return;
21837
+ this.callback({
21838
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
21839
+ data,
21840
+ hasNextPage: !!this.paginationController.getNextToken(),
21841
+ loading,
21842
+ error,
21843
+ });
21844
+ }
21845
+ setup() {
21846
+ var _a;
21847
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21848
+ if (!collection) {
21849
+ pushToCache(this.cacheKey, {
21850
+ data: [],
21851
+ params: {},
21852
+ });
21853
+ }
21854
+ }
21855
+ async persistModel(response) {
21856
+ await this.queryStreamController.saveToMainDB(response);
21857
+ }
21858
+ persistQueryStream({ response, direction, refresh, }) {
21859
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
21860
+ }
21861
+ }
21862
+
21863
+ /* begin_public_function
21864
+ id: message.search
21865
+ */
21866
+ /**
21867
+ * ```js
21868
+ * import { MessageRepository } from '@amityco/ts-sdk';
21869
+ *
21870
+ * let messages = [];
21871
+ *
21872
+ * const unsubscribe = MessageRepository.searchMessage(
21873
+ * { query: 'hello' },
21874
+ * response => merge(messages, response.data),
21875
+ * );
21876
+ * ```
21877
+ *
21878
+ * Live collection of {@link Amity.Message}s matching the search query. Backed
21879
+ * by `GET /api/v2/search/messages`. The first emission delivers the first
21880
+ * page; pagination is driven by `response.onNextPage()`.
21881
+ *
21882
+ * @param params Search parameters. `query` is required.
21883
+ * @param callback Called whenever new data are available.
21884
+ * @returns An {@link Amity.Unsubscriber} function to stop observing.
21885
+ *
21886
+ * @category Message Live Collection
21887
+ */
21888
+ const searchMessage = (params, callback) => {
21889
+ if (!params.query || params.query.trim().length === 0) {
21890
+ throw new Error('Query is required for message search');
21891
+ }
21892
+ const { log, cache } = getActiveClient();
21893
+ if (!cache) {
21894
+ console.log(ENABLE_CACHE_MESSAGE);
21895
+ }
21896
+ const timestamp = Date.now();
21897
+ log(`searchMessage(tmpid: ${timestamp}) > listen`);
21898
+ const controller = new SearchMessageLiveCollectionController(params, callback);
21899
+ const disposers = controller.startSubscription();
21900
+ const cacheKey = controller.getCacheKey();
21901
+ disposers.push(() => {
21902
+ dropFromCache(cacheKey);
21903
+ });
21904
+ return () => {
21905
+ log(`searchMessage(tmpid: ${timestamp}) > dispose`);
21906
+ disposers.forEach(fn => fn());
21907
+ };
21908
+ };
21909
+ /* end_public_function */
21910
+
20761
21911
  var index$n = /*#__PURE__*/Object.freeze({
20762
21912
  __proto__: null,
20763
21913
  createMessage: createMessage,
@@ -20783,6 +21933,7 @@ var index$n = /*#__PURE__*/Object.freeze({
20783
21933
  onMessageFetched: onMessageFetched,
20784
21934
  getMessage: getMessage,
20785
21935
  getMessages: getMessages,
21936
+ searchMessage: searchMessage,
20786
21937
  convertFromRaw: convertFromRaw$1,
20787
21938
  prepareMessagePayload: prepareMessagePayload,
20788
21939
  convertParams: convertParams,
@@ -21630,6 +22781,7 @@ class ChannelQueryStreamController extends QueryStreamController {
21630
22781
  "onCreate" /* Amity.ChannelActionType.OnCreate */,
21631
22782
  "onJoin" /* Amity.ChannelActionType.OnJoin */,
21632
22783
  "onResolveChannel" /* Amity.ChannelActionType.OnResolveChannel */,
22784
+ "onUnarchived" /* Amity.ChannelActionType.OnUnarchived */,
21633
22785
  ].includes(action)) {
21634
22786
  if (Array.isArray(payload)) {
21635
22787
  collection.data = [
@@ -21639,6 +22791,12 @@ class ChannelQueryStreamController extends QueryStreamController {
21639
22791
  else
21640
22792
  collection.data = [...new Set([payload.channelInternalId, ...collection.data])];
21641
22793
  }
22794
+ if (action === "onArchived" /* Amity.ChannelActionType.OnArchived */) {
22795
+ const ids = Array.isArray(payload)
22796
+ ? payload.map(getResolver('channel'))
22797
+ : [getResolver('channel')(payload)];
22798
+ collection.data = collection.data.filter(channelInternalId => !ids.includes(channelInternalId));
22799
+ }
21642
22800
  pushToCache(this.cacheKey, collection);
21643
22801
  this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
21644
22802
  };
@@ -21905,6 +23063,32 @@ class ChannelLiveCollectionController extends LiveCollectionController {
21905
23063
  },
21906
23064
  { fn: onChannelMemberAdded, action: "onMemberAdded" /* Amity.ChannelActionType.OnMemberAdded */ },
21907
23065
  { fn: onChannelMemberRemoved, action: "onMemberRemoved" /* Amity.ChannelActionType.OnMemberRemoved */ },
23066
+ {
23067
+ fn: (reactor) => onChannelArchived(payload => {
23068
+ const channels = payload.archives
23069
+ .map(archive => {
23070
+ var _a;
23071
+ return (_a = pullFromCache(['channel', 'get', archive.channelId])) === null || _a === void 0 ? void 0 : _a.data;
23072
+ })
23073
+ .filter((c) => Boolean(c));
23074
+ if (channels.length > 0)
23075
+ reactor(channels);
23076
+ }),
23077
+ action: "onArchived" /* Amity.ChannelActionType.OnArchived */,
23078
+ },
23079
+ {
23080
+ fn: (reactor) => onChannelUnarchived(payload => {
23081
+ const channels = payload.archives
23082
+ .map(archive => {
23083
+ var _a;
23084
+ return (_a = pullFromCache(['channel', 'get', archive.channelId])) === null || _a === void 0 ? void 0 : _a.data;
23085
+ })
23086
+ .filter((c) => Boolean(c));
23087
+ if (channels.length > 0)
23088
+ reactor(channels);
23089
+ }),
23090
+ action: "onUnarchived" /* Amity.ChannelActionType.OnUnarchived */,
23091
+ },
21908
23092
  {
21909
23093
  fn: convertEventPayload(onChannelMarkerFetched, 'entityId', 'channel'),
21910
23094
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
@@ -22258,6 +23442,192 @@ const getTotalChannelsUnread = (callback) => {
22258
23442
  };
22259
23443
  };
22260
23444
 
23445
+ class ArchivedChannelPaginationController extends PaginationController {
23446
+ async getRequest(queryParams, token) {
23447
+ var _a, _b;
23448
+ const limit = (_a = queryParams.limit) !== null && _a !== void 0 ? _a : COLLECTION_DEFAULT_PAGINATION_LIMIT;
23449
+ const pageIndex = token ? Number.parseInt(token, 10) : 0;
23450
+ if (pageIndex === 0) {
23451
+ await getArchivedChannelIds();
23452
+ }
23453
+ const cached = (_b = queryCache(['archivedChannel', 'get'])) !== null && _b !== void 0 ? _b : [];
23454
+ const archives = cached
23455
+ .map(entry => entry.data)
23456
+ .slice()
23457
+ .sort((a, b) => Number(new Date(b.archivedAt)) - Number(new Date(a.archivedAt)));
23458
+ const start = pageIndex * limit;
23459
+ const end = start + limit;
23460
+ const slice = archives.slice(start, end);
23461
+ const hasMore = end < archives.length;
23462
+ if (slice.length > 0) {
23463
+ await getChannelByIds$1(slice.map(archive => archive.channelId));
23464
+ }
23465
+ return {
23466
+ archives: slice,
23467
+ paging: {
23468
+ next: hasMore ? String(pageIndex + 1) : undefined,
23469
+ previous: undefined,
23470
+ },
23471
+ };
23472
+ }
23473
+ }
23474
+
23475
+ class ArchivedChannelQueryStreamController extends QueryStreamController {
23476
+ constructor(query, cacheKey, notifyChange) {
23477
+ super(query, cacheKey);
23478
+ this.notifyChange = notifyChange;
23479
+ }
23480
+ async saveToMainDB(_response) {
23481
+ //
23482
+ }
23483
+ appendToQueryStream(response, direction, refresh = false) {
23484
+ var _a, _b;
23485
+ const channelIds = response.archives.map(archive => archive.channelId);
23486
+ if (refresh) {
23487
+ pushToCache(this.cacheKey, {
23488
+ data: channelIds,
23489
+ params: {},
23490
+ });
23491
+ return;
23492
+ }
23493
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23494
+ const existing = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
23495
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */
23496
+ ? [...new Set([...channelIds, ...existing])]
23497
+ : [...new Set([...existing, ...channelIds])] }));
23498
+ }
23499
+ reactor(action) {
23500
+ return (channelIds) => {
23501
+ var _a;
23502
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23503
+ if (!collection)
23504
+ return;
23505
+ if (action === "onArchived" /* Amity.ChannelActionType.OnArchived */) {
23506
+ const filtered = collection.data.filter(id => !channelIds.includes(id));
23507
+ collection.data = [...channelIds, ...filtered];
23508
+ }
23509
+ if (action === "onUnarchived" /* Amity.ChannelActionType.OnUnarchived */ ||
23510
+ action === "onDelete" /* Amity.ChannelActionType.OnDelete */) {
23511
+ collection.data = collection.data.filter(id => !channelIds.includes(id));
23512
+ }
23513
+ pushToCache(this.cacheKey, collection);
23514
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
23515
+ };
23516
+ }
23517
+ subscribeRTE(createSubscriber) {
23518
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
23519
+ }
23520
+ }
23521
+
23522
+ class ArchivedChannelLiveCollectionController extends LiveCollectionController {
23523
+ constructor(query, callback) {
23524
+ const queryStreamId = hash__default["default"](query);
23525
+ const cacheKey = ['archivedChannel', 'collection', queryStreamId];
23526
+ const paginationController = new ArchivedChannelPaginationController(query);
23527
+ super(paginationController, queryStreamId, cacheKey, callback);
23528
+ this.queryStreamController = new ArchivedChannelQueryStreamController(query, this.cacheKey, this.notifyChange.bind(this));
23529
+ this.callback = callback.bind(this);
23530
+ this.loadPage({ initial: true });
23531
+ }
23532
+ setup() {
23533
+ var _a;
23534
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23535
+ if (!collection) {
23536
+ pushToCache(this.cacheKey, {
23537
+ data: [],
23538
+ params: {},
23539
+ });
23540
+ }
23541
+ }
23542
+ async persistModel(response) {
23543
+ await this.queryStreamController.saveToMainDB(response);
23544
+ }
23545
+ persistQueryStream({ response, direction, refresh, }) {
23546
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
23547
+ }
23548
+ startSubscription() {
23549
+ return this.queryStreamController.subscribeRTE([
23550
+ {
23551
+ fn: reactor => onChannelArchived(payload => reactor(payload.archives.map(archive => archive.channelId))),
23552
+ action: "onArchived" /* Amity.ChannelActionType.OnArchived */,
23553
+ },
23554
+ {
23555
+ fn: reactor => onChannelUnarchived(payload => reactor(payload.archives.map(archive => archive.channelId))),
23556
+ action: "onUnarchived" /* Amity.ChannelActionType.OnUnarchived */,
23557
+ },
23558
+ {
23559
+ fn: reactor => onChannelUpdated(channel => reactor([channel.channelId])),
23560
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
23561
+ },
23562
+ {
23563
+ fn: reactor => onChannelDeleted(channel => reactor([channel.channelId])),
23564
+ action: "onDelete" /* Amity.ChannelActionType.OnDelete */,
23565
+ },
23566
+ ]);
23567
+ }
23568
+ notifyChange({ origin, loading, error }) {
23569
+ var _a, _b;
23570
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23571
+ if (!collection)
23572
+ return;
23573
+ const data = (_b = collection.data
23574
+ .map(channelId => pullFromCache(['channel', 'get', channelId]))
23575
+ .filter((entry) => Boolean(entry))
23576
+ .map(({ data: channel }) => channel)
23577
+ .map(constructChannelObject)) !== null && _b !== void 0 ? _b : [];
23578
+ if (!this.shouldNotify(data) && origin === 'event')
23579
+ return;
23580
+ this.callback({
23581
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
23582
+ data,
23583
+ hasNextPage: !!this.paginationController.getNextToken(),
23584
+ loading,
23585
+ error,
23586
+ });
23587
+ }
23588
+ }
23589
+
23590
+ /* begin_public_function
23591
+ id: channel.archive.collection
23592
+ */
23593
+ /**
23594
+ * ```js
23595
+ * import { ChannelRepository } from '@amityco/ts-sdk'
23596
+ *
23597
+ * let channels = []
23598
+ * const unsub = ChannelRepository.getArchivedChannels(params, response => merge(channels, response.data))
23599
+ * ```
23600
+ *
23601
+ * Live collection of {@link Amity.Channel}s archived by the active user.
23602
+ *
23603
+ * @param params Live collection parameters (only `limit` is honored; the
23604
+ * archive list takes no other filters).
23605
+ * @param callback the function to call when new data are available
23606
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to
23607
+ * stop observing.
23608
+ *
23609
+ * @category Channel Live Collection
23610
+ */
23611
+ const getArchivedChannels = (params, callback) => {
23612
+ const { log, cache } = getActiveClient();
23613
+ if (!cache) {
23614
+ console.log(ENABLE_CACHE_MESSAGE);
23615
+ }
23616
+ const timestamp = Date.now();
23617
+ log(`getArchivedChannels(tmpid: ${timestamp}) > listen`);
23618
+ const controller = new ArchivedChannelLiveCollectionController(params, callback);
23619
+ const disposers = controller.startSubscription();
23620
+ const cacheKey = controller.getCacheKey();
23621
+ disposers.push(() => {
23622
+ dropFromCache(cacheKey);
23623
+ });
23624
+ return () => {
23625
+ log(`getArchivedChannels(tmpid: ${timestamp}) > dispose`);
23626
+ disposers.forEach(fn => fn());
23627
+ };
23628
+ };
23629
+ /* end_public_function */
23630
+
22261
23631
  /* begin_public_function
22262
23632
  id: channel.member.add
22263
23633
  */
@@ -22389,7 +23759,9 @@ class ChannelMemberQueryStreamController extends QueryStreamController {
22389
23759
  channelId: this.query.channelId,
22390
23760
  userId: channelMember.userId,
22391
23761
  });
22392
- if (channelMember.membership === 'none') {
23762
+ const membershipFilter = this.query.memberships;
23763
+ const isInFilter = !membershipFilter || membershipFilter.includes(channelMember.membership);
23764
+ if (channelMember.membership === 'none' || !isInFilter) {
22393
23765
  collection.data = collection.data.filter(m => m !== channelMemberCacheId);
22394
23766
  }
22395
23767
  else if (!collection.data.includes(channelMemberCacheId)) {
@@ -22725,6 +24097,7 @@ const banMembers$1 = async (channelId, userIds) => {
22725
24097
  const cachedAt = client.cache && Date.now();
22726
24098
  if (client.cache)
22727
24099
  ingestInCache(preparedPayload, { cachedAt });
24100
+ fireEvent('channel.banned', payload);
22728
24101
  return {
22729
24102
  data: channelUsers === null || channelUsers === void 0 ? void 0 : channelUsers.filter(user => user.membership === 'banned'),
22730
24103
  cachedAt,
@@ -22759,6 +24132,7 @@ const unbanMembers$1 = async (channelId, userIds) => {
22759
24132
  const cachedAt = client.cache && Date.now();
22760
24133
  if (client.cache)
22761
24134
  ingestInCache(preparedPayload, { cachedAt });
24135
+ fireEvent('channel.unbanned', payload);
22762
24136
  const { channelUsers } = preparedPayload;
22763
24137
  return {
22764
24138
  data: channelUsers === null || channelUsers === void 0 ? void 0 : channelUsers.filter(user => user.membership === 'member'),
@@ -22787,6 +24161,7 @@ const MUTE_FOREVER = -1;
22787
24161
  * @async
22788
24162
  * */
22789
24163
  const muteMembers = async (channelId, userIds, mutePeriod = MUTE_FOREVER) => {
24164
+ var _a;
22790
24165
  const client = getActiveClient();
22791
24166
  client.log('channel/muteMembers', { userIds, channelId, mutePeriod });
22792
24167
  const { data } = await client.http.put(`/api/v2/channel/${channelId}/users/mute`, {
@@ -22794,6 +24169,15 @@ const muteMembers = async (channelId, userIds, mutePeriod = MUTE_FOREVER) => {
22794
24169
  mutePeriod: mutePeriod === MUTE_FOREVER ? mutePeriod : mutePeriod * 1000,
22795
24170
  });
22796
24171
  const { success } = data;
24172
+ const muteTimeout = mutePeriod === MUTE_FOREVER
24173
+ ? new Date('9999-12-31T23:59:59.999Z').toISOString()
24174
+ : new Date(Date.now() + mutePeriod * 1000).toISOString();
24175
+ fireEvent('channel.setMutedUsers', {
24176
+ channelId,
24177
+ userIds,
24178
+ muteTimeout,
24179
+ actor: (_a = client.userId) !== null && _a !== void 0 ? _a : '',
24180
+ });
22797
24181
  return success;
22798
24182
  };
22799
24183
  /* end_public_function */
@@ -22816,6 +24200,7 @@ const muteMembers = async (channelId, userIds, mutePeriod = MUTE_FOREVER) => {
22816
24200
  * @async
22817
24201
  * */
22818
24202
  const unmuteMembers = async (channelId, userIds) => {
24203
+ var _a;
22819
24204
  const client = getActiveClient();
22820
24205
  client.log('channel/unmuteMembers', { userIds, channelId });
22821
24206
  const { data } = await client.http.put(`/api/v2/channel/${encodeURIComponent(channelId)}/users/mute`, {
@@ -22823,6 +24208,12 @@ const unmuteMembers = async (channelId, userIds) => {
22823
24208
  mutePeriod: 0,
22824
24209
  });
22825
24210
  const { success } = data;
24211
+ fireEvent('channel.setMutedUsers', {
24212
+ channelId,
24213
+ userIds,
24214
+ muteTimeout: new Date(0).toISOString(),
24215
+ actor: (_a = client.userId) !== null && _a !== void 0 ? _a : '',
24216
+ });
22826
24217
  return success;
22827
24218
  };
22828
24219
  /* end_public_function */
@@ -22849,6 +24240,9 @@ var index$j = /*#__PURE__*/Object.freeze({
22849
24240
  leaveChannel: leaveChannel,
22850
24241
  muteChannel: muteChannel,
22851
24242
  unmuteChannel: unmuteChannel,
24243
+ archiveChannel: archiveChannel,
24244
+ unarchiveChannel: unarchiveChannel,
24245
+ getArchivedChannelIds: getArchivedChannelIds,
22852
24246
  onChannelCreated: onChannelCreated,
22853
24247
  onChannelUpdated: onChannelUpdated,
22854
24248
  onChannelDeleted: onChannelDeleted,
@@ -22861,9 +24255,12 @@ var index$j = /*#__PURE__*/Object.freeze({
22861
24255
  onChannelMemberUnbanned: onChannelMemberUnbanned,
22862
24256
  onChannelMemberRoleAdded: onChannelMemberRoleAdded,
22863
24257
  onChannelMemberRoleRemoved: onChannelMemberRoleRemoved,
24258
+ onChannelArchived: onChannelArchived,
24259
+ onChannelUnarchived: onChannelUnarchived,
22864
24260
  getChannel: getChannel,
22865
24261
  getChannels: getChannels,
22866
24262
  getTotalChannelsUnread: getTotalChannelsUnread,
24263
+ getArchivedChannels: getArchivedChannels,
22867
24264
  MARKER_INCLUDED_CHANNEL_TYPE: MARKER_INCLUDED_CHANNEL_TYPE,
22868
24265
  isUnreadCountSupport: isUnreadCountSupport,
22869
24266
  convertFromRaw: convertFromRaw,
@@ -26759,7 +28156,7 @@ class CommentLiveCollectionController extends LiveCollectionController {
26759
28156
  this.queryStreamController.appendToQueryStream(response, direction, refresh);
26760
28157
  }
26761
28158
  startSubscription() {
26762
- return this.queryStreamController.subscribeRTE([
28159
+ const disposers = this.queryStreamController.subscribeRTE([
26763
28160
  { fn: onCommentCreatedLocal, action: EnumCommentActions.OnCommentCreated },
26764
28161
  { fn: onCommentDeleteLocal, action: EnumCommentActions.OnCommentDeleted },
26765
28162
  { fn: onCommentCreated, action: EnumCommentActions.OnCommentCreated },
@@ -26772,6 +28169,11 @@ class CommentLiveCollectionController extends LiveCollectionController {
26772
28169
  { fn: onLocalCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
26773
28170
  { fn: onLocalCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
26774
28171
  ]);
28172
+ if (this.query.excludeBlockUserComments) {
28173
+ const refresh = () => this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
28174
+ disposers.push(onUserDidBlock(refresh), onUserDidUnblock(refresh));
28175
+ }
28176
+ return disposers;
26775
28177
  }
26776
28178
  notifyChange({ origin, loading, error }) {
26777
28179
  var _a, _b;
@@ -26824,6 +28226,9 @@ class CommentLiveCollectionController extends LiveCollectionController {
26824
28226
  comments = comments.filter(comment => { var _a; return (_a = this.query.dataTypes) === null || _a === void 0 ? void 0 : _a.values.some(value => { var _a; return (_a = comment.dataTypes) === null || _a === void 0 ? void 0 : _a.includes(value); }); });
26825
28227
  }
26826
28228
  }
28229
+ if (this.query.excludeBlockUserComments) {
28230
+ comments = filterCommentsByBlockUsers(comments);
28231
+ }
26827
28232
  switch (this.query.sortBy) {
26828
28233
  case 'firstCreated':
26829
28234
  comments = comments.sort(sortByFirstCreated);
@@ -27909,13 +29314,218 @@ const getCommunityFeed = (params, callback, config) => {
27909
29314
  };
27910
29315
  /* end_public_function */
27911
29316
 
29317
+ /**
29318
+ * Thrown by `getForYouFeed` when the network has the For You feature
29319
+ * disabled. Mapped from HTTP 404 NOT_FOUND. Distinct from a generic
29320
+ * not-found so consumers can hide the For You tab without retrying.
29321
+ *
29322
+ * @category Errors
29323
+ */
29324
+ class AmityForYouFeedDisabledError extends ASCApiError {
29325
+ constructor(message = 'For You feed is not enabled for this network') {
29326
+ super(message, 400400 /* Amity.ServerError.ITEM_NOT_FOUND */, "error" /* Amity.ErrorLevel.ERROR */);
29327
+ this.type = 'AmityForYouFeedDisabledError';
29328
+ }
29329
+ }
29330
+
29331
+ class ForYouFeedPaginationController extends PaginationController {
29332
+ constructor(query) {
29333
+ super(query);
29334
+ this.checkedDisk = false;
29335
+ this.cursor = CursorController.current();
29336
+ }
29337
+ async getRequest(_queryParams, token) {
29338
+ let effectiveToken = token;
29339
+ if (!effectiveToken && !this.checkedDisk && this.cursor) {
29340
+ this.checkedDisk = true;
29341
+ const stored = await this.cursor.get();
29342
+ if (stored && !CursorController.isExpired(stored.expiredAt)) {
29343
+ effectiveToken = stored.cursor;
29344
+ }
29345
+ else if (stored) {
29346
+ await this.cursor.clear();
29347
+ }
29348
+ }
29349
+ const options = {
29350
+ limit: COLLECTION_DEFAULT_PAGINATION_SIZE,
29351
+ };
29352
+ if (effectiveToken)
29353
+ options.token = effectiveToken;
29354
+ let queryResponse;
29355
+ try {
29356
+ ({ data: queryResponse } = await this.http.get(API_ENDPOINTS.forYouFeed, { params: { options } }));
29357
+ }
29358
+ catch (error) {
29359
+ if (error instanceof ASCApiError && error.code === 400300 /* Amity.ServerError.FORBIDDEN */) {
29360
+ throw new AmityForYouFeedDisabledError();
29361
+ }
29362
+ const recoverable = error instanceof ASCApiError && error.code === 400322 /* Amity.ServerError.FEED_SNAPSHOT_EXPIRED */;
29363
+ if (recoverable && effectiveToken !== undefined) {
29364
+ if (this.cursor)
29365
+ await this.cursor.clear();
29366
+ ({ data: queryResponse } = await this.http.get(API_ENDPOINTS.forYouFeed, { params: { options: { limit: COLLECTION_DEFAULT_PAGINATION_SIZE } } }));
29367
+ }
29368
+ else {
29369
+ throw error;
29370
+ }
29371
+ }
29372
+ await this.persistCursor(queryResponse);
29373
+ return queryResponse;
29374
+ }
29375
+ async persistCursor(response) {
29376
+ var _a, _b;
29377
+ if (!this.cursor)
29378
+ return;
29379
+ const cursor = (_a = response.paging) === null || _a === void 0 ? void 0 : _a.next;
29380
+ const expiredAtIso = (_b = response.paging) === null || _b === void 0 ? void 0 : _b.expiredAt;
29381
+ if (!cursor || !expiredAtIso)
29382
+ return;
29383
+ const expiredAt = Date.parse(expiredAtIso);
29384
+ if (Number.isNaN(expiredAt))
29385
+ return;
29386
+ await this.cursor.set({ cursor, expiredAt });
29387
+ }
29388
+ }
29389
+
29390
+ class ForYouFeedQueryStreamController extends QueryStreamController {
29391
+ constructor(query, cacheKey, notifyChange, preparePayload) {
29392
+ super(query, cacheKey);
29393
+ this.notifyChange = notifyChange;
29394
+ this.preparePayload = preparePayload;
29395
+ }
29396
+ async saveToMainDB(response) {
29397
+ const processedPayload = await this.preparePayload(response);
29398
+ const client = getActiveClient();
29399
+ const cachedAt = client.cache && Date.now();
29400
+ if (client.cache)
29401
+ ingestInCache(processedPayload, { cachedAt });
29402
+ }
29403
+ appendToQueryStream(response, _direction, refresh = false) {
29404
+ var _a, _b;
29405
+ if (refresh) {
29406
+ pushToCache(this.cacheKey, {
29407
+ data: response.posts.map(getResolver('post')),
29408
+ });
29409
+ }
29410
+ else {
29411
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
29412
+ const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
29413
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...posts, ...response.posts.map(getResolver('post'))])] }));
29414
+ }
29415
+ }
29416
+ reactor(action) {
29417
+ return (post) => {
29418
+ var _a;
29419
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
29420
+ if (!collection)
29421
+ return;
29422
+ if (post.parentPostId && !collection.data.includes(post.parentPostId))
29423
+ return;
29424
+ if (action === EnumPostActions.OnPostDeleted || action === EnumPostActions.OnPostDeclined) {
29425
+ collection.data = collection.data.filter(postId => postId !== post.postId);
29426
+ }
29427
+ pushToCache(this.cacheKey, collection);
29428
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
29429
+ };
29430
+ }
29431
+ subscribeRTE(createSubscriber) {
29432
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
29433
+ }
29434
+ }
29435
+
29436
+ const FOR_YOU_FEED_CACHE_KEY = ['forYouFeed', 'collection'];
29437
+ class ForYouFeedLiveCollectionController extends LiveCollectionController {
29438
+ constructor(callback) {
29439
+ const queryStreamId = `for-you-feed-${getActiveClient().userId}`;
29440
+ const query = {};
29441
+ const paginationController = new ForYouFeedPaginationController(query);
29442
+ super(paginationController, queryStreamId, FOR_YOU_FEED_CACHE_KEY, callback);
29443
+ this.queryStreamController = new ForYouFeedQueryStreamController(query, this.cacheKey, this.notifyChange.bind(this), preparePostPayload);
29444
+ this.callback = callback.bind(this);
29445
+ this.loadPage({ initial: true });
29446
+ }
29447
+ setup() {
29448
+ var _a;
29449
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
29450
+ if (!collection)
29451
+ pushToCache(this.cacheKey, { data: [], params: {} });
29452
+ }
29453
+ async persistModel(payload) {
29454
+ await this.queryStreamController.saveToMainDB(payload);
29455
+ }
29456
+ persistQueryStream({ response, direction, refresh, }) {
29457
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
29458
+ }
29459
+ startSubscription() {
29460
+ return this.queryStreamController.subscribeRTE(getGlobalFeedSubscriptions(this.cacheKey));
29461
+ }
29462
+ notifyChange({ origin, loading, error }) {
29463
+ var _a, _b;
29464
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
29465
+ if (!collection)
29466
+ return;
29467
+ const data = ((_b = collection.data
29468
+ .map(id => pullFromCache(['post', 'get', id]))
29469
+ .filter(isNonNullable)
29470
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.post);
29471
+ if (!this.shouldNotify(data) && origin === 'event')
29472
+ return;
29473
+ this.callback({
29474
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
29475
+ data,
29476
+ hasNextPage: !!this.paginationController.getNextToken(),
29477
+ loading,
29478
+ error,
29479
+ });
29480
+ }
29481
+ }
29482
+
29483
+ /* begin_public_function
29484
+ id: feed.query.for_you_feed
29485
+ */
29486
+ /**
29487
+ * ```js
29488
+ * import { FeedRepository } from '@amityco/ts-sdk'
29489
+ *
29490
+ * const unsub = FeedRepository.getForYouFeed(({ data, loading, error, hasNextPage, onNextPage }) => {
29491
+ * // render posts; call onNextPage() to load the next page (20 posts)
29492
+ * })
29493
+ * ```
29494
+ *
29495
+ * Observe the For You feed — a personalized, server-ranked
29496
+ * {@link Amity.LiveCollection} of {@link Amity.Post}.
29497
+ *
29498
+ * @param callback the function to call when new data is available
29499
+ * @returns an {@link Amity.Unsubscriber} function to stop observing
29500
+ *
29501
+ * @category Posts Live Collection
29502
+ */
29503
+ const getForYouFeed = (callback) => {
29504
+ const { log, cache } = getActiveClient();
29505
+ if (!cache)
29506
+ console.log(ENABLE_CACHE_MESSAGE);
29507
+ const timestamp = Date.now();
29508
+ log(`getForYouFeed(tmpid: ${timestamp}) > listen`);
29509
+ const forYouFeedLiveCollection = new ForYouFeedLiveCollectionController(callback);
29510
+ const disposers = forYouFeedLiveCollection.startSubscription();
29511
+ const cacheKey = forYouFeedLiveCollection.getCacheKey();
29512
+ disposers.push(() => dropFromCache(cacheKey));
29513
+ return () => {
29514
+ log(`getForYouFeed(tmpid: ${timestamp}) > dispose`);
29515
+ disposers.forEach(fn => fn());
29516
+ };
29517
+ };
29518
+ /* end_public_function */
29519
+
27912
29520
  var index$d = /*#__PURE__*/Object.freeze({
27913
29521
  __proto__: null,
27914
29522
  queryGlobalFeed: queryGlobalFeed,
27915
29523
  getCustomRankingGlobalFeed: getCustomRankingGlobalFeed,
27916
29524
  getGlobalFeed: getGlobalFeed,
27917
29525
  getUserFeed: getUserFeed,
27918
- getCommunityFeed: getCommunityFeed
29526
+ getCommunityFeed: getCommunityFeed,
29527
+ getForYouFeed: getForYouFeed,
29528
+ AmityForYouFeedDisabledError: AmityForYouFeedDisabledError
27919
29529
  });
27920
29530
 
27921
29531
  /* begin_public_function
@@ -28928,7 +30538,12 @@ class PostLiveCollectionController extends LiveCollectionController {
28928
30538
  this.queryStreamController.appendToQueryStream(response, direction, refresh);
28929
30539
  }
28930
30540
  startSubscription() {
28931
- return this.queryStreamController.subscribeRTE(getPostSubscription(this.cacheKey));
30541
+ const disposers = this.queryStreamController.subscribeRTE(getPostSubscription(this.cacheKey));
30542
+ if (this.query.excludeBlockUserPosts) {
30543
+ const refresh = () => this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
30544
+ disposers.push(onUserDidBlock(refresh), onUserDidUnblock(refresh));
30545
+ }
30546
+ return disposers;
28932
30547
  }
28933
30548
  notifyChange({ origin, loading, error }) {
28934
30549
  var _a, _b;
@@ -28974,6 +30589,9 @@ class PostLiveCollectionController extends LiveCollectionController {
28974
30589
  const sortBy = this.query.sortBy || 'lastCreated';
28975
30590
  posts = posts.filter(post => !exceedsUntilAtBoundary(post.createdAt, validatedUntilAt, sortBy));
28976
30591
  }
30592
+ if (this.query.excludeBlockUserPosts) {
30593
+ posts = filterPostsByBlockUsers(posts);
30594
+ }
28977
30595
  switch (this.query.sortBy) {
28978
30596
  case 'firstCreated':
28979
30597
  posts = posts.sort(sortByFirstCreated);
@@ -35696,6 +37314,9 @@ exports.filterByPropIntersection = filterByPropIntersection;
35696
37314
  exports.filterBySearchTerm = filterBySearchTerm;
35697
37315
  exports.filterByStringComparePartially = filterByStringComparePartially;
35698
37316
  exports.filterByUntilAt = filterByUntilAt;
37317
+ exports.filterCommentsByBlockUsers = filterCommentsByBlockUsers;
37318
+ exports.filterPostsByBlockUsers = filterPostsByBlockUsers;
37319
+ exports.getBlockUsersId = getBlockUsersId;
35699
37320
  exports.getChannelTopic = getChannelTopic;
35700
37321
  exports.getCommentTopic = getCommentTopic;
35701
37322
  exports.getCommunityStoriesTopic = getCommunityStoriesTopic;
@@ -35707,6 +37328,7 @@ exports.getMarkerUserFeedTopic = getMarkerUserFeedTopic;
35707
37328
  exports.getMessageTopic = getMessageTopic;
35708
37329
  exports.getMyFollowersTopic = getMyFollowersTopic;
35709
37330
  exports.getMyFollowingsTopic = getMyFollowingsTopic;
37331
+ exports.getNetworkId = getNetworkId;
35710
37332
  exports.getNetworkTopic = getNetworkTopic;
35711
37333
  exports.getPostTopic = getPostTopic;
35712
37334
  exports.getRole = getRole;