@amityco/ts-sdk 7.1.1-611ceb49.0 → 7.1.1-67cf0d9.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 (146) hide show
  1. package/dist/@types/core/events.d.ts +2 -5
  2. package/dist/@types/core/events.d.ts.map +1 -1
  3. package/dist/@types/core/model.d.ts +2 -4
  4. package/dist/@types/core/model.d.ts.map +1 -1
  5. package/dist/@types/core/payload.d.ts +0 -18
  6. package/dist/@types/core/payload.d.ts.map +1 -1
  7. package/dist/@types/core/readReceipt.d.ts +12 -1
  8. package/dist/@types/core/readReceipt.d.ts.map +1 -1
  9. package/dist/@types/domains/channel.d.ts +10 -0
  10. package/dist/@types/domains/channel.d.ts.map +1 -1
  11. package/dist/@types/domains/client.d.ts +2 -0
  12. package/dist/@types/domains/client.d.ts.map +1 -1
  13. package/dist/channelRepository/api/markChannelsAsReadBySegment.d.ts +16 -0
  14. package/dist/channelRepository/api/markChannelsAsReadBySegment.d.ts.map +1 -0
  15. package/dist/channelRepository/events/onChannelDeleted.d.ts.map +1 -1
  16. package/dist/channelRepository/events/onChannelLeft.d.ts.map +1 -1
  17. package/dist/{marker → channelRepository}/events/onChannelUnreadUpdatedLocal.d.ts +2 -2
  18. package/dist/channelRepository/events/onChannelUnreadUpdatedLocal.d.ts.map +1 -0
  19. package/dist/channelRepository/internalApi/getTotalChannelsUnread.d.ts +11 -0
  20. package/dist/channelRepository/internalApi/getTotalChannelsUnread.d.ts.map +1 -0
  21. package/dist/channelRepository/observers/getChannel.d.ts.map +1 -1
  22. package/dist/channelRepository/observers/getChannels/ChannelLiveCollectionController.d.ts.map +1 -1
  23. package/dist/channelRepository/observers/getTotalChannelsUnread.d.ts +20 -0
  24. package/dist/channelRepository/observers/getTotalChannelsUnread.d.ts.map +1 -0
  25. package/dist/channelRepository/observers/index.d.ts +1 -0
  26. package/dist/channelRepository/observers/index.d.ts.map +1 -1
  27. package/dist/channelRepository/utils/constructChannelDynamicValue.d.ts.map +1 -1
  28. package/dist/channelRepository/utils/getLegacyChannelUnread.d.ts +2 -0
  29. package/dist/channelRepository/utils/getLegacyChannelUnread.d.ts.map +1 -0
  30. package/dist/channelRepository/utils/prepareChannelPayload.d.ts.map +1 -1
  31. package/dist/client/api/createClient.d.ts +1 -0
  32. package/dist/client/api/createClient.d.ts.map +1 -1
  33. package/dist/client/api/enableUnreadCount.d.ts.map +1 -1
  34. package/dist/client/api/login.d.ts.map +1 -1
  35. package/dist/client/utils/ReadReceiptSync/legacyReadReceiptSyncEngine.d.ts +33 -0
  36. package/dist/client/utils/ReadReceiptSync/legacyReadReceiptSyncEngine.d.ts.map +1 -0
  37. package/dist/client/utils/ReadReceiptSync/legacyReadReceiptSyncEngineOnLoginHandler.d.ts +3 -0
  38. package/dist/client/utils/ReadReceiptSync/legacyReadReceiptSyncEngineOnLoginHandler.d.ts.map +1 -0
  39. package/dist/client/utils/ReadReceiptSync/readReceiptSyncEngine.d.ts +2 -4
  40. package/dist/client/utils/ReadReceiptSync/readReceiptSyncEngine.d.ts.map +1 -1
  41. package/dist/client/utils/endpoints.d.ts +1 -0
  42. package/dist/client/utils/endpoints.d.ts.map +1 -1
  43. package/dist/client/utils/setClientToken.d.ts.map +1 -1
  44. package/dist/core/events.d.ts +3 -3
  45. package/dist/core/events.d.ts.map +1 -1
  46. package/dist/core/model/idResolvers.d.ts.map +1 -1
  47. package/dist/core/model/index.d.ts.map +1 -1
  48. package/dist/index.cjs.js +599 -477
  49. package/dist/index.d.ts +0 -1
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.esm.js +580 -457
  52. package/dist/index.umd.js +4 -4
  53. package/dist/marker/events/onChannelUnreadInfoUpdatedLocal.d.ts +12 -0
  54. package/dist/marker/events/onChannelUnreadInfoUpdatedLocal.d.ts.map +1 -0
  55. package/dist/messageRepository/events/onMessageCreated.d.ts.map +1 -1
  56. package/dist/messageRepository/observers/getMessage.d.ts.map +1 -1
  57. package/dist/messageRepository/utils/markReadMessage.d.ts.map +1 -1
  58. package/dist/utils/linkedObject/index.d.ts +0 -1
  59. package/dist/utils/linkedObject/index.d.ts.map +1 -1
  60. package/package.json +1 -1
  61. package/src/@types/core/events.ts +2 -6
  62. package/src/@types/core/model.ts +4 -6
  63. package/src/@types/core/payload.ts +0 -25
  64. package/src/@types/core/readReceipt.ts +14 -1
  65. package/src/@types/domains/channel.ts +13 -0
  66. package/src/@types/domains/client.ts +3 -0
  67. package/src/channelRepository/api/markChannelsAsReadBySegment.ts +29 -0
  68. package/src/channelRepository/events/onChannelDeleted.ts +17 -4
  69. package/src/channelRepository/events/onChannelLeft.ts +11 -3
  70. package/src/{marker → channelRepository}/events/onChannelUnreadUpdatedLocal.ts +3 -3
  71. package/src/channelRepository/internalApi/getTotalChannelsUnread.ts +38 -0
  72. package/src/channelRepository/observers/getChannel.ts +3 -1
  73. package/src/channelRepository/observers/getChannels/ChannelLiveCollectionController.ts +6 -1
  74. package/src/channelRepository/observers/getTotalChannelsUnread.ts +129 -0
  75. package/src/channelRepository/observers/index.ts +1 -0
  76. package/src/channelRepository/utils/constructChannelDynamicValue.ts +12 -2
  77. package/src/channelRepository/utils/getLegacyChannelUnread.ts +5 -0
  78. package/src/channelRepository/utils/prepareChannelPayload.ts +68 -17
  79. package/src/client/api/createClient.ts +7 -1
  80. package/src/client/api/enableUnreadCount.ts +1 -0
  81. package/src/client/api/login.ts +5 -1
  82. package/src/client/utils/ReadReceiptSync/legacyReadReceiptSyncEngine.ts +267 -0
  83. package/src/client/utils/ReadReceiptSync/legacyReadReceiptSyncEngineOnLoginHandler.ts +21 -0
  84. package/src/client/utils/ReadReceiptSync/readReceiptSyncEngine.ts +74 -99
  85. package/src/client/utils/endpoints.ts +1 -0
  86. package/src/client/utils/setClientToken.ts +8 -0
  87. package/src/core/model/idResolvers.ts +2 -3
  88. package/src/core/model/index.ts +0 -2
  89. package/src/fileRepository/api/uploadFile.ts +1 -1
  90. package/src/fileRepository/api/uploadImage.ts +1 -1
  91. package/src/fileRepository/api/uploadVideo.ts +1 -1
  92. package/src/index.ts +0 -2
  93. package/src/marker/events/onChannelUnreadInfoUpdatedLocal.ts +29 -0
  94. package/src/messageRepository/events/onMessageCreated.ts +45 -1
  95. package/src/messageRepository/observers/getMessage.ts +0 -1
  96. package/src/messageRepository/utils/markReadMessage.ts +10 -3
  97. package/src/utils/linkedObject/index.ts +0 -2
  98. package/dist/@types/domains/notification.d.ts +0 -81
  99. package/dist/@types/domains/notification.d.ts.map +0 -1
  100. package/dist/marker/events/onChannelUnreadUpdatedLocal.d.ts.map +0 -1
  101. package/dist/notificationTrayRepository/api/index.d.ts +0 -3
  102. package/dist/notificationTrayRepository/api/index.d.ts.map +0 -1
  103. package/dist/notificationTrayRepository/api/markNotificationItemsSeen.d.ts +0 -16
  104. package/dist/notificationTrayRepository/api/markNotificationItemsSeen.d.ts.map +0 -1
  105. package/dist/notificationTrayRepository/api/markNotificationTraySeen.d.ts +0 -19
  106. package/dist/notificationTrayRepository/api/markNotificationTraySeen.d.ts.map +0 -1
  107. package/dist/notificationTrayRepository/events/index.d.ts +0 -2
  108. package/dist/notificationTrayRepository/events/index.d.ts.map +0 -1
  109. package/dist/notificationTrayRepository/events/onNotificationTraySeenUpdated.d.ts +0 -17
  110. package/dist/notificationTrayRepository/events/onNotificationTraySeenUpdated.d.ts.map +0 -1
  111. package/dist/notificationTrayRepository/index.d.ts +0 -4
  112. package/dist/notificationTrayRepository/index.d.ts.map +0 -1
  113. package/dist/notificationTrayRepository/internalApi/getNotificationTraySeen.d.ts +0 -30
  114. package/dist/notificationTrayRepository/internalApi/getNotificationTraySeen.d.ts.map +0 -1
  115. package/dist/notificationTrayRepository/observers/getNotificationTrayItems/NotificationTrayItemsLiveCollectionController.d.ts +0 -13
  116. package/dist/notificationTrayRepository/observers/getNotificationTrayItems/NotificationTrayItemsLiveCollectionController.d.ts.map +0 -1
  117. package/dist/notificationTrayRepository/observers/getNotificationTrayItems/NotificationTrayItemsPaginationController.d.ts +0 -9
  118. package/dist/notificationTrayRepository/observers/getNotificationTrayItems/NotificationTrayItemsPaginationController.d.ts.map +0 -1
  119. package/dist/notificationTrayRepository/observers/getNotificationTrayItems/NotificationTrayItemsQuerystreamController.d.ts +0 -9
  120. package/dist/notificationTrayRepository/observers/getNotificationTrayItems/NotificationTrayItemsQuerystreamController.d.ts.map +0 -1
  121. package/dist/notificationTrayRepository/observers/getNotificationTrayItems.d.ts +0 -12
  122. package/dist/notificationTrayRepository/observers/getNotificationTrayItems.d.ts.map +0 -1
  123. package/dist/notificationTrayRepository/observers/getNotificationTraySeen.d.ts +0 -21
  124. package/dist/notificationTrayRepository/observers/getNotificationTraySeen.d.ts.map +0 -1
  125. package/dist/notificationTrayRepository/observers/index.d.ts +0 -3
  126. package/dist/notificationTrayRepository/observers/index.d.ts.map +0 -1
  127. package/dist/notificationTrayRepository/utils/prepareNotificationTrayItemsPayload.d.ts +0 -2
  128. package/dist/notificationTrayRepository/utils/prepareNotificationTrayItemsPayload.d.ts.map +0 -1
  129. package/dist/utils/linkedObject/notificationTrayLinkedObject.d.ts +0 -2
  130. package/dist/utils/linkedObject/notificationTrayLinkedObject.d.ts.map +0 -1
  131. package/src/@types/domains/notification.ts +0 -90
  132. package/src/notificationTrayRepository/api/index.ts +0 -2
  133. package/src/notificationTrayRepository/api/markNotificationItemsSeen.ts +0 -59
  134. package/src/notificationTrayRepository/api/markNotificationTraySeen.ts +0 -65
  135. package/src/notificationTrayRepository/events/index.ts +0 -1
  136. package/src/notificationTrayRepository/events/onNotificationTraySeenUpdated.ts +0 -36
  137. package/src/notificationTrayRepository/index.ts +0 -3
  138. package/src/notificationTrayRepository/internalApi/getNotificationTraySeen.ts +0 -81
  139. package/src/notificationTrayRepository/observers/getNotificationTrayItems/NotificationTrayItemsLiveCollectionController.ts +0 -96
  140. package/src/notificationTrayRepository/observers/getNotificationTrayItems/NotificationTrayItemsPaginationController.ts +0 -31
  141. package/src/notificationTrayRepository/observers/getNotificationTrayItems/NotificationTrayItemsQuerystreamController.ts +0 -68
  142. package/src/notificationTrayRepository/observers/getNotificationTrayItems.ts +0 -44
  143. package/src/notificationTrayRepository/observers/getNotificationTraySeen.ts +0 -43
  144. package/src/notificationTrayRepository/observers/index.ts +0 -2
  145. package/src/notificationTrayRepository/utils/prepareNotificationTrayItemsPayload.ts +0 -12
  146. package/src/utils/linkedObject/notificationTrayLinkedObject.ts +0 -28
package/dist/index.esm.js CHANGED
@@ -106,7 +106,6 @@ const SECOND$1 = 1000;
106
106
  const MINUTE = 60 * SECOND$1;
107
107
  const HOUR = 60 * MINUTE;
108
108
  const DAY = 24 * HOUR;
109
- const WEEK = 7 * DAY;
110
109
  const YEAR = 365 * DAY;
111
110
  const ACCESS_TOKEN_WATCHER_INTERVAL = 10 * MINUTE;
112
111
 
@@ -502,6 +501,7 @@ const idResolvers = {
502
501
  messagePreviewSubChannel: ({ subChannelId }) => `${subChannelId}`,
503
502
  channelUnreadInfo: ({ channelId }) => channelId,
504
503
  subChannelUnreadInfo: ({ subChannelId }) => subChannelId,
504
+ channelUnread: ({ channelId }) => channelId,
505
505
  channelMarker: ({ entityId, userId }) => `${entityId}#${userId}`,
506
506
  subChannelMarker: ({ entityId, feedId, userId }) => `${entityId}#${feedId}#${userId}`,
507
507
  messageMarker: ({ feedId, contentId, creatorId }) => `${feedId}#${contentId}#${creatorId}`,
@@ -528,8 +528,6 @@ const idResolvers = {
528
528
  advertiser: ({ advertiserId }) => advertiserId,
529
529
  pin: ({ placement, referenceId }) => `${placement}#${referenceId}`,
530
530
  pinTarget: ({ targetId }) => targetId,
531
- notificationTrayItem: ({ _id }) => _id,
532
- notificationTraySeen: ({ userId }) => userId,
533
531
  };
534
532
  /**
535
533
  * Retrieve the id resolver matching a domain name
@@ -581,7 +579,6 @@ const PAYLOAD2MODEL = {
581
579
  advertisers: 'advertiser',
582
580
  pinTargets: 'pinTarget',
583
581
  pins: 'pin',
584
- notificationTrayItems: 'notificationTrayItem',
585
582
  };
586
583
  /** hidden */
587
584
  const isOutdated = (prevData, nextData) => {
@@ -1550,6 +1547,7 @@ const API_REGIONS = {
1550
1547
  };
1551
1548
  const URLS = {
1552
1549
  http: 'https://apix.{region}.amity.co',
1550
+ upload: 'https://upload.{region}.amity.co',
1553
1551
  mqtt: 'wss://sse.{region}.amity.co:443/mqtt',
1554
1552
  };
1555
1553
  function computeUrl(type, region) {
@@ -1598,13 +1596,13 @@ class NetworkActivitiesWatcher {
1598
1596
  this._listener.clear();
1599
1597
  }
1600
1598
  }
1601
- let instance$5;
1599
+ let instance$6;
1602
1600
  var NetworkActivitiesWatcher$1 = {
1603
1601
  getInstance: () => {
1604
- if (!instance$5) {
1605
- instance$5 = new NetworkActivitiesWatcher();
1602
+ if (!instance$6) {
1603
+ instance$6 = new NetworkActivitiesWatcher();
1606
1604
  }
1607
- return instance$5;
1605
+ return instance$6;
1608
1606
  },
1609
1607
  };
1610
1608
 
@@ -21244,13 +21242,13 @@ class AnalyticsEngine {
21244
21242
  this._eventCapturer.resetAllBuckets();
21245
21243
  }
21246
21244
  }
21247
- let instance$4;
21245
+ let instance$5;
21248
21246
  var AnalyticsEngine$1 = {
21249
21247
  getInstance: () => {
21250
- if (!instance$4) {
21251
- instance$4 = new AnalyticsEngine();
21248
+ if (!instance$5) {
21249
+ instance$5 = new AnalyticsEngine();
21252
21250
  }
21253
- return instance$4;
21251
+ return instance$5;
21254
21252
  },
21255
21253
  };
21256
21254
 
@@ -21676,6 +21674,223 @@ const getMessageReadCount = (message, marker) => {
21676
21674
  getCachedMarker$2(message)) !== null && _a !== void 0 ? _a : { readCount: 0, deliveredCount: 0 };
21677
21675
  }; // and if not found in cache use default value `0`
21678
21676
 
21677
+ /**
21678
+ *
21679
+ * Mark subChannel as read by readToSegment
21680
+ *
21681
+ * @param subChannelIds the IDs of the {@link Amity.SubChannel} to update
21682
+ * @param readToSegment the segment to mark as read
21683
+ * @returns a success boolean if the {@link Amity.SubChannel} was updated
21684
+ *
21685
+ * @category Channel API
21686
+ * @async
21687
+ */
21688
+ const markChannelsAsReadBySegment = async (readings) => {
21689
+ const client = getActiveClient();
21690
+ try {
21691
+ await client.http.post('api/v3/channels/seen', { channels: readings });
21692
+ return true;
21693
+ }
21694
+ catch (e) {
21695
+ return false;
21696
+ }
21697
+ };
21698
+
21699
+ class MessageReadReceiptSyncEngine {
21700
+ constructor() {
21701
+ this.isActive = true;
21702
+ this.MAX_RETRY = 3;
21703
+ this.JOB_QUEUE_SIZE = 120;
21704
+ this.jobQueue = [];
21705
+ // Interval for message read receipt sync in seconds
21706
+ this.RECEIPT_SYNC_INTERVAL = 1;
21707
+ this.client = getActiveClient();
21708
+ // Get remaining unsync read receipts from cache
21709
+ this.getUnsyncJobs();
21710
+ }
21711
+ // Call this when client call client.login
21712
+ startSyncReadReceipt() {
21713
+ // Start timer when start receipt sync
21714
+ this.timer = setInterval(() => {
21715
+ this.syncReadReceipts();
21716
+ }, this.RECEIPT_SYNC_INTERVAL * 1000);
21717
+ }
21718
+ // Read receipt observer handling
21719
+ syncReadReceipts() {
21720
+ if (this.jobQueue.length === 0 || this.isActive === false)
21721
+ return;
21722
+ const readReceipts = this.getReadReceipts();
21723
+ if (readReceipts) {
21724
+ this.markReadApi(readReceipts);
21725
+ }
21726
+ }
21727
+ getUnsyncJobs() {
21728
+ var _a;
21729
+ // Get all read receipts that has latestSyncSegment < latestSegment
21730
+ const readReceipts = (_a = queryCache(['readReceipt'])) === null || _a === void 0 ? void 0 : _a.filter(({ data }) => {
21731
+ return data.latestSyncSegment < data.latestSegment;
21732
+ });
21733
+ // Enqueue unsync read receipts to the job queue
21734
+ readReceipts === null || readReceipts === void 0 ? void 0 : readReceipts.forEach(({ data: readReceipt }) => {
21735
+ this.enqueueReadReceipt(readReceipt.channelId, readReceipt.latestSegment);
21736
+ });
21737
+ }
21738
+ getReadReceipts() {
21739
+ // get all read receipts from queue, now the queue is empty
21740
+ const syncJob = this.jobQueue.splice(0, this.jobQueue.length);
21741
+ if (syncJob.length === 0)
21742
+ return;
21743
+ return syncJob.filter(job => {
21744
+ var _a;
21745
+ const readReceipt = (_a = pullFromCache(['readReceipt', job.channelId])) === null || _a === void 0 ? void 0 : _a.data;
21746
+ if (!readReceipt)
21747
+ return false;
21748
+ if (readReceipt.latestSegment > readReceipt.latestSyncSegment)
21749
+ return true;
21750
+ return false;
21751
+ });
21752
+ }
21753
+ async markReadApi(syncJobs) {
21754
+ var _a;
21755
+ // constuct payload
21756
+ // example: [{ channelId: 'channelId', readToSegment: 2 }]
21757
+ const syncJobsPayload = syncJobs.map(job => {
21758
+ return {
21759
+ channelId: job.channelId,
21760
+ readToSegment: job.segment,
21761
+ };
21762
+ });
21763
+ const response = await markChannelsAsReadBySegment(syncJobsPayload);
21764
+ if (response) {
21765
+ for (let i = 0; i < syncJobs.length; i += 1) {
21766
+ // update lastestSyncSegment in read receipt cache
21767
+ const cacheKey = ['readReceipt', syncJobs[i].channelId];
21768
+ const readReceiptCache = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21769
+ pushToCache(cacheKey, Object.assign(Object.assign({}, readReceiptCache), { latestSyncSegment: syncJobs[i].segment }));
21770
+ }
21771
+ }
21772
+ else {
21773
+ for (let i = 0; i < syncJobs.length; i += 1) {
21774
+ // push them back to queue if the syncing is failed and retry count is less than max retry
21775
+ if (syncJobs[i].retryCount >= this.MAX_RETRY)
21776
+ return;
21777
+ const updatedJob = Object.assign(Object.assign({}, syncJobs[i]), { syncState: "create" /* Amity.ReadReceiptSyncState.CREATED */, retryCount: syncJobs[i].retryCount + 1 });
21778
+ this.enqueueJob(updatedJob);
21779
+ }
21780
+ }
21781
+ }
21782
+ startObservingReadReceiptQueue() {
21783
+ if (this.client.useLegacyUnreadCount) {
21784
+ this.isActive = true;
21785
+ this.startSyncReadReceipt();
21786
+ }
21787
+ }
21788
+ stopObservingReadReceiptQueue() {
21789
+ this.isActive = false;
21790
+ this.jobQueue.map(job => {
21791
+ if (job.syncState === "syncing" /* Amity.ReadReceiptSyncState.SYNCING */) {
21792
+ return Object.assign(Object.assign({}, job), { syncState: "create" /* Amity.ReadReceiptSyncState.CREATED */ });
21793
+ }
21794
+ return job;
21795
+ });
21796
+ if (this.timer)
21797
+ clearInterval(this.timer);
21798
+ }
21799
+ // Session Management
21800
+ onSessionEstablished() {
21801
+ this.startObservingReadReceiptQueue();
21802
+ }
21803
+ onSessionDestroyed() {
21804
+ this.stopObservingReadReceiptQueue();
21805
+ this.jobQueue = [];
21806
+ }
21807
+ onTokenExpired() {
21808
+ this.stopObservingReadReceiptQueue();
21809
+ }
21810
+ // Network Connection Management
21811
+ onNetworkOffline() {
21812
+ // Stop observing to the read receipt queue.
21813
+ this.stopObservingReadReceiptQueue();
21814
+ }
21815
+ onNetworkOnline() {
21816
+ // Resume observing to the read receipt queue.
21817
+ this.startObservingReadReceiptQueue();
21818
+ }
21819
+ markRead(channelId, segment) {
21820
+ var _a;
21821
+ // Step 1: Optimistic update of channelUnread.readToSegment to message.segment and update unreadCount value
21822
+ const cacheKey = ['channelUnread', 'get', channelId];
21823
+ const channelUnread = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21824
+ if (typeof (channelUnread === null || channelUnread === void 0 ? void 0 : channelUnread.readToSegment) === 'number' &&
21825
+ channelUnread &&
21826
+ segment > channelUnread.readToSegment) {
21827
+ channelUnread.readToSegment = segment;
21828
+ channelUnread.unreadCount = Math.max(channelUnread.lastSegment - segment, 0);
21829
+ pushToCache(cacheKey, channelUnread);
21830
+ fireEvent('local.channelUnread.updated', channelUnread);
21831
+ }
21832
+ // Step 2: Enqueue the read receipt
21833
+ this.enqueueReadReceipt(channelId, segment);
21834
+ }
21835
+ enqueueReadReceipt(channelId, segment) {
21836
+ var _a;
21837
+ const readReceipt = (_a = pullFromCache(['readReceipt', channelId])) === null || _a === void 0 ? void 0 : _a.data;
21838
+ // Create new read receipt if it's not exists and add the job to queue
21839
+ if (!readReceipt) {
21840
+ const readReceiptChannel = {
21841
+ channelId,
21842
+ latestSegment: segment,
21843
+ latestSyncSegment: 0,
21844
+ };
21845
+ pushToCache(['readReceipt', channelId], readReceiptChannel);
21846
+ }
21847
+ else if (readReceipt.latestSegment < segment) {
21848
+ // Update latestSegment in read receipt cache
21849
+ pushToCache(['readReceipt', channelId], Object.assign(Object.assign({}, readReceipt), { latestSegment: segment }));
21850
+ }
21851
+ else if (readReceipt.latestSyncSegment >= segment) {
21852
+ // Skip the job when lastSyncSegment > = segment
21853
+ return;
21854
+ }
21855
+ let syncJob = this.getSyncJob(channelId);
21856
+ if (syncJob === null || syncJob.syncState === "syncing" /* Amity.ReadReceiptSyncState.SYNCING */) {
21857
+ syncJob = {
21858
+ channelId,
21859
+ segment,
21860
+ syncState: "create" /* Amity.ReadReceiptSyncState.CREATED */,
21861
+ retryCount: 0,
21862
+ };
21863
+ this.enqueueJob(syncJob);
21864
+ }
21865
+ else if (syncJob.segment < segment) {
21866
+ syncJob.segment = segment;
21867
+ }
21868
+ }
21869
+ getSyncJob(channelId) {
21870
+ const { jobQueue } = this;
21871
+ const targetJob = jobQueue.find(job => job.channelId === channelId);
21872
+ return targetJob || null;
21873
+ }
21874
+ enqueueJob(syncJob) {
21875
+ if (this.jobQueue.length < this.JOB_QUEUE_SIZE) {
21876
+ this.jobQueue.push(syncJob);
21877
+ }
21878
+ else {
21879
+ // Remove oldest job when queue reach maximum capacity
21880
+ this.jobQueue.shift();
21881
+ this.jobQueue.push(syncJob);
21882
+ }
21883
+ }
21884
+ }
21885
+ let instance$4 = null;
21886
+ var ReadReceiptSyncEngine = {
21887
+ getInstance: () => {
21888
+ if (!instance$4)
21889
+ instance$4 = new MessageReadReceiptSyncEngine();
21890
+ return instance$4;
21891
+ },
21892
+ };
21893
+
21679
21894
  /**
21680
21895
  *
21681
21896
  * Mark subChannel as read by readToSegment
@@ -21724,7 +21939,7 @@ const reCalculateChannelUnreadInfo = (channelId) => {
21724
21939
  return channelUnreadInfo;
21725
21940
  };
21726
21941
 
21727
- class MessageReadReceiptSyncEngine {
21942
+ class LegacyMessageReadReceiptSyncEngine {
21728
21943
  constructor() {
21729
21944
  this.isActive = true;
21730
21945
  this.MAX_RETRY = 3;
@@ -21755,7 +21970,7 @@ class MessageReadReceiptSyncEngine {
21755
21970
  getUnsyncJobs() {
21756
21971
  var _a;
21757
21972
  // Get all read receipts that has latestSyncSegment < latestSegment
21758
- const readReceipts = (_a = queryCache(['readReceipt'])) === null || _a === void 0 ? void 0 : _a.filter(({ data }) => {
21973
+ const readReceipts = (_a = queryCache(['legacyReadReceipt'])) === null || _a === void 0 ? void 0 : _a.filter(({ data }) => {
21759
21974
  return data.latestSyncSegment < data.latestSegment;
21760
21975
  });
21761
21976
  // Enqueue unsync read receipts to the job queue
@@ -21774,7 +21989,7 @@ class MessageReadReceiptSyncEngine {
21774
21989
  return;
21775
21990
  // Get readReceipt from cache by subChannelId
21776
21991
  const readReceipt = (_a = pullFromCache([
21777
- 'readReceipt',
21992
+ 'legacyReadReceipt',
21778
21993
  syncJob.subChannelId,
21779
21994
  ])) === null || _a === void 0 ? void 0 : _a.data;
21780
21995
  if (!readReceipt)
@@ -21797,10 +22012,10 @@ class MessageReadReceiptSyncEngine {
21797
22012
  if (response) {
21798
22013
  this.removeSynedReceipt(syncJob.subChannelId, syncJob.segment);
21799
22014
  const readReceiptCache = (_a = pullFromCache([
21800
- 'readReceipt',
22015
+ 'legacyReadReceipt',
21801
22016
  subChannelId,
21802
22017
  ])) === null || _a === void 0 ? void 0 : _a.data;
21803
- pushToCache(['readReceipt', subChannelId], Object.assign(Object.assign({}, readReceiptCache), { latestSyncSegment: segment }));
22018
+ pushToCache(['legacyReadReceipt', subChannelId], Object.assign(Object.assign({}, readReceiptCache), { latestSyncSegment: segment }));
21804
22019
  }
21805
22020
  else if (!response) {
21806
22021
  if (newSyncJob.retryCount > this.MAX_RETRY) {
@@ -21867,7 +22082,7 @@ class MessageReadReceiptSyncEngine {
21867
22082
  subChannelUnreadInfo.readToSegment = segment;
21868
22083
  subChannelUnreadInfo.unreadCount = Math.max(subChannelUnreadInfo.lastSegment - segment, 0);
21869
22084
  const channelUnreadInfo = reCalculateChannelUnreadInfo(subChannelUnreadInfo.channelId);
21870
- fireEvent('local.channelUnread.updated', channelUnreadInfo);
22085
+ fireEvent('local.channelUnreadInfo.updated', channelUnreadInfo);
21871
22086
  pushToCache(cacheKey, subChannelUnreadInfo);
21872
22087
  fireEvent('local.subChannelUnread.updated', subChannelUnreadInfo);
21873
22088
  }
@@ -21876,7 +22091,10 @@ class MessageReadReceiptSyncEngine {
21876
22091
  }
21877
22092
  enqueueReadReceipt(subChannelId, segment) {
21878
22093
  var _a;
21879
- const readReceipt = (_a = pullFromCache(['readReceipt', subChannelId])) === null || _a === void 0 ? void 0 : _a.data;
22094
+ const readReceipt = (_a = pullFromCache([
22095
+ 'legacyReadReceipt',
22096
+ subChannelId,
22097
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21880
22098
  // Create new read receipt if it's not exists and add job to queue
21881
22099
  if (!readReceipt) {
21882
22100
  const readReceiptSubChannel = {
@@ -21884,10 +22102,10 @@ class MessageReadReceiptSyncEngine {
21884
22102
  latestSegment: segment,
21885
22103
  latestSyncSegment: 0,
21886
22104
  };
21887
- pushToCache(['readReceipt', subChannelId], readReceiptSubChannel);
22105
+ pushToCache(['legacyReadReceipt', subChannelId], readReceiptSubChannel);
21888
22106
  }
21889
22107
  else if (readReceipt.latestSegment < segment) {
21890
- pushToCache(['readReceipt', subChannelId], Object.assign(Object.assign({}, readReceipt), { latestSegment: segment }));
22108
+ pushToCache(['legacyReadReceipt', subChannelId], Object.assign(Object.assign({}, readReceipt), { latestSegment: segment }));
21891
22109
  }
21892
22110
  else if (readReceipt.latestSyncSegment >= segment) {
21893
22111
  // Skip the job when lastSyncSegment > = segment
@@ -21930,18 +22148,24 @@ class MessageReadReceiptSyncEngine {
21930
22148
  }
21931
22149
  }
21932
22150
  let instance$3 = null;
21933
- var ReadReceiptSyncEngine = {
22151
+ var LegacyReadReceiptSyncEngine = {
21934
22152
  getInstance: () => {
21935
22153
  if (!instance$3)
21936
- instance$3 = new MessageReadReceiptSyncEngine();
22154
+ instance$3 = new LegacyMessageReadReceiptSyncEngine();
21937
22155
  return instance$3;
21938
22156
  },
21939
22157
  };
21940
22158
 
21941
22159
  const markReadMessage = (message) => {
21942
- const { subChannelId, channelSegment } = message;
21943
- const markReadReceiptEngine = ReadReceiptSyncEngine.getInstance();
21944
- markReadReceiptEngine.markRead(subChannelId, channelSegment);
22160
+ const client = getActiveClient();
22161
+ if (client.useLegacyUnreadCount) {
22162
+ const markReadReceiptEngine = ReadReceiptSyncEngine.getInstance();
22163
+ markReadReceiptEngine.markRead(message.channelId, message.channelSegment);
22164
+ }
22165
+ else {
22166
+ const markReadReceiptEngine = LegacyReadReceiptSyncEngine.getInstance();
22167
+ markReadReceiptEngine.markRead(message.subChannelId, message.channelSegment);
22168
+ }
21945
22169
  };
21946
22170
 
21947
22171
  const messageLinkedObject = (message) => {
@@ -22089,65 +22313,6 @@ const pinnedPostLinkedObject = (pinnedPost) => {
22089
22313
  } });
22090
22314
  };
22091
22315
 
22092
- /* begin_public_function
22093
- id: notificationTrayItem.markSeen
22094
- */
22095
- /**
22096
- * ```js
22097
- * import { NotificationTrayRepository } from '@amityco/ts-sdk'
22098
- * const updated = await NotificationTrayRepository.markNotificationItemsSeen()
22099
- * ```
22100
- *
22101
- * Updates an {@link Amity.NotificationItemSeen}
22102
- *
22103
- * @param trayItems[] that include id and lastTraySeenAt, The ID of the {@link Amity.NotificationItemSeen} to edit
22104
- * @returns the updated {@link Amity.NotificationItemSeen} object
22105
- *
22106
- * @category NotificationItemSeen API
22107
- * @async
22108
- */
22109
- const markNotificationItemsSeen = async (patch) => {
22110
- const client = getActiveClient();
22111
- client.log('notificationTray/markNotificationItemsSeen', {});
22112
- const { data: payload } = await client.http.put(`api/v1/notification-tray/items/seen`, {
22113
- patch,
22114
- });
22115
- const updatedData = patch.trayItems
22116
- .map(patchItem => {
22117
- var _a;
22118
- const cacheData = (_a = pullFromCache([
22119
- 'notificationTraySeen',
22120
- 'get',
22121
- patchItem.id,
22122
- ])) === null || _a === void 0 ? void 0 : _a.data;
22123
- if (!cacheData)
22124
- return;
22125
- const data = Object.assign(Object.assign({}, cacheData), payload);
22126
- if (client.cache) {
22127
- const cachedAt = Date.now();
22128
- pushToCache(['notificationTrayItem', 'get'], data, { cachedAt });
22129
- }
22130
- return data;
22131
- })
22132
- .filter(Boolean);
22133
- fireEvent('local.notificationTrayItem.updated', { notificationTrayItems: updatedData });
22134
- };
22135
- /* end_public_function */
22136
-
22137
- const notificationTrayLinkedObject = (noti) => {
22138
- return Object.assign(Object.assign({}, noti), { isSeen: noti.lastSeenAt > noti.lastOccuredAt, isRecent: new Date(noti.lastOccuredAt).getTime() >= Date.now() - WEEK, users: noti.actors
22139
- .map(userId => { var _a; return (_a = pullFromCache(['user', 'get', userId])) === null || _a === void 0 ? void 0 : _a.data; })
22140
- .filter(isNonNullable)
22141
- .map(user => userLinkedObject(user)), markRead: () => markNotificationItemsSeen({
22142
- trayItems: [
22143
- {
22144
- id: noti._id,
22145
- lastSeenAt: noti.lastSeenAt,
22146
- },
22147
- ],
22148
- }) });
22149
- };
22150
-
22151
22316
  const LinkedObject = {
22152
22317
  ad: adLinkedObject,
22153
22318
  comment: commentLinkedObject,
@@ -22161,7 +22326,6 @@ const LinkedObject = {
22161
22326
  reactor: reactorLinkedObject,
22162
22327
  channel: channelLinkedObject,
22163
22328
  pinnedPost: pinnedPostLinkedObject,
22164
- notificationTray: notificationTrayLinkedObject,
22165
22329
  };
22166
22330
 
22167
22331
  const getChannelMessagePreviewWithUser = (channel) => {
@@ -22989,6 +23153,32 @@ const preUpdateChannelCache = (rawPayload, options = { isMessagePreviewUpdated:
22989
23153
  channels: rawPayload.channels.map(channel => convertFromRaw(channel, { isMessagePreviewUpdated: options.isMessagePreviewUpdated })),
22990
23154
  });
22991
23155
  };
23156
+ const updateChannelUnread = ({ currentUserId, channels, channelUsers, }) => {
23157
+ for (let i = 0; i < channels.length; i += 1) {
23158
+ const cacheKey = ['channelUnread', 'get', channels[i].channelId];
23159
+ const channelUser = channelUsers.find(channelUser => channelUser.channelId === channels[i].channelId && channelUser.userId === currentUserId);
23160
+ let unreadCount = 0;
23161
+ let readToSegment = null;
23162
+ let lastMentionedSegment = null;
23163
+ let isMentioned = false;
23164
+ if (channelUser) {
23165
+ readToSegment = channelUser.readToSegment;
23166
+ lastMentionedSegment = channelUser.lastMentionedSegment;
23167
+ unreadCount = Math.max(channels[i].messageCount - readToSegment, 0);
23168
+ isMentioned = lastMentionedSegment > readToSegment;
23169
+ }
23170
+ const cacheChannelUnread = {
23171
+ channelId: channels[i].channelId,
23172
+ lastSegment: channels[i].messageCount,
23173
+ readToSegment,
23174
+ lastMentionedSegment,
23175
+ unreadCount,
23176
+ isMentioned,
23177
+ isDeleted: channels[i].isDeleted || false,
23178
+ };
23179
+ pushToCache(cacheKey, cacheChannelUnread);
23180
+ }
23181
+ };
22992
23182
  const prepareChannelPayload = async (rawPayload, options = { isMessagePreviewUpdated: true }) => {
22993
23183
  const client = getActiveClient();
22994
23184
  const networkPreviewSetting = await client.getMessagePreviewSetting(false);
@@ -22998,23 +23188,34 @@ const prepareChannelPayload = async (rawPayload, options = { isMessagePreviewUpd
22998
23188
  rawPayload.messagePreviews.length > 0) {
22999
23189
  updateChannelMessagePreviewCache(rawPayload);
23000
23190
  }
23001
- const markerIds = rawPayload.channels
23002
- // filter channel by type. Only conversation, community and broadcast type are included.
23003
- .filter(isUnreadCountSupport)
23004
- .map(({ channelInternalId }) => channelInternalId);
23005
- if (markerIds.length > 0) {
23006
- // since the get markers method requires a channel cache to function with the reducer.
23007
- preUpdateChannelCache(rawPayload, { isMessagePreviewUpdated: options.isMessagePreviewUpdated });
23008
- try {
23009
- await getChannelMarkers(markerIds);
23010
- }
23011
- catch (e) {
23012
- // empty block (from the spec, allow marker fetch to fail without having to do anything)
23191
+ if (client.useLegacyUnreadCount) {
23192
+ updateChannelUnread({
23193
+ channels: rawPayload.channels,
23194
+ channelUsers: rawPayload.channelUsers,
23195
+ currentUserId: client.userId,
23196
+ });
23197
+ }
23198
+ else {
23199
+ const markerIds = rawPayload.channels
23200
+ // filter channel by type. Only conversation, community and broadcast type are included.
23201
+ .filter(isUnreadCountSupport)
23202
+ .map(({ channelInternalId }) => channelInternalId);
23203
+ if (markerIds.length > 0) {
23204
+ // since the get markers method requires a channel cache to function with the reducer.
23205
+ preUpdateChannelCache(rawPayload, {
23206
+ isMessagePreviewUpdated: options.isMessagePreviewUpdated,
23207
+ });
23208
+ try {
23209
+ await getChannelMarkers(markerIds);
23210
+ }
23211
+ catch (e) {
23212
+ // empty block (from the spec, allow marker fetch to fail without having to do anything)
23213
+ }
23013
23214
  }
23014
23215
  }
23015
- // attach marker to channel
23216
+ // convert raw channel to internal channel
23016
23217
  const channels = rawPayload.channels.map(payload => convertFromRaw(payload, { isMessagePreviewUpdated: options.isMessagePreviewUpdated }));
23017
- // user marker to channel users
23218
+ // convert raw channel user to membership (add user object)
23018
23219
  const channelUsers = rawPayload.channelUsers.map(channelUser => {
23019
23220
  return convertRawMembershipToMembership(channelUser);
23020
23221
  });
@@ -23141,15 +23342,28 @@ const getSubChannelsUnreadCount = (channel, marker) => {
23141
23342
  return (_e = (_c = marker === null || marker === void 0 ? void 0 : marker.unreadCount) !== null && _c !== void 0 ? _c : (_d = getCachedMarker(channel.channelInternalId)) === null || _d === void 0 ? void 0 : _d.unreadCount) !== null && _e !== void 0 ? _e : 0;
23142
23343
  };
23143
23344
 
23345
+ const getLegacyChannelUnread = (channelId) => {
23346
+ var _a;
23347
+ return (_a = pullFromCache(['channelUnread', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
23348
+ };
23349
+
23144
23350
  const constructChannelDynamicValue = (channel) => {
23351
+ const client = getActiveClient();
23145
23352
  const rest = __rest(channel, ["messageCount"]);
23146
23353
  return shallowClone(rest, {
23147
- get isMentioned() {
23148
- return getChannelIsMentioned(rest);
23354
+ get unreadCount() {
23355
+ var _a, _b;
23356
+ return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.unreadCount) !== null && _b !== void 0 ? _b : 0;
23149
23357
  },
23150
23358
  get subChannelsUnreadCount() {
23151
23359
  return getSubChannelsUnreadCount(rest);
23152
23360
  },
23361
+ get isMentioned() {
23362
+ var _a, _b;
23363
+ if (client.useLegacyUnreadCount)
23364
+ return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.isMentioned) !== null && _b !== void 0 ? _b : false;
23365
+ return getChannelIsMentioned(rest);
23366
+ },
23153
23367
  });
23154
23368
  };
23155
23369
 
@@ -23762,6 +23976,12 @@ const setClientToken = async (params) => {
23762
23976
  isGlobalBanned: false,
23763
23977
  isUserDeleted: false,
23764
23978
  };
23979
+ client.upload.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
23980
+ client.upload.defaults.metadata = {
23981
+ tokenExpiry: expiresAt,
23982
+ isGlobalBanned: false,
23983
+ isUserDeleted: false,
23984
+ };
23765
23985
  // manually setup the token for ws transport
23766
23986
  if (client.ws)
23767
23987
  client.ws.io.opts.query = { token: accessToken };
@@ -23806,12 +24026,21 @@ const onChannelDeleted = (callback) => {
23806
24026
  const client = getActiveClient();
23807
24027
  const filter = async (payload) => {
23808
24028
  const data = await prepareChannelPayload(payload);
23809
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
23810
- data.channels.forEach(channel => {
24029
+ const isConsistentMode = client.getMarkerSyncConsistentMode() && client.isUnreadCountEnabled;
24030
+ const isLegacyUnreadCount = client.useLegacyUnreadCount;
24031
+ data.channels.forEach(channel => {
24032
+ if (isConsistentMode) {
23811
24033
  addFlagIsDeletedSubChannelUnreadByChannelId(channel.channelId);
23812
24034
  deleteChannelUnreadByChannelId(channel.channelId);
23813
- });
23814
- }
24035
+ }
24036
+ else if (isLegacyUnreadCount) {
24037
+ const cacheKey = ['channelUnread', 'get', channel.channelId];
24038
+ const cache = pullFromCache(cacheKey);
24039
+ if (cache) {
24040
+ pushToCache(cacheKey, Object.assign(Object.assign({}, cache), { isDeleted: true }));
24041
+ }
24042
+ }
24043
+ });
23815
24044
  ingestInCache(data);
23816
24045
  callbacks$b.forEach(cb => cb(data.channels[0]));
23817
24046
  };
@@ -23925,6 +24154,25 @@ var readReceiptSyncEngineOnLoginHandler = () => {
23925
24154
  };
23926
24155
  };
23927
24156
 
24157
+ var legacyReadReceiptSyncEngineOnLoginHandler = () => {
24158
+ const readReceiptSyncEngine = LegacyReadReceiptSyncEngine.getInstance();
24159
+ readReceiptSyncEngine.startSyncReadReceipt();
24160
+ onSessionStateChange(state => {
24161
+ if (state === "established" /* Amity.SessionStates.ESTABLISHED */) {
24162
+ readReceiptSyncEngine.onSessionEstablished();
24163
+ }
24164
+ else if (state === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
24165
+ readReceiptSyncEngine.onTokenExpired();
24166
+ }
24167
+ else {
24168
+ readReceiptSyncEngine.onSessionDestroyed();
24169
+ }
24170
+ });
24171
+ return () => {
24172
+ readReceiptSyncEngine.onSessionDestroyed();
24173
+ };
24174
+ };
24175
+
23928
24176
  const onOnline = (callback) => {
23929
24177
  if (typeof window !== 'undefined' && window.addEventListener) {
23930
24178
  window.addEventListener('online', callback);
@@ -24491,10 +24739,17 @@ const onChannelLeft = (callback) => {
24491
24739
  const preparedPayload = await prepareChannelPayload(payload, {
24492
24740
  isMessagePreviewUpdated: isLeftByMe,
24493
24741
  });
24494
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode() && isLeftByMe) {
24742
+ const isConsistentMode = client.getMarkerSyncConsistentMode() && client.isUnreadCountEnabled;
24743
+ const isLegacyUnreadCount = client.useLegacyUnreadCount;
24744
+ if (isLeftByMe) {
24495
24745
  preparedPayload.channels.forEach(channel => {
24496
- addFlagIsDeletedSubChannelUnreadByChannelId(channel.channelId);
24497
- deleteChannelUnreadByChannelId(channel.channelId);
24746
+ if (isConsistentMode) {
24747
+ addFlagIsDeletedSubChannelUnreadByChannelId(channel.channelId);
24748
+ deleteChannelUnreadByChannelId(channel.channelId);
24749
+ }
24750
+ else if (isLegacyUnreadCount) {
24751
+ dropFromCache(['channelUnread', 'get', channel.channelId]);
24752
+ }
24498
24753
  });
24499
24754
  }
24500
24755
  const { channels, channelUsers } = preparedPayload;
@@ -24762,6 +25017,34 @@ const onMessageCreatedMqtt = (callback) => {
24762
25017
  reCalculateChannelUnreadInfo(message.channelId);
24763
25018
  });
24764
25019
  }
25020
+ if (client.useLegacyUnreadCount) {
25021
+ rawPayload.messages.forEach(message => {
25022
+ var _a, _b;
25023
+ const channelUnread = (_a = pullFromCache([
25024
+ 'channelUnread',
25025
+ 'get',
25026
+ message.channelId,
25027
+ ])) === null || _a === void 0 ? void 0 : _a.data;
25028
+ if (!channelUnread ||
25029
+ channelUnread.lastSegment >= message.segment ||
25030
+ typeof channelUnread.readToSegment !== 'number' ||
25031
+ typeof channelUnread.lastMentionedSegment !== 'number')
25032
+ return;
25033
+ const lastSegment = message.segment;
25034
+ const isMentionedInMessage = (_b = message.mentionedUsers) === null || _b === void 0 ? void 0 : _b.some(mention => {
25035
+ return (mention.type === 'channel' ||
25036
+ (mention.type === 'user' &&
25037
+ client.userId &&
25038
+ mention.userPublicIds.includes(client.userId)));
25039
+ });
25040
+ const lastMentionedSegment = isMentionedInMessage
25041
+ ? message.segment
25042
+ : channelUnread.lastMentionedSegment;
25043
+ const updatedChannelUnread = Object.assign(Object.assign({}, channelUnread), { lastSegment, unreadCount: Math.max(lastSegment - channelUnread.readToSegment, 0), lastMentionedSegment, isMentioned: !(channelUnread.readToSegment >= lastMentionedSegment) });
25044
+ pushToCache(['channelUnread', 'get', message.channelId], updatedChannelUnread);
25045
+ fireEvent('local.channelUnread.updated', updatedChannelUnread);
25046
+ });
25047
+ }
24765
25048
  // Update in cache
24766
25049
  ingestInCache(payload);
24767
25050
  payload.messages.forEach(message => {
@@ -24937,6 +25220,7 @@ const enableUnreadCount = () => {
24937
25220
  if (client.isUnreadCountEnabled)
24938
25221
  return false;
24939
25222
  client.isUnreadCountEnabled = true;
25223
+ client.useLegacyUnreadCount = false;
24940
25224
  client.emitter.emit('unreadCountEnabled', true);
24941
25225
  return true;
24942
25226
  };
@@ -25252,7 +25536,12 @@ const login = async (params, sessionHandler, config) => {
25252
25536
  // NOTE: This is a temporary solution to handle the channel marker when the user is forced to leave
25253
25537
  // the channel because currently backend can't handle this, so every time a user is banned from
25254
25538
  // a channel or the channel is deleted the channel's unread count will not be reset to zero
25255
- onChannelDeleted(removeChannelMarkerCache), onChannelMemberBanned(removeChannelMarkerCache), markReadEngineOnLoginHandler(), analyticsEngineOnLoginHandler(), readReceiptSyncEngineOnLoginHandler(), objectResolverEngineOnLoginHandler());
25539
+ onChannelDeleted(removeChannelMarkerCache), onChannelMemberBanned(removeChannelMarkerCache), markReadEngineOnLoginHandler(), analyticsEngineOnLoginHandler(), objectResolverEngineOnLoginHandler());
25540
+ if (client.useLegacyUnreadCount) {
25541
+ subscriptions.push(readReceiptSyncEngineOnLoginHandler());
25542
+ }
25543
+ else
25544
+ subscriptions.push(legacyReadReceiptSyncEngineOnLoginHandler());
25256
25545
  const markerSyncUnsubscriber = await startMarkerSync();
25257
25546
  subscriptions.push(markerSyncUnsubscriber);
25258
25547
  }
@@ -25410,15 +25699,17 @@ const DEFAULT_DEBUG_SESSION = 'amity';
25410
25699
  * @category Client API
25411
25700
  * */
25412
25701
  const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAULT_DEBUG_SESSION, apiEndpoint, prefixDeviceIdKey, rteEnabled = true, } = {}) => {
25413
- var _a, _b;
25702
+ var _a, _b, _c;
25414
25703
  const log = createLogger(debugSession);
25415
25704
  log('client/api/createClient', {
25416
25705
  apiKey: apiKey.replace(/.{5}$/g, 'xxxxx'),
25417
25706
  apiRegion,
25418
25707
  });
25419
25708
  const httpEndpoint = (_a = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.http) !== null && _a !== void 0 ? _a : computeUrl('http', apiRegion);
25420
- const mqttEndpoint = (_b = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.mqtt) !== null && _b !== void 0 ? _b : computeUrl('mqtt', apiRegion);
25709
+ const uploadEndpoint = (_b = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.upload) !== null && _b !== void 0 ? _b : computeUrl('upload', apiRegion);
25710
+ const mqttEndpoint = (_c = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.mqtt) !== null && _c !== void 0 ? _c : computeUrl('mqtt', apiRegion);
25421
25711
  const http = createHttpTransport(httpEndpoint);
25712
+ const upload = createHttpTransport(uploadEndpoint);
25422
25713
  let ws;
25423
25714
  let mqtt;
25424
25715
  if (rteEnabled) {
@@ -25433,6 +25724,8 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
25433
25724
  const sessionState = "notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */;
25434
25725
  const sessionHandler = undefined;
25435
25726
  const isUnreadCountEnabled = false;
25727
+ // Legacy unread count is true by default
25728
+ const useLegacyUnreadCount = true;
25436
25729
  const client = {
25437
25730
  version: `${VERSION}`,
25438
25731
  apiKey,
@@ -25447,6 +25740,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
25447
25740
  http,
25448
25741
  ws,
25449
25742
  mqtt,
25743
+ upload,
25450
25744
  emitter,
25451
25745
  /*
25452
25746
  * Session Components
@@ -25462,6 +25756,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
25462
25756
  getMessagePreviewSetting,
25463
25757
  use: () => setActiveClient(client),
25464
25758
  isUnreadCountEnabled,
25759
+ useLegacyUnreadCount,
25465
25760
  getMarkerSyncConsistentMode,
25466
25761
  /**
25467
25762
  * Prefix for the deviceId key in the local storage or async storage.
@@ -25475,7 +25770,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
25475
25770
  return activeClient;
25476
25771
  setActiveClient(client);
25477
25772
  }
25478
- catch (_c) {
25773
+ catch (_d) {
25479
25774
  setActiveClient(client);
25480
25775
  }
25481
25776
  return client;
@@ -25932,7 +26227,7 @@ const getUserUnread = (callback) => {
25932
26227
  };
25933
26228
  };
25934
26229
 
25935
- var index$m = /*#__PURE__*/Object.freeze({
26230
+ var index$l = /*#__PURE__*/Object.freeze({
25936
26231
  __proto__: null,
25937
26232
  getActiveClient: getActiveClient,
25938
26233
  getActiveUser: getActiveUser,
@@ -27139,7 +27434,7 @@ const getMyFollowInfo = (callback) => {
27139
27434
  };
27140
27435
  /* end_public_function */
27141
27436
 
27142
- var index$l = /*#__PURE__*/Object.freeze({
27437
+ var index$k = /*#__PURE__*/Object.freeze({
27143
27438
  __proto__: null,
27144
27439
  blockUser: blockUser,
27145
27440
  unBlockUser: unBlockUser,
@@ -28154,9 +28449,9 @@ var AmityUserSearchMatchType;
28154
28449
  AmityUserSearchMatchType["PARTIAL"] = "partial";
28155
28450
  })(AmityUserSearchMatchType || (AmityUserSearchMatchType = {}));
28156
28451
 
28157
- var index$k = /*#__PURE__*/Object.freeze({
28452
+ var index$j = /*#__PURE__*/Object.freeze({
28158
28453
  __proto__: null,
28159
- Relationship: index$l,
28454
+ Relationship: index$k,
28160
28455
  getUserByIds: getUserByIds,
28161
28456
  updateUser: updateUser,
28162
28457
  flagUser: flagUser,
@@ -28264,7 +28559,7 @@ const uploadFile = async (formData, onProgress) => {
28264
28559
  const headers = 'getHeaders' in formData
28265
28560
  ? formData.getHeaders()
28266
28561
  : { 'content-type': 'multipart/form-data' };
28267
- const { data } = await client.http.post('/api/v4/files', formData, {
28562
+ const { data } = await client.upload.post('/api/v4/files', formData, {
28268
28563
  headers,
28269
28564
  onUploadProgress({ loaded, total = 100 }) {
28270
28565
  onProgress && onProgress(Math.round((loaded * 100) / total));
@@ -28354,7 +28649,7 @@ const uploadVideo = async (formData, feedType, onProgress) => {
28354
28649
  const headers = 'getHeaders' in formData
28355
28650
  ? formData.getHeaders()
28356
28651
  : { 'content-type': 'multipart/form-data' };
28357
- const { data } = await client.http.post('/api/v4/videos', formData, {
28652
+ const { data } = await client.upload.post('/api/v4/videos', formData, {
28358
28653
  headers,
28359
28654
  onUploadProgress({ loaded, total = 100 }) {
28360
28655
  onProgress && onProgress(Math.round((loaded * 100) / total));
@@ -28402,7 +28697,7 @@ const uploadImage = async (formData, onProgress) => {
28402
28697
  const headers = 'getHeaders' in formData
28403
28698
  ? formData.getHeaders()
28404
28699
  : { 'content-type': 'multipart/form-data' };
28405
- const { data } = await client.http.post('/api/v4/images', formData, {
28700
+ const { data } = await client.upload.post('/api/v4/images', formData, {
28406
28701
  headers,
28407
28702
  onUploadProgress({ loaded, total = 100 }) {
28408
28703
  onProgress && onProgress(Math.round((loaded * 100) / total));
@@ -28420,7 +28715,7 @@ const uploadImage = async (formData, onProgress) => {
28420
28715
  };
28421
28716
  /* end_public_function */
28422
28717
 
28423
- var index$j = /*#__PURE__*/Object.freeze({
28718
+ var index$i = /*#__PURE__*/Object.freeze({
28424
28719
  __proto__: null,
28425
28720
  getFile: getFile,
28426
28721
  uploadFile: uploadFile,
@@ -30232,7 +30527,7 @@ const getReactions = (params, callback, config) => {
30232
30527
  };
30233
30528
  /* end_public_function */
30234
30529
 
30235
- var index$i = /*#__PURE__*/Object.freeze({
30530
+ var index$h = /*#__PURE__*/Object.freeze({
30236
30531
  __proto__: null,
30237
30532
  addReaction: addReaction,
30238
30533
  removeReaction: removeReaction,
@@ -32048,7 +32343,7 @@ const getMessages = (params, callback, config) => {
32048
32343
  };
32049
32344
  /* end_public_function */
32050
32345
 
32051
- var index$h = /*#__PURE__*/Object.freeze({
32346
+ var index$g = /*#__PURE__*/Object.freeze({
32052
32347
  __proto__: null,
32053
32348
  createMessage: createMessage,
32054
32349
  updateMessage: updateMessage,
@@ -32574,7 +32869,7 @@ const stopMessageReceiptSync = (subChannelId) => {
32574
32869
  };
32575
32870
  /* end_public_function */
32576
32871
 
32577
- var index$g = /*#__PURE__*/Object.freeze({
32872
+ var index$f = /*#__PURE__*/Object.freeze({
32578
32873
  __proto__: null,
32579
32874
  getSubChannelByIds: getSubChannels$1,
32580
32875
  createSubChannel: createSubChannel,
@@ -32595,19 +32890,37 @@ var index$g = /*#__PURE__*/Object.freeze({
32595
32890
  /**
32596
32891
  * Internal used only
32597
32892
  *
32598
- * Fired when an {@link Amity.userMessageFeedMarkers} has been resolved by Object Rsesolver
32893
+ * Fired when an {@link Amity.channelUnreadInfo} has been updated.
32599
32894
  *
32600
32895
  * @param callback The function to call when the event was fired
32601
32896
  * @returns an {@link Amity.Unsubscriber} function to stop listening
32602
32897
  *
32603
- * @category MessageMarker Events
32898
+ * @category ChannelMarker Events
32899
+ */
32900
+ const onChannelUnreadInfoUpdatedLocal = (callback) => {
32901
+ const client = getActiveClient();
32902
+ const filter = (payload) => {
32903
+ callback(payload);
32904
+ };
32905
+ return createEventSubscriber(client, 'channelMarker/onChannelUnreadInfoUpdatedLocal', 'local.channelUnreadInfo.updated', filter);
32906
+ };
32907
+
32908
+ /**
32909
+ * Internal used only
32910
+ *
32911
+ * Fired when an {@link Amity.ChannelUnread} has been updated.
32912
+ *
32913
+ * @param callback The function to call when the event was fired
32914
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
32915
+ *
32916
+ * @category Channel Events
32604
32917
  */
32605
32918
  const onChannelUnreadUpdatedLocal = (callback) => {
32606
32919
  const client = getActiveClient();
32607
32920
  const filter = (payload) => {
32608
32921
  callback(payload);
32609
32922
  };
32610
- return createEventSubscriber(client, 'channelMarker/onChannelUnreadUpdatedLocal', 'local.channelUnread.updated', filter);
32923
+ return createEventSubscriber(client, 'channel/onChannelUnreadUpdatedLocal', 'local.channelUnread.updated', filter);
32611
32924
  };
32612
32925
 
32613
32926
  /* begin_public_function
@@ -32809,6 +33122,7 @@ const getChannel = (channelId, callback) => {
32809
33122
  return onSubChannelUpdated(updateMessagePreview);
32810
33123
  }, 'channelId', 'channel'),
32811
33124
  convertEventPayload(onSubChannelCreated, 'channelId', 'channel'),
33125
+ convertEventPayload(onChannelUnreadInfoUpdatedLocal, 'channelId', 'channel'),
32812
33126
  convertEventPayload(onChannelUnreadUpdatedLocal, 'channelId', 'channel'),
32813
33127
  ], {
32814
33128
  forceDispatch: true,
@@ -33322,6 +33636,10 @@ class ChannelLiveCollectionController extends LiveCollectionController {
33322
33636
  },
33323
33637
  action: "OnResolveUnread" /* Amity.ChannelActionType.OnResolveUnread */,
33324
33638
  },
33639
+ {
33640
+ fn: convertEventPayload(onChannelUnreadInfoUpdatedLocal, 'channelId', 'channel'),
33641
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
33642
+ },
33325
33643
  {
33326
33644
  fn: convertEventPayload(onChannelUnreadUpdatedLocal, 'channelId', 'channel'),
33327
33645
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
@@ -33387,6 +33705,120 @@ const getChannels = (params, callback, config) => {
33387
33705
  };
33388
33706
  /* end_public_function */
33389
33707
 
33708
+ /**
33709
+ *
33710
+ * Calculate user unread from {@link Amity.ChannelUnread} objects
33711
+ *
33712
+ * @returns the {@link Amity.UserUnread} objects
33713
+ *
33714
+ * @category Channel API
33715
+ * @async
33716
+ */
33717
+ const getTotalChannelsUnread$1 = () => {
33718
+ var _a;
33719
+ const client = getActiveClient();
33720
+ client.log('channel/getTotalChannelsUnread.locally');
33721
+ const cachedChannelsUnread = ((_a = queryCache(['channelUnread', 'get'])) === null || _a === void 0 ? void 0 : _a.filter(({ data }) => {
33722
+ return !data.isDeleted;
33723
+ })) || [];
33724
+ const totalChannelsUnread = (cachedChannelsUnread === null || cachedChannelsUnread === void 0 ? void 0 : cachedChannelsUnread.reduce((acc, { data }) => {
33725
+ acc.unreadCount += data.unreadCount;
33726
+ acc.isMentioned = acc.isMentioned || data.isMentioned;
33727
+ return acc;
33728
+ }, { unreadCount: 0, isMentioned: false })) || { unreadCount: 0, isMentioned: false };
33729
+ const cachedAt = client.cache && Date.now();
33730
+ return {
33731
+ data: totalChannelsUnread,
33732
+ cachedAt,
33733
+ };
33734
+ };
33735
+
33736
+ /* begin_public_function
33737
+ id: totalChannelsUnread.get
33738
+ */
33739
+ /**
33740
+ * ```js
33741
+ * import { ChannelRepository } from '@amityco/ts-sdk';
33742
+ *
33743
+ * let totalChannelsUnread;
33744
+ *
33745
+ * const unsubscribe = ChannelRepository.getTotalChannelsUnread(response => {
33746
+ * unread = response.data;
33747
+ * });
33748
+ * ```
33749
+ *
33750
+ * Observe all mutation on a given {@link Amity.UserUnread}
33751
+ *
33752
+ * @returns An {@link Amity.UserUnread} function to run when willing to stop observing the message
33753
+ *
33754
+ * @category User Unread Live Object
33755
+ *
33756
+ */
33757
+ const getTotalChannelsUnread = (callback) => {
33758
+ const { _id: userId } = getActiveUser();
33759
+ if (!userId)
33760
+ throw new ASCError('The _id has not been defined in ActiveUser', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
33761
+ const { log, cache } = getActiveClient();
33762
+ if (!cache) {
33763
+ console.log('For using Live Object feature you need to enable Cache!');
33764
+ }
33765
+ const timestamp = Date.now();
33766
+ log(`liveTotalChannelsUnread(tmpid: ${timestamp}) > listen`);
33767
+ const disposers = [];
33768
+ let isUnsyncedModel = false; // for messages
33769
+ let model;
33770
+ const dispatcher = (data) => {
33771
+ const { data: userUnread } = data;
33772
+ const callbackModel = userUnread
33773
+ ? {
33774
+ unreadCount: userUnread.unreadCount,
33775
+ isMentioned: userUnread.isMentioned,
33776
+ }
33777
+ : undefined;
33778
+ model = callbackModel ? convertGetterPropsToStatic(callbackModel) : callbackModel;
33779
+ callback({
33780
+ data: callbackModel
33781
+ ? Object.assign(Object.assign({}, callbackModel), { isMentioned: callbackModel.isMentioned }) : callbackModel,
33782
+ loading: data.loading,
33783
+ error: data.error,
33784
+ });
33785
+ };
33786
+ const realtimeRouter = (userUnread) => {
33787
+ if (isEqual(model, userUnread))
33788
+ return;
33789
+ dispatcher({
33790
+ loading: false,
33791
+ data: userUnread,
33792
+ });
33793
+ };
33794
+ const onFetch = () => {
33795
+ const query = createQuery(async () => getTotalChannelsUnread$1());
33796
+ runQuery(query, ({ error, data, loading, origin, cachedAt }) => {
33797
+ if (cachedAt === UNSYNCED_OBJECT_CACHED_AT_VALUE) {
33798
+ dispatcher({
33799
+ data,
33800
+ origin,
33801
+ loading: false,
33802
+ error: new ASCApiError(UNSYNCED_OBJECT_CACHED_AT_MESSAGE, 800800 /* Amity.ClientError.DISALOOW_UNSYNCED_OBJECT */, "error" /* Amity.ErrorLevel.ERROR */),
33803
+ });
33804
+ isUnsyncedModel = true;
33805
+ disposers.forEach(fn => fn());
33806
+ }
33807
+ else if (!isUnsyncedModel) {
33808
+ dispatcher({ loading, data, origin, error });
33809
+ }
33810
+ if (error) {
33811
+ disposers.forEach(fn => fn());
33812
+ }
33813
+ });
33814
+ };
33815
+ disposers.push(onChannelUnreadUpdatedLocal(realtimeRouter));
33816
+ onFetch();
33817
+ return () => {
33818
+ disposers.forEach(fn => fn());
33819
+ };
33820
+ };
33821
+
33390
33822
  /* begin_public_function
33391
33823
  id: channel.member.add
33392
33824
  */
@@ -33751,7 +34183,7 @@ const searchMembers$1 = (params, callback, config) => {
33751
34183
  };
33752
34184
  /* end_public_function */
33753
34185
 
33754
- var index$f = /*#__PURE__*/Object.freeze({
34186
+ var index$e = /*#__PURE__*/Object.freeze({
33755
34187
  __proto__: null,
33756
34188
  addMembers: addMembers$1,
33757
34189
  removeMembers: removeMembers$1,
@@ -33954,7 +34386,7 @@ const unmuteMembers = async (channelId, userIds) => {
33954
34386
  };
33955
34387
  /* end_public_function */
33956
34388
 
33957
- var index$e = /*#__PURE__*/Object.freeze({
34389
+ var index$d = /*#__PURE__*/Object.freeze({
33958
34390
  __proto__: null,
33959
34391
  addRole: addRole,
33960
34392
  removeRole: removeRole,
@@ -33964,10 +34396,10 @@ var index$e = /*#__PURE__*/Object.freeze({
33964
34396
  unmuteMembers: unmuteMembers
33965
34397
  });
33966
34398
 
33967
- var index$d = /*#__PURE__*/Object.freeze({
34399
+ var index$c = /*#__PURE__*/Object.freeze({
33968
34400
  __proto__: null,
33969
- Membership: index$f,
33970
- Moderation: index$e,
34401
+ Membership: index$e,
34402
+ Moderation: index$d,
33971
34403
  getChannelByIds: getChannelByIds$1,
33972
34404
  createChannel: createChannel,
33973
34405
  updateChannel: updateChannel,
@@ -33990,6 +34422,7 @@ var index$d = /*#__PURE__*/Object.freeze({
33990
34422
  onChannelMemberRoleRemoved: onChannelMemberRoleRemoved,
33991
34423
  getChannel: getChannel,
33992
34424
  getChannels: getChannels,
34425
+ getTotalChannelsUnread: getTotalChannelsUnread,
33993
34426
  MARKER_INCLUDED_CHANNEL_TYPE: MARKER_INCLUDED_CHANNEL_TYPE,
33994
34427
  isUnreadCountSupport: isUnreadCountSupport,
33995
34428
  convertFromRaw: convertFromRaw,
@@ -35346,7 +35779,7 @@ const searchMembers = (params, callback, config) => {
35346
35779
  };
35347
35780
  /* end_public_function */
35348
35781
 
35349
- var index$c = /*#__PURE__*/Object.freeze({
35782
+ var index$b = /*#__PURE__*/Object.freeze({
35350
35783
  __proto__: null,
35351
35784
  addMembers: addMembers,
35352
35785
  removeMembers: removeMembers,
@@ -36371,7 +36804,7 @@ const unbanMembers = async (communityId, userIds) => {
36371
36804
  };
36372
36805
  /* end_public_function */
36373
36806
 
36374
- var index$b = /*#__PURE__*/Object.freeze({
36807
+ var index$a = /*#__PURE__*/Object.freeze({
36375
36808
  __proto__: null,
36376
36809
  addRoles: addRoles,
36377
36810
  removeRoles: removeRoles,
@@ -36379,10 +36812,10 @@ var index$b = /*#__PURE__*/Object.freeze({
36379
36812
  unbanMembers: unbanMembers
36380
36813
  });
36381
36814
 
36382
- var index$a = /*#__PURE__*/Object.freeze({
36815
+ var index$9 = /*#__PURE__*/Object.freeze({
36383
36816
  __proto__: null,
36384
- Moderation: index$b,
36385
- Membership: index$c,
36817
+ Moderation: index$a,
36818
+ Membership: index$b,
36386
36819
  getCommunityByIds: getCommunities$1,
36387
36820
  createCommunity: createCommunity,
36388
36821
  updateCommunity: updateCommunity,
@@ -36615,7 +37048,7 @@ const getCategories = (params, callback, config) => {
36615
37048
  };
36616
37049
  /* end_public_function */
36617
37050
 
36618
- var index$9 = /*#__PURE__*/Object.freeze({
37051
+ var index$8 = /*#__PURE__*/Object.freeze({
36619
37052
  __proto__: null,
36620
37053
  getCategory: getCategory,
36621
37054
  getCategories: getCategories
@@ -36783,7 +37216,7 @@ getCustomRankingGlobalFeed.locally = (query) => {
36783
37216
  : undefined;
36784
37217
  };
36785
37218
 
36786
- var index$8 = /*#__PURE__*/Object.freeze({
37219
+ var index$7 = /*#__PURE__*/Object.freeze({
36787
37220
  __proto__: null,
36788
37221
  queryGlobalFeed: queryGlobalFeed,
36789
37222
  getCustomRankingGlobalFeed: getCustomRankingGlobalFeed
@@ -38098,7 +38531,7 @@ const getComments = (params, callback, config) => {
38098
38531
  };
38099
38532
  /* end_public_function */
38100
38533
 
38101
- var index$7 = /*#__PURE__*/Object.freeze({
38534
+ var index$6 = /*#__PURE__*/Object.freeze({
38102
38535
  __proto__: null,
38103
38536
  getCommentByIds: getCommentByIds,
38104
38537
  createComment: createComment,
@@ -39105,7 +39538,7 @@ const semanticSearchPosts = (params, callback, config) => {
39105
39538
  };
39106
39539
  };
39107
39540
 
39108
- var index$6 = /*#__PURE__*/Object.freeze({
39541
+ var index$5 = /*#__PURE__*/Object.freeze({
39109
39542
  __proto__: null,
39110
39543
  getPostByIds: getPostByIds,
39111
39544
  createPost: createPost,
@@ -39639,7 +40072,7 @@ const getStreams = (params, callback, config) => {
39639
40072
  };
39640
40073
  };
39641
40074
 
39642
- var index$5 = /*#__PURE__*/Object.freeze({
40075
+ var index$4 = /*#__PURE__*/Object.freeze({
39643
40076
  __proto__: null,
39644
40077
  createStream: createStream,
39645
40078
  updateStream: updateStream,
@@ -39926,7 +40359,7 @@ const getPoll = (pollId, callback) => {
39926
40359
  };
39927
40360
  /* end_public_function */
39928
40361
 
39929
- var index$4 = /*#__PURE__*/Object.freeze({
40362
+ var index$3 = /*#__PURE__*/Object.freeze({
39930
40363
  __proto__: null,
39931
40364
  createPoll: createPoll,
39932
40365
  closePoll: closePoll,
@@ -40297,7 +40730,7 @@ const getPlayer = async (parameters) => {
40297
40730
  return video;
40298
40731
  };
40299
40732
 
40300
- var index$3 = /*#__PURE__*/Object.freeze({
40733
+ var index$2 = /*#__PURE__*/Object.freeze({
40301
40734
  __proto__: null,
40302
40735
  getPlayer: getPlayer
40303
40736
  });
@@ -41470,7 +41903,7 @@ const getGlobalStoryTargets = (params, callback, config) => {
41470
41903
  };
41471
41904
  };
41472
41905
 
41473
- var index$2 = /*#__PURE__*/Object.freeze({
41906
+ var index$1 = /*#__PURE__*/Object.freeze({
41474
41907
  __proto__: null,
41475
41908
  createImageStory: createImageStory,
41476
41909
  createVideoStory: createVideoStory,
@@ -41507,7 +41940,7 @@ const getNetworkAds = async () => {
41507
41940
  };
41508
41941
  };
41509
41942
 
41510
- var index$1 = /*#__PURE__*/Object.freeze({
41943
+ var index = /*#__PURE__*/Object.freeze({
41511
41944
  __proto__: null,
41512
41945
  getNetworkAds: getNetworkAds
41513
41946
  });
@@ -41534,314 +41967,4 @@ const createUserToken = async (apiKey, apiRegion, params) => {
41534
41967
  return { accessToken: data.accessToken };
41535
41968
  };
41536
41969
 
41537
- /* begin_public_function
41538
- id: notificationTray.getNotificationTraySeen
41539
- */
41540
- /**
41541
- * ```js
41542
- * import { NotificationTrayRepository } from '@amityco/ts-sdk'
41543
- * const notificationTraySeen = await NotificationTrayRepository.getNotificationTraySeen()
41544
- * ```
41545
- *
41546
- *
41547
- * @returns A page of {@link Amity.NotificationTraySeen} objects
41548
- *
41549
- * @category NotificationTray API
41550
- * @async
41551
- * */
41552
- const getNotificationTraySeen$1 = async () => {
41553
- const client = getActiveClient();
41554
- client.log('notificationTray/getNotificationTraySeen', {});
41555
- const { data: payload } = await client.http.get(`api/v1/notification-tray/tray/seen`);
41556
- const cachedAt = client.cache && Date.now();
41557
- if (client.cache) {
41558
- const cacheKey = ['notificationTraySeen', 'get', client.userId];
41559
- pushToCache(cacheKey, {
41560
- userId: client.userId,
41561
- lastTraySeenAt: payload.lastTraySeenAt,
41562
- lastTrayOccuredAt: payload.lastTrayOccuredAt,
41563
- });
41564
- }
41565
- return {
41566
- data: {
41567
- userId: client.userId,
41568
- lastTraySeenAt: payload.lastTraySeenAt,
41569
- lastTrayOccuredAt: payload.lastTrayOccuredAt,
41570
- isSeen: payload.lastTraySeenAt > payload.lastTrayOccuredAt,
41571
- },
41572
- cachedAt,
41573
- };
41574
- };
41575
- /* end_public_function */
41576
- /**
41577
- * ```js
41578
- * import { NotificationTrayRepository } from '@amityco/ts-sdk'
41579
- * const notificationTraySeen = await NotificationTrayRepository.getNotificationTraySeen.locally()
41580
- * ```
41581
- *
41582
- * Queries a paginable list of {@link Amity.NotificationTraySeen} objects from cache
41583
- *
41584
- * @returns A page of {@link Amity.NotificationTraySeen} objects
41585
- *
41586
- * @category NotificationTray API
41587
- * @async
41588
- * */
41589
- getNotificationTraySeen$1.locally = () => {
41590
- var _a;
41591
- const client = getActiveClient();
41592
- client.log('notificationTray/getNotificationTraySeen.locally', {});
41593
- if (!client.cache)
41594
- return;
41595
- const queryKey = ['notificationTraySeen', 'get'];
41596
- const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
41597
- if (!(data === null || data === void 0 ? void 0 : data.notificationTraySeen))
41598
- return;
41599
- return { data: data.notificationTraySeen, cachedAt };
41600
- };
41601
-
41602
- /**
41603
- * ```js
41604
- * import { onNotificationTraySeenUpdated } from '@amityco/ts-sdk'
41605
- * const dispose = onNotificationTraySeenUpdated(data => {
41606
- * // ...
41607
- * })
41608
- * ```
41609
- *
41610
- * Fired when an {@link Amity.NotificationTraySeen} has been updated
41611
- *
41612
- * @param callback The function to call when the event was fired
41613
- * @returns an {@link Amity.Unsubscriber} function to stop listening
41614
- *
41615
- * @category NotificationTraySeen Events
41616
- */
41617
- const onNotificationTraySeenUpdated = (callback) => {
41618
- const client = getActiveClient();
41619
- const disposers = [
41620
- createEventSubscriber(client, 'onNotificationTraySeenUpdated', 'local.notificationTraySeen.updated', payload => callback(payload)),
41621
- ];
41622
- return () => {
41623
- disposers.forEach(fn => fn());
41624
- };
41625
- };
41626
-
41627
- /* begin_public_function
41628
- id: notificationTraySeen.get
41629
- */
41630
- /**
41631
- * ```js
41632
- * import { getNotificationTraySeen } from '@amityco/ts-sdk';
41633
- *
41634
- * let notificationTraySeen;
41635
- *
41636
- * const unsubscribe = getNotificationTraySeen(userId, response => {
41637
- * notificationTraySeen = response.data;
41638
- * });
41639
- * ```
41640
- *
41641
- * Observe all mutation on a given {@link Amity.NotificationTraySeen}
41642
- *
41643
- * @param userId the ID of the user to observe
41644
- * @param callback the function to call when new data are available
41645
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the message
41646
- *
41647
- * @category NotificationTraySeen Live Object
41648
- */
41649
- const getNotificationTraySeen = (callback) => {
41650
- const responder = (snapshot) => {
41651
- const { data } = snapshot;
41652
- callback(Object.assign(Object.assign({}, snapshot), { data }));
41653
- };
41654
- const { userId } = getActiveUser();
41655
- return liveObject(userId, responder, 'userId', getNotificationTraySeen$1, [
41656
- onNotificationTraySeenUpdated,
41657
- ]);
41658
- };
41659
- /* end_public_function */
41660
-
41661
- /**
41662
- * TODO: handle cache receive cache option, and cache policy
41663
- * TODO: check if querybyIds is supported
41664
- */
41665
- class NotificationTrayItemsPaginationController extends PaginationController {
41666
- async getRequest(queryParams, token) {
41667
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
41668
- const options = token ? { token } : { limit };
41669
- const { data: queryResponse } = await this.http.get(`/api/v1/notification-tray`, {
41670
- params: Object.assign(Object.assign({}, params), { options }),
41671
- });
41672
- return queryResponse;
41673
- }
41674
- }
41675
-
41676
- class NotificationTrayItemsQuerystreamController extends QueryStreamController {
41677
- constructor(query, cacheKey, notifyChange, preparePayload) {
41678
- super(query, cacheKey);
41679
- this.notifyChange = notifyChange;
41680
- this.preparePayload = preparePayload;
41681
- }
41682
- async saveToMainDB(response) {
41683
- const processedPayload = await this.preparePayload(response);
41684
- const client = getActiveClient();
41685
- const cachedAt = client.cache && Date.now();
41686
- if (client.cache) {
41687
- ingestInCache(processedPayload, { cachedAt });
41688
- }
41689
- }
41690
- appendToQueryStream(response, direction, refresh = false) {
41691
- var _a, _b;
41692
- if (refresh) {
41693
- pushToCache(this.cacheKey, {
41694
- data: response.notificationTrayItems.map(getResolver('notificationTrayItem')),
41695
- });
41696
- }
41697
- else {
41698
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
41699
- const notifications = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
41700
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
41701
- ...new Set([
41702
- ...notifications,
41703
- ...response.notificationTrayItems.map(getResolver('notificationTrayItem')),
41704
- ]),
41705
- ] }));
41706
- }
41707
- }
41708
- }
41709
-
41710
- const prepareNotificationTrayItemsPayload = (rawPayload) => {
41711
- const users = rawPayload.users.map(convertRawUserToInternalUser);
41712
- return Object.assign(Object.assign({}, rawPayload), { users });
41713
- };
41714
-
41715
- class NotificationTrayItemsLiveCollectionController extends LiveCollectionController {
41716
- constructor(query, callback) {
41717
- const queryStreamId = hash(query);
41718
- const cacheKey = ['notificationTrayItem', 'collection', queryStreamId];
41719
- const paginationController = new NotificationTrayItemsPaginationController(query);
41720
- super(paginationController, queryStreamId, cacheKey, callback);
41721
- this.query = query;
41722
- this.queryStreamController = new NotificationTrayItemsQuerystreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareNotificationTrayItemsPayload);
41723
- this.callback = callback.bind(this);
41724
- this.loadPage({ initial: true });
41725
- }
41726
- setup() {
41727
- var _a;
41728
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
41729
- if (!collection) {
41730
- pushToCache(this.cacheKey, {
41731
- data: [],
41732
- params: {},
41733
- });
41734
- }
41735
- }
41736
- async persistModel(queryPayload) {
41737
- await this.queryStreamController.saveToMainDB(queryPayload);
41738
- }
41739
- persistQueryStream({ response, direction, refresh, }) {
41740
- this.queryStreamController.appendToQueryStream(response, direction, refresh);
41741
- }
41742
- // eslint-disable-next-line class-methods-use-this
41743
- startSubscription() {
41744
- return [];
41745
- }
41746
- notifyChange({ origin, loading, error }) {
41747
- var _a, _b;
41748
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
41749
- if (!collection)
41750
- return;
41751
- const data = ((_b = collection.data
41752
- .map(id => pullFromCache(['notificationTrayItem', 'get', id]))
41753
- .filter(isNonNullable)
41754
- .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.notificationTray);
41755
- if (!this.shouldNotify(data) && origin === 'event')
41756
- return;
41757
- this.callback({
41758
- onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
41759
- data,
41760
- hasNextPage: !!this.paginationController.getNextToken(),
41761
- loading,
41762
- error,
41763
- });
41764
- }
41765
- }
41766
-
41767
- /**
41768
- * Get notification tray items for a notification tray page
41769
- *
41770
- * @param params the limit query parameters
41771
- * @param callback the callback to be called when the notification tray items are updated
41772
- * @returns items in the notification tray
41773
- *
41774
- * @category Notification tray items Live Collection
41775
- *
41776
- */
41777
- const getNotificationTrayItems = (params, callback, config) => {
41778
- const { log, cache } = getActiveClient();
41779
- if (!cache) {
41780
- console.log(ENABLE_CACHE_MESSAGE);
41781
- }
41782
- const timestamp = Date.now();
41783
- log(`getNotificationTrayItems(tmpid: ${timestamp}) > listen`);
41784
- const notiTrayItemsLiveCollection = new NotificationTrayItemsLiveCollectionController(params, callback);
41785
- const disposers = notiTrayItemsLiveCollection.startSubscription();
41786
- const cacheKey = notiTrayItemsLiveCollection.getCacheKey();
41787
- disposers.push(() => dropFromCache(cacheKey));
41788
- return () => {
41789
- log(`getNotificationTrayItems(tmpid: ${timestamp}) > dispose`);
41790
- disposers.forEach(fn => fn());
41791
- };
41792
- };
41793
-
41794
- /* begin_public_function
41795
- id: notificationTray.markSeen
41796
- */
41797
- /**
41798
- * ```js
41799
- * import { NotificationTrayRepository } from '@amityco/ts-sdk'
41800
- * const updated = await NotificationTrayRepository.markNotificationTraySeen({
41801
- * lastSeenAt: Amity.timestamp,
41802
- * })
41803
- * ```
41804
- *
41805
- * Updates an {@link Amity.NotificationTraySeen}
41806
- *
41807
- * @param userId The ID of the {@link Amity.NotificationTraySeen} to edit
41808
- * @param lastSeenAt The patch data to apply
41809
- * @returns the updated {@link Amity.NotificationTraySeen} object
41810
- *
41811
- * @category Post API
41812
- * @async
41813
- */
41814
- const markNotificationTraySeen = async (lastSeenAt) => {
41815
- var _a;
41816
- const client = getActiveClient();
41817
- client.log('notificationTray/markNotificationTraySeen', {});
41818
- const { data: payload } = await client.http.put(`api/v1/notification-tray/tray/seen`, {
41819
- lastSeenAt,
41820
- });
41821
- const cacheData = (_a = pullFromCache([
41822
- 'notificationTraySeen',
41823
- 'get',
41824
- ])) === null || _a === void 0 ? void 0 : _a.data;
41825
- const data = Object.assign({ userId: client.userId }, payload);
41826
- const updateCacheData = Object.assign(Object.assign({}, cacheData), data);
41827
- const cachedAt = client.cache && Date.now();
41828
- if (client.cache)
41829
- pushToCache(['notificationTraySeen', 'get', client.userId], updateCacheData, { cachedAt });
41830
- fireEvent('local.notificationTraySeen.updated', data);
41831
- return {
41832
- data: payload,
41833
- cachedAt,
41834
- };
41835
- };
41836
- /* end_public_function */
41837
-
41838
- var index = /*#__PURE__*/Object.freeze({
41839
- __proto__: null,
41840
- getNotificationTraySeen: getNotificationTraySeen,
41841
- getNotificationTrayItems: getNotificationTrayItems,
41842
- markNotificationItemsSeen: markNotificationItemsSeen,
41843
- markNotificationTraySeen: markNotificationTraySeen,
41844
- onNotificationTraySeenUpdated: onNotificationTraySeenUpdated
41845
- });
41846
-
41847
- export { API_REGIONS, index$1 as AdRepository, index$9 as CategoryRepository, index$d as ChannelRepository, index$m as Client, index$7 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$a as CommunityRepository, ContentFeedType, DefaultCommunityPostSetting, index$8 as FeedRepository, FileAccessTypeEnum, index$j as FileRepository, FileType, index$3 as LiveStreamPlayer, MessageContentType, index$h as MessageRepository, index as NotificationTrayRepository, index$4 as PollRepository, PostContentType, index$6 as PostRepository, index$i as ReactionRepository, index$2 as StoryRepository, index$5 as StreamRepository, index$g as SubChannelRepository, SubscriptionLevels, index$k as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, getLiveStreamTopic, getMarkedMessageTopic, getMarkerUserFeedTopic, getMessageTopic, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPostTopic, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStoryTopic, getSubChannelTopic, getUserTopic, isAfterBefore, isAfterBeforeRaw, isCachable, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, mergeInCache, onChannelMarkerFetched, onFeedMarkerFetched, onFeedMarkerUpdated, onMessageMarked, onMessageMarkerFetched, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onUserMarkerFetched, onUserMarkerFetchedLegacy, pullFromCache, pushToCache, queryCache, queryOptions, queryRoles, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByFirstUpdated, sortByLastActivity, sortByLastCreated, sortByLastUpdated, sortByLocalSortingDate, sortByName, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, upsertInCache, wipeCache };
41970
+ export { API_REGIONS, index as AdRepository, index$8 as CategoryRepository, index$c as ChannelRepository, index$l as Client, index$6 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$9 as CommunityRepository, ContentFeedType, DefaultCommunityPostSetting, index$7 as FeedRepository, FileAccessTypeEnum, index$i as FileRepository, FileType, index$2 as LiveStreamPlayer, MessageContentType, index$g as MessageRepository, index$3 as PollRepository, PostContentType, index$5 as PostRepository, index$h as ReactionRepository, index$1 as StoryRepository, index$4 as StreamRepository, index$f as SubChannelRepository, SubscriptionLevels, index$j as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, getLiveStreamTopic, getMarkedMessageTopic, getMarkerUserFeedTopic, getMessageTopic, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPostTopic, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStoryTopic, getSubChannelTopic, getUserTopic, isAfterBefore, isAfterBeforeRaw, isCachable, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, mergeInCache, onChannelMarkerFetched, onFeedMarkerFetched, onFeedMarkerUpdated, onMessageMarked, onMessageMarkerFetched, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onUserMarkerFetched, onUserMarkerFetchedLegacy, pullFromCache, pushToCache, queryCache, queryOptions, queryRoles, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByFirstUpdated, sortByLastActivity, sortByLastCreated, sortByLastUpdated, sortByLocalSortingDate, sortByName, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, upsertInCache, wipeCache };