@amityco/ts-sdk 7.1.1-61f30ce0.0 → 7.1.1-98a13d34.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.cjs.js CHANGED
@@ -121,7 +121,6 @@ const SECOND$1 = 1000;
121
121
  const MINUTE = 60 * SECOND$1;
122
122
  const HOUR = 60 * MINUTE;
123
123
  const DAY = 24 * HOUR;
124
- const WEEK = 7 * DAY;
125
124
  const YEAR = 365 * DAY;
126
125
  const ACCESS_TOKEN_WATCHER_INTERVAL = 10 * MINUTE;
127
126
 
@@ -517,6 +516,7 @@ const idResolvers = {
517
516
  messagePreviewSubChannel: ({ subChannelId }) => `${subChannelId}`,
518
517
  channelUnreadInfo: ({ channelId }) => channelId,
519
518
  subChannelUnreadInfo: ({ subChannelId }) => subChannelId,
519
+ channelUnread: ({ channelId }) => channelId,
520
520
  channelMarker: ({ entityId, userId }) => `${entityId}#${userId}`,
521
521
  subChannelMarker: ({ entityId, feedId, userId }) => `${entityId}#${feedId}#${userId}`,
522
522
  messageMarker: ({ feedId, contentId, creatorId }) => `${feedId}#${contentId}#${creatorId}`,
@@ -543,8 +543,6 @@ const idResolvers = {
543
543
  advertiser: ({ advertiserId }) => advertiserId,
544
544
  pin: ({ placement, referenceId }) => `${placement}#${referenceId}`,
545
545
  pinTarget: ({ targetId }) => targetId,
546
- notificationTrayItem: ({ _id }) => _id,
547
- notificationTraySeen: ({ userId }) => userId,
548
546
  };
549
547
  /**
550
548
  * Retrieve the id resolver matching a domain name
@@ -596,7 +594,6 @@ const PAYLOAD2MODEL = {
596
594
  advertisers: 'advertiser',
597
595
  pinTargets: 'pinTarget',
598
596
  pins: 'pin',
599
- notificationTrayItems: 'notificationTrayItem',
600
597
  };
601
598
  /** hidden */
602
599
  const isOutdated = (prevData, nextData) => {
@@ -1565,6 +1562,7 @@ const API_REGIONS = {
1565
1562
  };
1566
1563
  const URLS = {
1567
1564
  http: 'https://apix.{region}.amity.co',
1565
+ upload: 'https://upload.{region}.amity.co',
1568
1566
  mqtt: 'wss://sse.{region}.amity.co:443/mqtt',
1569
1567
  };
1570
1568
  function computeUrl(type, region) {
@@ -1613,13 +1611,13 @@ class NetworkActivitiesWatcher {
1613
1611
  this._listener.clear();
1614
1612
  }
1615
1613
  }
1616
- let instance$5;
1614
+ let instance$6;
1617
1615
  var NetworkActivitiesWatcher$1 = {
1618
1616
  getInstance: () => {
1619
- if (!instance$5) {
1620
- instance$5 = new NetworkActivitiesWatcher();
1617
+ if (!instance$6) {
1618
+ instance$6 = new NetworkActivitiesWatcher();
1621
1619
  }
1622
- return instance$5;
1620
+ return instance$6;
1623
1621
  },
1624
1622
  };
1625
1623
 
@@ -5152,13 +5150,13 @@ class AnalyticsEngine {
5152
5150
  this._eventCapturer.resetAllBuckets();
5153
5151
  }
5154
5152
  }
5155
- let instance$4;
5153
+ let instance$5;
5156
5154
  var AnalyticsEngine$1 = {
5157
5155
  getInstance: () => {
5158
- if (!instance$4) {
5159
- instance$4 = new AnalyticsEngine();
5156
+ if (!instance$5) {
5157
+ instance$5 = new AnalyticsEngine();
5160
5158
  }
5161
- return instance$4;
5159
+ return instance$5;
5162
5160
  },
5163
5161
  };
5164
5162
 
@@ -5584,6 +5582,223 @@ const getMessageReadCount = (message, marker) => {
5584
5582
  getCachedMarker$2(message)) !== null && _a !== void 0 ? _a : { readCount: 0, deliveredCount: 0 };
5585
5583
  }; // and if not found in cache use default value `0`
5586
5584
 
5585
+ /**
5586
+ *
5587
+ * Mark subChannel as read by readToSegment
5588
+ *
5589
+ * @param subChannelIds the IDs of the {@link Amity.SubChannel} to update
5590
+ * @param readToSegment the segment to mark as read
5591
+ * @returns a success boolean if the {@link Amity.SubChannel} was updated
5592
+ *
5593
+ * @category Channel API
5594
+ * @async
5595
+ */
5596
+ const markChannelsAsReadBySegment = async (readings) => {
5597
+ const client = getActiveClient();
5598
+ try {
5599
+ await client.http.post('api/v3/channels/seen', { channels: readings });
5600
+ return true;
5601
+ }
5602
+ catch (e) {
5603
+ return false;
5604
+ }
5605
+ };
5606
+
5607
+ class MessageReadReceiptSyncEngine {
5608
+ constructor() {
5609
+ this.isActive = true;
5610
+ this.MAX_RETRY = 3;
5611
+ this.JOB_QUEUE_SIZE = 120;
5612
+ this.jobQueue = [];
5613
+ // Interval for message read receipt sync in seconds
5614
+ this.RECEIPT_SYNC_INTERVAL = 1;
5615
+ this.client = getActiveClient();
5616
+ // Get remaining unsync read receipts from cache
5617
+ this.getUnsyncJobs();
5618
+ }
5619
+ // Call this when client call client.login
5620
+ startSyncReadReceipt() {
5621
+ // Start timer when start receipt sync
5622
+ this.timer = setInterval(() => {
5623
+ this.syncReadReceipts();
5624
+ }, this.RECEIPT_SYNC_INTERVAL * 1000);
5625
+ }
5626
+ // Read receipt observer handling
5627
+ syncReadReceipts() {
5628
+ if (this.jobQueue.length === 0 || this.isActive === false)
5629
+ return;
5630
+ const readReceipts = this.getReadReceipts();
5631
+ if (readReceipts) {
5632
+ this.markReadApi(readReceipts);
5633
+ }
5634
+ }
5635
+ getUnsyncJobs() {
5636
+ var _a;
5637
+ // Get all read receipts that has latestSyncSegment < latestSegment
5638
+ const readReceipts = (_a = queryCache(['readReceipt'])) === null || _a === void 0 ? void 0 : _a.filter(({ data }) => {
5639
+ return data.latestSyncSegment < data.latestSegment;
5640
+ });
5641
+ // Enqueue unsync read receipts to the job queue
5642
+ readReceipts === null || readReceipts === void 0 ? void 0 : readReceipts.forEach(({ data: readReceipt }) => {
5643
+ this.enqueueReadReceipt(readReceipt.channelId, readReceipt.latestSegment);
5644
+ });
5645
+ }
5646
+ getReadReceipts() {
5647
+ // get all read receipts from queue, now the queue is empty
5648
+ const syncJob = this.jobQueue.splice(0, this.jobQueue.length);
5649
+ if (syncJob.length === 0)
5650
+ return;
5651
+ return syncJob.filter(job => {
5652
+ var _a;
5653
+ const readReceipt = (_a = pullFromCache(['readReceipt', job.channelId])) === null || _a === void 0 ? void 0 : _a.data;
5654
+ if (!readReceipt)
5655
+ return false;
5656
+ if (readReceipt.latestSegment > readReceipt.latestSyncSegment)
5657
+ return true;
5658
+ return false;
5659
+ });
5660
+ }
5661
+ async markReadApi(syncJobs) {
5662
+ var _a;
5663
+ // constuct payload
5664
+ // example: [{ channelId: 'channelId', readToSegment: 2 }]
5665
+ const syncJobsPayload = syncJobs.map(job => {
5666
+ return {
5667
+ channelId: job.channelId,
5668
+ readToSegment: job.segment,
5669
+ };
5670
+ });
5671
+ const response = await markChannelsAsReadBySegment(syncJobsPayload);
5672
+ if (response) {
5673
+ for (let i = 0; i < syncJobs.length; i += 1) {
5674
+ // update lastestSyncSegment in read receipt cache
5675
+ const cacheKey = ['readReceipt', syncJobs[i].channelId];
5676
+ const readReceiptCache = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
5677
+ pushToCache(cacheKey, Object.assign(Object.assign({}, readReceiptCache), { latestSyncSegment: syncJobs[i].segment }));
5678
+ }
5679
+ }
5680
+ else {
5681
+ for (let i = 0; i < syncJobs.length; i += 1) {
5682
+ // push them back to queue if the syncing is failed and retry count is less than max retry
5683
+ if (syncJobs[i].retryCount >= this.MAX_RETRY)
5684
+ return;
5685
+ const updatedJob = Object.assign(Object.assign({}, syncJobs[i]), { syncState: "create" /* Amity.ReadReceiptSyncState.CREATED */, retryCount: syncJobs[i].retryCount + 1 });
5686
+ this.enqueueJob(updatedJob);
5687
+ }
5688
+ }
5689
+ }
5690
+ startObservingReadReceiptQueue() {
5691
+ if (this.client.useLegacyUnreadCount) {
5692
+ this.isActive = true;
5693
+ this.startSyncReadReceipt();
5694
+ }
5695
+ }
5696
+ stopObservingReadReceiptQueue() {
5697
+ this.isActive = false;
5698
+ this.jobQueue.map(job => {
5699
+ if (job.syncState === "syncing" /* Amity.ReadReceiptSyncState.SYNCING */) {
5700
+ return Object.assign(Object.assign({}, job), { syncState: "create" /* Amity.ReadReceiptSyncState.CREATED */ });
5701
+ }
5702
+ return job;
5703
+ });
5704
+ if (this.timer)
5705
+ clearInterval(this.timer);
5706
+ }
5707
+ // Session Management
5708
+ onSessionEstablished() {
5709
+ this.startObservingReadReceiptQueue();
5710
+ }
5711
+ onSessionDestroyed() {
5712
+ this.stopObservingReadReceiptQueue();
5713
+ this.jobQueue = [];
5714
+ }
5715
+ onTokenExpired() {
5716
+ this.stopObservingReadReceiptQueue();
5717
+ }
5718
+ // Network Connection Management
5719
+ onNetworkOffline() {
5720
+ // Stop observing to the read receipt queue.
5721
+ this.stopObservingReadReceiptQueue();
5722
+ }
5723
+ onNetworkOnline() {
5724
+ // Resume observing to the read receipt queue.
5725
+ this.startObservingReadReceiptQueue();
5726
+ }
5727
+ markRead(channelId, segment) {
5728
+ var _a;
5729
+ // Step 1: Optimistic update of channelUnread.readToSegment to message.segment and update unreadCount value
5730
+ const cacheKey = ['channelUnread', 'get', channelId];
5731
+ const channelUnread = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
5732
+ if (typeof (channelUnread === null || channelUnread === void 0 ? void 0 : channelUnread.readToSegment) === 'number' &&
5733
+ channelUnread &&
5734
+ segment > channelUnread.readToSegment) {
5735
+ channelUnread.readToSegment = segment;
5736
+ channelUnread.unreadCount = Math.max(channelUnread.lastSegment - segment, 0);
5737
+ pushToCache(cacheKey, channelUnread);
5738
+ fireEvent('local.channelUnread.updated', channelUnread);
5739
+ }
5740
+ // Step 2: Enqueue the read receipt
5741
+ this.enqueueReadReceipt(channelId, segment);
5742
+ }
5743
+ enqueueReadReceipt(channelId, segment) {
5744
+ var _a;
5745
+ const readReceipt = (_a = pullFromCache(['readReceipt', channelId])) === null || _a === void 0 ? void 0 : _a.data;
5746
+ // Create new read receipt if it's not exists and add the job to queue
5747
+ if (!readReceipt) {
5748
+ const readReceiptChannel = {
5749
+ channelId,
5750
+ latestSegment: segment,
5751
+ latestSyncSegment: 0,
5752
+ };
5753
+ pushToCache(['readReceipt', channelId], readReceiptChannel);
5754
+ }
5755
+ else if (readReceipt.latestSegment < segment) {
5756
+ // Update latestSegment in read receipt cache
5757
+ pushToCache(['readReceipt', channelId], Object.assign(Object.assign({}, readReceipt), { latestSegment: segment }));
5758
+ }
5759
+ else if (readReceipt.latestSyncSegment >= segment) {
5760
+ // Skip the job when lastSyncSegment > = segment
5761
+ return;
5762
+ }
5763
+ let syncJob = this.getSyncJob(channelId);
5764
+ if (syncJob === null || syncJob.syncState === "syncing" /* Amity.ReadReceiptSyncState.SYNCING */) {
5765
+ syncJob = {
5766
+ channelId,
5767
+ segment,
5768
+ syncState: "create" /* Amity.ReadReceiptSyncState.CREATED */,
5769
+ retryCount: 0,
5770
+ };
5771
+ this.enqueueJob(syncJob);
5772
+ }
5773
+ else if (syncJob.segment < segment) {
5774
+ syncJob.segment = segment;
5775
+ }
5776
+ }
5777
+ getSyncJob(channelId) {
5778
+ const { jobQueue } = this;
5779
+ const targetJob = jobQueue.find(job => job.channelId === channelId);
5780
+ return targetJob || null;
5781
+ }
5782
+ enqueueJob(syncJob) {
5783
+ if (this.jobQueue.length < this.JOB_QUEUE_SIZE) {
5784
+ this.jobQueue.push(syncJob);
5785
+ }
5786
+ else {
5787
+ // Remove oldest job when queue reach maximum capacity
5788
+ this.jobQueue.shift();
5789
+ this.jobQueue.push(syncJob);
5790
+ }
5791
+ }
5792
+ }
5793
+ let instance$4 = null;
5794
+ var ReadReceiptSyncEngine = {
5795
+ getInstance: () => {
5796
+ if (!instance$4)
5797
+ instance$4 = new MessageReadReceiptSyncEngine();
5798
+ return instance$4;
5799
+ },
5800
+ };
5801
+
5587
5802
  /**
5588
5803
  *
5589
5804
  * Mark subChannel as read by readToSegment
@@ -5632,7 +5847,7 @@ const reCalculateChannelUnreadInfo = (channelId) => {
5632
5847
  return channelUnreadInfo;
5633
5848
  };
5634
5849
 
5635
- class MessageReadReceiptSyncEngine {
5850
+ class LegacyMessageReadReceiptSyncEngine {
5636
5851
  constructor() {
5637
5852
  this.isActive = true;
5638
5853
  this.MAX_RETRY = 3;
@@ -5663,7 +5878,7 @@ class MessageReadReceiptSyncEngine {
5663
5878
  getUnsyncJobs() {
5664
5879
  var _a;
5665
5880
  // Get all read receipts that has latestSyncSegment < latestSegment
5666
- const readReceipts = (_a = queryCache(['readReceipt'])) === null || _a === void 0 ? void 0 : _a.filter(({ data }) => {
5881
+ const readReceipts = (_a = queryCache(['legacyReadReceipt'])) === null || _a === void 0 ? void 0 : _a.filter(({ data }) => {
5667
5882
  return data.latestSyncSegment < data.latestSegment;
5668
5883
  });
5669
5884
  // Enqueue unsync read receipts to the job queue
@@ -5682,7 +5897,7 @@ class MessageReadReceiptSyncEngine {
5682
5897
  return;
5683
5898
  // Get readReceipt from cache by subChannelId
5684
5899
  const readReceipt = (_a = pullFromCache([
5685
- 'readReceipt',
5900
+ 'legacyReadReceipt',
5686
5901
  syncJob.subChannelId,
5687
5902
  ])) === null || _a === void 0 ? void 0 : _a.data;
5688
5903
  if (!readReceipt)
@@ -5705,10 +5920,10 @@ class MessageReadReceiptSyncEngine {
5705
5920
  if (response) {
5706
5921
  this.removeSynedReceipt(syncJob.subChannelId, syncJob.segment);
5707
5922
  const readReceiptCache = (_a = pullFromCache([
5708
- 'readReceipt',
5923
+ 'legacyReadReceipt',
5709
5924
  subChannelId,
5710
5925
  ])) === null || _a === void 0 ? void 0 : _a.data;
5711
- pushToCache(['readReceipt', subChannelId], Object.assign(Object.assign({}, readReceiptCache), { latestSyncSegment: segment }));
5926
+ pushToCache(['legacyReadReceipt', subChannelId], Object.assign(Object.assign({}, readReceiptCache), { latestSyncSegment: segment }));
5712
5927
  }
5713
5928
  else if (!response) {
5714
5929
  if (newSyncJob.retryCount > this.MAX_RETRY) {
@@ -5775,7 +5990,7 @@ class MessageReadReceiptSyncEngine {
5775
5990
  subChannelUnreadInfo.readToSegment = segment;
5776
5991
  subChannelUnreadInfo.unreadCount = Math.max(subChannelUnreadInfo.lastSegment - segment, 0);
5777
5992
  const channelUnreadInfo = reCalculateChannelUnreadInfo(subChannelUnreadInfo.channelId);
5778
- fireEvent('local.channelUnread.updated', channelUnreadInfo);
5993
+ fireEvent('local.channelUnreadInfo.updated', channelUnreadInfo);
5779
5994
  pushToCache(cacheKey, subChannelUnreadInfo);
5780
5995
  fireEvent('local.subChannelUnread.updated', subChannelUnreadInfo);
5781
5996
  }
@@ -5784,7 +5999,10 @@ class MessageReadReceiptSyncEngine {
5784
5999
  }
5785
6000
  enqueueReadReceipt(subChannelId, segment) {
5786
6001
  var _a;
5787
- const readReceipt = (_a = pullFromCache(['readReceipt', subChannelId])) === null || _a === void 0 ? void 0 : _a.data;
6002
+ const readReceipt = (_a = pullFromCache([
6003
+ 'legacyReadReceipt',
6004
+ subChannelId,
6005
+ ])) === null || _a === void 0 ? void 0 : _a.data;
5788
6006
  // Create new read receipt if it's not exists and add job to queue
5789
6007
  if (!readReceipt) {
5790
6008
  const readReceiptSubChannel = {
@@ -5792,10 +6010,10 @@ class MessageReadReceiptSyncEngine {
5792
6010
  latestSegment: segment,
5793
6011
  latestSyncSegment: 0,
5794
6012
  };
5795
- pushToCache(['readReceipt', subChannelId], readReceiptSubChannel);
6013
+ pushToCache(['legacyReadReceipt', subChannelId], readReceiptSubChannel);
5796
6014
  }
5797
6015
  else if (readReceipt.latestSegment < segment) {
5798
- pushToCache(['readReceipt', subChannelId], Object.assign(Object.assign({}, readReceipt), { latestSegment: segment }));
6016
+ pushToCache(['legacyReadReceipt', subChannelId], Object.assign(Object.assign({}, readReceipt), { latestSegment: segment }));
5799
6017
  }
5800
6018
  else if (readReceipt.latestSyncSegment >= segment) {
5801
6019
  // Skip the job when lastSyncSegment > = segment
@@ -5838,18 +6056,24 @@ class MessageReadReceiptSyncEngine {
5838
6056
  }
5839
6057
  }
5840
6058
  let instance$3 = null;
5841
- var ReadReceiptSyncEngine = {
6059
+ var LegacyReadReceiptSyncEngine = {
5842
6060
  getInstance: () => {
5843
6061
  if (!instance$3)
5844
- instance$3 = new MessageReadReceiptSyncEngine();
6062
+ instance$3 = new LegacyMessageReadReceiptSyncEngine();
5845
6063
  return instance$3;
5846
6064
  },
5847
6065
  };
5848
6066
 
5849
6067
  const markReadMessage = (message) => {
5850
- const { subChannelId, channelSegment } = message;
5851
- const markReadReceiptEngine = ReadReceiptSyncEngine.getInstance();
5852
- markReadReceiptEngine.markRead(subChannelId, channelSegment);
6068
+ const client = getActiveClient();
6069
+ if (client.useLegacyUnreadCount) {
6070
+ const markReadReceiptEngine = ReadReceiptSyncEngine.getInstance();
6071
+ markReadReceiptEngine.markRead(message.channelId, message.channelSegment);
6072
+ }
6073
+ else {
6074
+ const markReadReceiptEngine = LegacyReadReceiptSyncEngine.getInstance();
6075
+ markReadReceiptEngine.markRead(message.subChannelId, message.channelSegment);
6076
+ }
5853
6077
  };
5854
6078
 
5855
6079
  const messageLinkedObject = (message) => {
@@ -5997,65 +6221,6 @@ const pinnedPostLinkedObject = (pinnedPost) => {
5997
6221
  } });
5998
6222
  };
5999
6223
 
6000
- /* begin_public_function
6001
- id: notificationTrayItem.markSeen
6002
- */
6003
- /**
6004
- * ```js
6005
- * import { NotificationTrayRepository } from '@amityco/ts-sdk'
6006
- * const updated = await NotificationTrayRepository.markNotificationItemsSeen()
6007
- * ```
6008
- *
6009
- * Updates an {@link Amity.NotificationItemSeen}
6010
- *
6011
- * @param trayItems[] that include id and lastTraySeenAt, The ID of the {@link Amity.NotificationItemSeen} to edit
6012
- * @returns the updated {@link Amity.NotificationItemSeen} object
6013
- *
6014
- * @category NotificationItemSeen API
6015
- * @async
6016
- */
6017
- const markNotificationItemsSeen = async (patch) => {
6018
- const client = getActiveClient();
6019
- client.log('notificationTray/markNotificationItemsSeen', {});
6020
- const { data: payload } = await client.http.put(`api/v1/notification-tray/items/seen`, {
6021
- patch,
6022
- });
6023
- const updatedData = patch.trayItems
6024
- .map(patchItem => {
6025
- var _a;
6026
- const cacheData = (_a = pullFromCache([
6027
- 'notificationTraySeen',
6028
- 'get',
6029
- patchItem.id,
6030
- ])) === null || _a === void 0 ? void 0 : _a.data;
6031
- if (!cacheData)
6032
- return;
6033
- const data = Object.assign(Object.assign({}, cacheData), payload);
6034
- if (client.cache) {
6035
- const cachedAt = Date.now();
6036
- pushToCache(['notificationTrayItem', 'get'], data, { cachedAt });
6037
- }
6038
- return data;
6039
- })
6040
- .filter(Boolean);
6041
- fireEvent('local.notificationTrayItem.updated', { notificationTrayItems: updatedData });
6042
- };
6043
- /* end_public_function */
6044
-
6045
- const notificationTrayLinkedObject = (noti) => {
6046
- return Object.assign(Object.assign({}, noti), { isSeen: noti.lastSeenAt > noti.lastOccuredAt, isRecent: new Date(noti.lastOccuredAt).getTime() >= Date.now() - WEEK, users: noti.actorIds
6047
- .map(userId => { var _a; return (_a = pullFromCache(['user', 'get', userId])) === null || _a === void 0 ? void 0 : _a.data; })
6048
- .filter(isNonNullable)
6049
- .map(user => userLinkedObject(user)), markRead: () => markNotificationItemsSeen({
6050
- trayItems: [
6051
- {
6052
- id: noti._id,
6053
- lastSeenAt: noti.lastSeenAt,
6054
- },
6055
- ],
6056
- }) });
6057
- };
6058
-
6059
6224
  const LinkedObject = {
6060
6225
  ad: adLinkedObject,
6061
6226
  comment: commentLinkedObject,
@@ -6069,7 +6234,6 @@ const LinkedObject = {
6069
6234
  reactor: reactorLinkedObject,
6070
6235
  channel: channelLinkedObject,
6071
6236
  pinnedPost: pinnedPostLinkedObject,
6072
- notificationTray: notificationTrayLinkedObject,
6073
6237
  };
6074
6238
 
6075
6239
  const getChannelMessagePreviewWithUser = (channel) => {
@@ -6897,6 +7061,32 @@ const preUpdateChannelCache = (rawPayload, options = { isMessagePreviewUpdated:
6897
7061
  channels: rawPayload.channels.map(channel => convertFromRaw(channel, { isMessagePreviewUpdated: options.isMessagePreviewUpdated })),
6898
7062
  });
6899
7063
  };
7064
+ const updateChannelUnread = ({ currentUserId, channels, channelUsers, }) => {
7065
+ for (let i = 0; i < channels.length; i += 1) {
7066
+ const cacheKey = ['channelUnread', 'get', channels[i].channelId];
7067
+ const channelUser = channelUsers.find(channelUser => channelUser.channelId === channels[i].channelId && channelUser.userId === currentUserId);
7068
+ let unreadCount = 0;
7069
+ let readToSegment = null;
7070
+ let lastMentionedSegment = null;
7071
+ let isMentioned = false;
7072
+ if (channelUser) {
7073
+ readToSegment = channelUser.readToSegment;
7074
+ lastMentionedSegment = channelUser.lastMentionedSegment;
7075
+ unreadCount = Math.max(channels[i].messageCount - readToSegment, 0);
7076
+ isMentioned = lastMentionedSegment > readToSegment;
7077
+ }
7078
+ const cacheChannelUnread = {
7079
+ channelId: channels[i].channelId,
7080
+ lastSegment: channels[i].messageCount,
7081
+ readToSegment,
7082
+ lastMentionedSegment,
7083
+ unreadCount,
7084
+ isMentioned,
7085
+ isDeleted: channels[i].isDeleted || false,
7086
+ };
7087
+ pushToCache(cacheKey, cacheChannelUnread);
7088
+ }
7089
+ };
6900
7090
  const prepareChannelPayload = async (rawPayload, options = { isMessagePreviewUpdated: true }) => {
6901
7091
  const client = getActiveClient();
6902
7092
  const networkPreviewSetting = await client.getMessagePreviewSetting(false);
@@ -6906,23 +7096,34 @@ const prepareChannelPayload = async (rawPayload, options = { isMessagePreviewUpd
6906
7096
  rawPayload.messagePreviews.length > 0) {
6907
7097
  updateChannelMessagePreviewCache(rawPayload);
6908
7098
  }
6909
- const markerIds = rawPayload.channels
6910
- // filter channel by type. Only conversation, community and broadcast type are included.
6911
- .filter(isUnreadCountSupport)
6912
- .map(({ channelInternalId }) => channelInternalId);
6913
- if (markerIds.length > 0) {
6914
- // since the get markers method requires a channel cache to function with the reducer.
6915
- preUpdateChannelCache(rawPayload, { isMessagePreviewUpdated: options.isMessagePreviewUpdated });
6916
- try {
6917
- await getChannelMarkers(markerIds);
6918
- }
6919
- catch (e) {
6920
- // empty block (from the spec, allow marker fetch to fail without having to do anything)
7099
+ if (client.useLegacyUnreadCount) {
7100
+ updateChannelUnread({
7101
+ channels: rawPayload.channels,
7102
+ channelUsers: rawPayload.channelUsers,
7103
+ currentUserId: client.userId,
7104
+ });
7105
+ }
7106
+ else {
7107
+ const markerIds = rawPayload.channels
7108
+ // filter channel by type. Only conversation, community and broadcast type are included.
7109
+ .filter(isUnreadCountSupport)
7110
+ .map(({ channelInternalId }) => channelInternalId);
7111
+ if (markerIds.length > 0) {
7112
+ // since the get markers method requires a channel cache to function with the reducer.
7113
+ preUpdateChannelCache(rawPayload, {
7114
+ isMessagePreviewUpdated: options.isMessagePreviewUpdated,
7115
+ });
7116
+ try {
7117
+ await getChannelMarkers(markerIds);
7118
+ }
7119
+ catch (e) {
7120
+ // empty block (from the spec, allow marker fetch to fail without having to do anything)
7121
+ }
6921
7122
  }
6922
7123
  }
6923
- // attach marker to channel
7124
+ // convert raw channel to internal channel
6924
7125
  const channels = rawPayload.channels.map(payload => convertFromRaw(payload, { isMessagePreviewUpdated: options.isMessagePreviewUpdated }));
6925
- // user marker to channel users
7126
+ // convert raw channel user to membership (add user object)
6926
7127
  const channelUsers = rawPayload.channelUsers.map(channelUser => {
6927
7128
  return convertRawMembershipToMembership(channelUser);
6928
7129
  });
@@ -7049,15 +7250,28 @@ const getSubChannelsUnreadCount = (channel, marker) => {
7049
7250
  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;
7050
7251
  };
7051
7252
 
7253
+ const getLegacyChannelUnread = (channelId) => {
7254
+ var _a;
7255
+ return (_a = pullFromCache(['channelUnread', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
7256
+ };
7257
+
7052
7258
  const constructChannelDynamicValue = (channel) => {
7259
+ const client = getActiveClient();
7053
7260
  const rest = __rest(channel, ["messageCount"]);
7054
7261
  return shallowClone(rest, {
7055
- get isMentioned() {
7056
- return getChannelIsMentioned(rest);
7262
+ get unreadCount() {
7263
+ var _a, _b;
7264
+ return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.unreadCount) !== null && _b !== void 0 ? _b : 0;
7057
7265
  },
7058
7266
  get subChannelsUnreadCount() {
7059
7267
  return getSubChannelsUnreadCount(rest);
7060
7268
  },
7269
+ get isMentioned() {
7270
+ var _a, _b;
7271
+ if (client.useLegacyUnreadCount)
7272
+ return (_b = (_a = getLegacyChannelUnread(rest.channelId)) === null || _a === void 0 ? void 0 : _a.isMentioned) !== null && _b !== void 0 ? _b : false;
7273
+ return getChannelIsMentioned(rest);
7274
+ },
7061
7275
  });
7062
7276
  };
7063
7277
 
@@ -7670,6 +7884,12 @@ const setClientToken = async (params) => {
7670
7884
  isGlobalBanned: false,
7671
7885
  isUserDeleted: false,
7672
7886
  };
7887
+ client.upload.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
7888
+ client.upload.defaults.metadata = {
7889
+ tokenExpiry: expiresAt,
7890
+ isGlobalBanned: false,
7891
+ isUserDeleted: false,
7892
+ };
7673
7893
  // manually setup the token for ws transport
7674
7894
  if (client.ws)
7675
7895
  client.ws.io.opts.query = { token: accessToken };
@@ -7714,12 +7934,21 @@ const onChannelDeleted = (callback) => {
7714
7934
  const client = getActiveClient();
7715
7935
  const filter = async (payload) => {
7716
7936
  const data = await prepareChannelPayload(payload);
7717
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode()) {
7718
- data.channels.forEach(channel => {
7937
+ const isConsistentMode = client.getMarkerSyncConsistentMode() && client.isUnreadCountEnabled;
7938
+ const isLegacyUnreadCount = client.useLegacyUnreadCount;
7939
+ data.channels.forEach(channel => {
7940
+ if (isConsistentMode) {
7719
7941
  addFlagIsDeletedSubChannelUnreadByChannelId(channel.channelId);
7720
7942
  deleteChannelUnreadByChannelId(channel.channelId);
7721
- });
7722
- }
7943
+ }
7944
+ else if (isLegacyUnreadCount) {
7945
+ const cacheKey = ['channelUnread', 'get', channel.channelId];
7946
+ const cache = pullFromCache(cacheKey);
7947
+ if (cache) {
7948
+ pushToCache(cacheKey, Object.assign(Object.assign({}, cache), { isDeleted: true }));
7949
+ }
7950
+ }
7951
+ });
7723
7952
  ingestInCache(data);
7724
7953
  callbacks$b.forEach(cb => cb(data.channels[0]));
7725
7954
  };
@@ -7833,6 +8062,25 @@ var readReceiptSyncEngineOnLoginHandler = () => {
7833
8062
  };
7834
8063
  };
7835
8064
 
8065
+ var legacyReadReceiptSyncEngineOnLoginHandler = () => {
8066
+ const readReceiptSyncEngine = LegacyReadReceiptSyncEngine.getInstance();
8067
+ readReceiptSyncEngine.startSyncReadReceipt();
8068
+ onSessionStateChange(state => {
8069
+ if (state === "established" /* Amity.SessionStates.ESTABLISHED */) {
8070
+ readReceiptSyncEngine.onSessionEstablished();
8071
+ }
8072
+ else if (state === "tokenExpired" /* Amity.SessionStates.TOKEN_EXPIRED */) {
8073
+ readReceiptSyncEngine.onTokenExpired();
8074
+ }
8075
+ else {
8076
+ readReceiptSyncEngine.onSessionDestroyed();
8077
+ }
8078
+ });
8079
+ return () => {
8080
+ readReceiptSyncEngine.onSessionDestroyed();
8081
+ };
8082
+ };
8083
+
7836
8084
  const onOnline = (callback) => {
7837
8085
  if (typeof window !== 'undefined' && window.addEventListener) {
7838
8086
  window.addEventListener('online', callback);
@@ -8399,10 +8647,17 @@ const onChannelLeft = (callback) => {
8399
8647
  const preparedPayload = await prepareChannelPayload(payload, {
8400
8648
  isMessagePreviewUpdated: isLeftByMe,
8401
8649
  });
8402
- if (client.isUnreadCountEnabled && client.getMarkerSyncConsistentMode() && isLeftByMe) {
8650
+ const isConsistentMode = client.getMarkerSyncConsistentMode() && client.isUnreadCountEnabled;
8651
+ const isLegacyUnreadCount = client.useLegacyUnreadCount;
8652
+ if (isLeftByMe) {
8403
8653
  preparedPayload.channels.forEach(channel => {
8404
- addFlagIsDeletedSubChannelUnreadByChannelId(channel.channelId);
8405
- deleteChannelUnreadByChannelId(channel.channelId);
8654
+ if (isConsistentMode) {
8655
+ addFlagIsDeletedSubChannelUnreadByChannelId(channel.channelId);
8656
+ deleteChannelUnreadByChannelId(channel.channelId);
8657
+ }
8658
+ else if (isLegacyUnreadCount) {
8659
+ dropFromCache(['channelUnread', 'get', channel.channelId]);
8660
+ }
8406
8661
  });
8407
8662
  }
8408
8663
  const { channels, channelUsers } = preparedPayload;
@@ -8670,6 +8925,34 @@ const onMessageCreatedMqtt = (callback) => {
8670
8925
  reCalculateChannelUnreadInfo(message.channelId);
8671
8926
  });
8672
8927
  }
8928
+ if (client.useLegacyUnreadCount) {
8929
+ rawPayload.messages.forEach(message => {
8930
+ var _a, _b;
8931
+ const channelUnread = (_a = pullFromCache([
8932
+ 'channelUnread',
8933
+ 'get',
8934
+ message.channelId,
8935
+ ])) === null || _a === void 0 ? void 0 : _a.data;
8936
+ if (!channelUnread ||
8937
+ channelUnread.lastSegment >= message.segment ||
8938
+ typeof channelUnread.readToSegment !== 'number' ||
8939
+ typeof channelUnread.lastMentionedSegment !== 'number')
8940
+ return;
8941
+ const lastSegment = message.segment;
8942
+ const isMentionedInMessage = (_b = message.mentionedUsers) === null || _b === void 0 ? void 0 : _b.some(mention => {
8943
+ return (mention.type === 'channel' ||
8944
+ (mention.type === 'user' &&
8945
+ client.userId &&
8946
+ mention.userPublicIds.includes(client.userId)));
8947
+ });
8948
+ const lastMentionedSegment = isMentionedInMessage
8949
+ ? message.segment
8950
+ : channelUnread.lastMentionedSegment;
8951
+ const updatedChannelUnread = Object.assign(Object.assign({}, channelUnread), { lastSegment, unreadCount: Math.max(lastSegment - channelUnread.readToSegment, 0), lastMentionedSegment, isMentioned: !(channelUnread.readToSegment >= lastMentionedSegment) });
8952
+ pushToCache(['channelUnread', 'get', message.channelId], updatedChannelUnread);
8953
+ fireEvent('local.channelUnread.updated', updatedChannelUnread);
8954
+ });
8955
+ }
8673
8956
  // Update in cache
8674
8957
  ingestInCache(payload);
8675
8958
  payload.messages.forEach(message => {
@@ -8845,6 +9128,7 @@ const enableUnreadCount = () => {
8845
9128
  if (client.isUnreadCountEnabled)
8846
9129
  return false;
8847
9130
  client.isUnreadCountEnabled = true;
9131
+ client.useLegacyUnreadCount = false;
8848
9132
  client.emitter.emit('unreadCountEnabled', true);
8849
9133
  return true;
8850
9134
  };
@@ -9160,7 +9444,12 @@ const login = async (params, sessionHandler, config) => {
9160
9444
  // NOTE: This is a temporary solution to handle the channel marker when the user is forced to leave
9161
9445
  // the channel because currently backend can't handle this, so every time a user is banned from
9162
9446
  // a channel or the channel is deleted the channel's unread count will not be reset to zero
9163
- onChannelDeleted(removeChannelMarkerCache), onChannelMemberBanned(removeChannelMarkerCache), markReadEngineOnLoginHandler(), analyticsEngineOnLoginHandler(), readReceiptSyncEngineOnLoginHandler(), objectResolverEngineOnLoginHandler());
9447
+ onChannelDeleted(removeChannelMarkerCache), onChannelMemberBanned(removeChannelMarkerCache), markReadEngineOnLoginHandler(), analyticsEngineOnLoginHandler(), objectResolverEngineOnLoginHandler());
9448
+ if (client.useLegacyUnreadCount) {
9449
+ subscriptions.push(readReceiptSyncEngineOnLoginHandler());
9450
+ }
9451
+ else
9452
+ subscriptions.push(legacyReadReceiptSyncEngineOnLoginHandler());
9164
9453
  const markerSyncUnsubscriber = await startMarkerSync();
9165
9454
  subscriptions.push(markerSyncUnsubscriber);
9166
9455
  }
@@ -9318,15 +9607,17 @@ const DEFAULT_DEBUG_SESSION = 'amity';
9318
9607
  * @category Client API
9319
9608
  * */
9320
9609
  const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAULT_DEBUG_SESSION, apiEndpoint, prefixDeviceIdKey, rteEnabled = true, } = {}) => {
9321
- var _a, _b;
9610
+ var _a, _b, _c;
9322
9611
  const log = createLogger(debugSession);
9323
9612
  log('client/api/createClient', {
9324
9613
  apiKey: apiKey.replace(/.{5}$/g, 'xxxxx'),
9325
9614
  apiRegion,
9326
9615
  });
9327
9616
  const httpEndpoint = (_a = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.http) !== null && _a !== void 0 ? _a : computeUrl('http', apiRegion);
9328
- const mqttEndpoint = (_b = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.mqtt) !== null && _b !== void 0 ? _b : computeUrl('mqtt', apiRegion);
9617
+ const uploadEndpoint = (_b = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.upload) !== null && _b !== void 0 ? _b : computeUrl('upload', apiRegion);
9618
+ const mqttEndpoint = (_c = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.mqtt) !== null && _c !== void 0 ? _c : computeUrl('mqtt', apiRegion);
9329
9619
  const http = createHttpTransport(httpEndpoint);
9620
+ const upload = createHttpTransport(uploadEndpoint);
9330
9621
  let ws;
9331
9622
  let mqtt;
9332
9623
  if (rteEnabled) {
@@ -9341,6 +9632,8 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
9341
9632
  const sessionState = "notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */;
9342
9633
  const sessionHandler = undefined;
9343
9634
  const isUnreadCountEnabled = false;
9635
+ // Legacy unread count is true by default
9636
+ const useLegacyUnreadCount = true;
9344
9637
  const client = {
9345
9638
  version: `${VERSION}`,
9346
9639
  apiKey,
@@ -9355,6 +9648,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
9355
9648
  http,
9356
9649
  ws,
9357
9650
  mqtt,
9651
+ upload,
9358
9652
  emitter,
9359
9653
  /*
9360
9654
  * Session Components
@@ -9370,6 +9664,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
9370
9664
  getMessagePreviewSetting,
9371
9665
  use: () => setActiveClient(client),
9372
9666
  isUnreadCountEnabled,
9667
+ useLegacyUnreadCount,
9373
9668
  getMarkerSyncConsistentMode,
9374
9669
  /**
9375
9670
  * Prefix for the deviceId key in the local storage or async storage.
@@ -9383,7 +9678,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
9383
9678
  return activeClient;
9384
9679
  setActiveClient(client);
9385
9680
  }
9386
- catch (_c) {
9681
+ catch (_d) {
9387
9682
  setActiveClient(client);
9388
9683
  }
9389
9684
  return client;
@@ -9840,7 +10135,7 @@ const getUserUnread = (callback) => {
9840
10135
  };
9841
10136
  };
9842
10137
 
9843
- var index$m = /*#__PURE__*/Object.freeze({
10138
+ var index$l = /*#__PURE__*/Object.freeze({
9844
10139
  __proto__: null,
9845
10140
  getActiveClient: getActiveClient,
9846
10141
  getActiveUser: getActiveUser,
@@ -11047,7 +11342,7 @@ const getMyFollowInfo = (callback) => {
11047
11342
  };
11048
11343
  /* end_public_function */
11049
11344
 
11050
- var index$l = /*#__PURE__*/Object.freeze({
11345
+ var index$k = /*#__PURE__*/Object.freeze({
11051
11346
  __proto__: null,
11052
11347
  blockUser: blockUser,
11053
11348
  unBlockUser: unBlockUser,
@@ -12062,9 +12357,9 @@ var AmityUserSearchMatchType;
12062
12357
  AmityUserSearchMatchType["PARTIAL"] = "partial";
12063
12358
  })(AmityUserSearchMatchType || (AmityUserSearchMatchType = {}));
12064
12359
 
12065
- var index$k = /*#__PURE__*/Object.freeze({
12360
+ var index$j = /*#__PURE__*/Object.freeze({
12066
12361
  __proto__: null,
12067
- Relationship: index$l,
12362
+ Relationship: index$k,
12068
12363
  getUserByIds: getUserByIds,
12069
12364
  updateUser: updateUser,
12070
12365
  flagUser: flagUser,
@@ -12172,7 +12467,7 @@ const uploadFile = async (formData, onProgress) => {
12172
12467
  const headers = 'getHeaders' in formData
12173
12468
  ? formData.getHeaders()
12174
12469
  : { 'content-type': 'multipart/form-data' };
12175
- const { data } = await client.http.post('/api/v4/files', formData, {
12470
+ const { data } = await client.upload.post('/api/v4/files', formData, {
12176
12471
  headers,
12177
12472
  onUploadProgress({ loaded, total = 100 }) {
12178
12473
  onProgress && onProgress(Math.round((loaded * 100) / total));
@@ -12262,7 +12557,7 @@ const uploadVideo = async (formData, feedType, onProgress) => {
12262
12557
  const headers = 'getHeaders' in formData
12263
12558
  ? formData.getHeaders()
12264
12559
  : { 'content-type': 'multipart/form-data' };
12265
- const { data } = await client.http.post('/api/v4/videos', formData, {
12560
+ const { data } = await client.upload.post('/api/v4/videos', formData, {
12266
12561
  headers,
12267
12562
  onUploadProgress({ loaded, total = 100 }) {
12268
12563
  onProgress && onProgress(Math.round((loaded * 100) / total));
@@ -12310,7 +12605,7 @@ const uploadImage = async (formData, onProgress) => {
12310
12605
  const headers = 'getHeaders' in formData
12311
12606
  ? formData.getHeaders()
12312
12607
  : { 'content-type': 'multipart/form-data' };
12313
- const { data } = await client.http.post('/api/v4/images', formData, {
12608
+ const { data } = await client.upload.post('/api/v4/images', formData, {
12314
12609
  headers,
12315
12610
  onUploadProgress({ loaded, total = 100 }) {
12316
12611
  onProgress && onProgress(Math.round((loaded * 100) / total));
@@ -12328,7 +12623,7 @@ const uploadImage = async (formData, onProgress) => {
12328
12623
  };
12329
12624
  /* end_public_function */
12330
12625
 
12331
- var index$j = /*#__PURE__*/Object.freeze({
12626
+ var index$i = /*#__PURE__*/Object.freeze({
12332
12627
  __proto__: null,
12333
12628
  getFile: getFile,
12334
12629
  uploadFile: uploadFile,
@@ -14140,7 +14435,7 @@ const getReactions = (params, callback, config) => {
14140
14435
  };
14141
14436
  /* end_public_function */
14142
14437
 
14143
- var index$i = /*#__PURE__*/Object.freeze({
14438
+ var index$h = /*#__PURE__*/Object.freeze({
14144
14439
  __proto__: null,
14145
14440
  addReaction: addReaction,
14146
14441
  removeReaction: removeReaction,
@@ -15956,7 +16251,7 @@ const getMessages = (params, callback, config) => {
15956
16251
  };
15957
16252
  /* end_public_function */
15958
16253
 
15959
- var index$h = /*#__PURE__*/Object.freeze({
16254
+ var index$g = /*#__PURE__*/Object.freeze({
15960
16255
  __proto__: null,
15961
16256
  createMessage: createMessage,
15962
16257
  updateMessage: updateMessage,
@@ -16482,7 +16777,7 @@ const stopMessageReceiptSync = (subChannelId) => {
16482
16777
  };
16483
16778
  /* end_public_function */
16484
16779
 
16485
- var index$g = /*#__PURE__*/Object.freeze({
16780
+ var index$f = /*#__PURE__*/Object.freeze({
16486
16781
  __proto__: null,
16487
16782
  getSubChannelByIds: getSubChannels$1,
16488
16783
  createSubChannel: createSubChannel,
@@ -16503,19 +16798,37 @@ var index$g = /*#__PURE__*/Object.freeze({
16503
16798
  /**
16504
16799
  * Internal used only
16505
16800
  *
16506
- * Fired when an {@link Amity.userMessageFeedMarkers} has been resolved by Object Rsesolver
16801
+ * Fired when an {@link Amity.channelUnreadInfo} has been updated.
16507
16802
  *
16508
16803
  * @param callback The function to call when the event was fired
16509
16804
  * @returns an {@link Amity.Unsubscriber} function to stop listening
16510
16805
  *
16511
- * @category MessageMarker Events
16806
+ * @category ChannelMarker Events
16807
+ */
16808
+ const onChannelUnreadInfoUpdatedLocal = (callback) => {
16809
+ const client = getActiveClient();
16810
+ const filter = (payload) => {
16811
+ callback(payload);
16812
+ };
16813
+ return createEventSubscriber(client, 'channelMarker/onChannelUnreadInfoUpdatedLocal', 'local.channelUnreadInfo.updated', filter);
16814
+ };
16815
+
16816
+ /**
16817
+ * Internal used only
16818
+ *
16819
+ * Fired when an {@link Amity.ChannelUnread} has been updated.
16820
+ *
16821
+ * @param callback The function to call when the event was fired
16822
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
16823
+ *
16824
+ * @category Channel Events
16512
16825
  */
16513
16826
  const onChannelUnreadUpdatedLocal = (callback) => {
16514
16827
  const client = getActiveClient();
16515
16828
  const filter = (payload) => {
16516
16829
  callback(payload);
16517
16830
  };
16518
- return createEventSubscriber(client, 'channelMarker/onChannelUnreadUpdatedLocal', 'local.channelUnread.updated', filter);
16831
+ return createEventSubscriber(client, 'channel/onChannelUnreadUpdatedLocal', 'local.channelUnread.updated', filter);
16519
16832
  };
16520
16833
 
16521
16834
  /* begin_public_function
@@ -16717,6 +17030,7 @@ const getChannel = (channelId, callback) => {
16717
17030
  return onSubChannelUpdated(updateMessagePreview);
16718
17031
  }, 'channelId', 'channel'),
16719
17032
  convertEventPayload(onSubChannelCreated, 'channelId', 'channel'),
17033
+ convertEventPayload(onChannelUnreadInfoUpdatedLocal, 'channelId', 'channel'),
16720
17034
  convertEventPayload(onChannelUnreadUpdatedLocal, 'channelId', 'channel'),
16721
17035
  ], {
16722
17036
  forceDispatch: true,
@@ -17230,6 +17544,10 @@ class ChannelLiveCollectionController extends LiveCollectionController {
17230
17544
  },
17231
17545
  action: "OnResolveUnread" /* Amity.ChannelActionType.OnResolveUnread */,
17232
17546
  },
17547
+ {
17548
+ fn: convertEventPayload(onChannelUnreadInfoUpdatedLocal, 'channelId', 'channel'),
17549
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
17550
+ },
17233
17551
  {
17234
17552
  fn: convertEventPayload(onChannelUnreadUpdatedLocal, 'channelId', 'channel'),
17235
17553
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
@@ -17289,11 +17607,125 @@ const getChannels = (params, callback, config) => {
17289
17607
  dropFromCache(cacheKey);
17290
17608
  });
17291
17609
  return () => {
17292
- log(`getChannels(tmpid: ${timestamp}) > dispose`);
17610
+ log(`getChannels(tmpid: ${timestamp}) > dispose`);
17611
+ disposers.forEach(fn => fn());
17612
+ };
17613
+ };
17614
+ /* end_public_function */
17615
+
17616
+ /**
17617
+ *
17618
+ * Calculate user unread from {@link Amity.ChannelUnread} objects
17619
+ *
17620
+ * @returns the {@link Amity.UserUnread} objects
17621
+ *
17622
+ * @category Channel API
17623
+ * @async
17624
+ */
17625
+ const getTotalChannelsUnread$1 = () => {
17626
+ var _a;
17627
+ const client = getActiveClient();
17628
+ client.log('channel/getTotalChannelsUnread.locally');
17629
+ const cachedChannelsUnread = ((_a = queryCache(['channelUnread', 'get'])) === null || _a === void 0 ? void 0 : _a.filter(({ data }) => {
17630
+ return !data.isDeleted;
17631
+ })) || [];
17632
+ const totalChannelsUnread = (cachedChannelsUnread === null || cachedChannelsUnread === void 0 ? void 0 : cachedChannelsUnread.reduce((acc, { data }) => {
17633
+ acc.unreadCount += data.unreadCount;
17634
+ acc.isMentioned = acc.isMentioned || data.isMentioned;
17635
+ return acc;
17636
+ }, { unreadCount: 0, isMentioned: false })) || { unreadCount: 0, isMentioned: false };
17637
+ const cachedAt = client.cache && Date.now();
17638
+ return {
17639
+ data: totalChannelsUnread,
17640
+ cachedAt,
17641
+ };
17642
+ };
17643
+
17644
+ /* begin_public_function
17645
+ id: totalChannelsUnread.get
17646
+ */
17647
+ /**
17648
+ * ```js
17649
+ * import { ChannelRepository } from '@amityco/ts-sdk';
17650
+ *
17651
+ * let totalChannelsUnread;
17652
+ *
17653
+ * const unsubscribe = ChannelRepository.getTotalChannelsUnread(response => {
17654
+ * unread = response.data;
17655
+ * });
17656
+ * ```
17657
+ *
17658
+ * Observe all mutation on a given {@link Amity.UserUnread}
17659
+ *
17660
+ * @returns An {@link Amity.UserUnread} function to run when willing to stop observing the message
17661
+ *
17662
+ * @category User Unread Live Object
17663
+ *
17664
+ */
17665
+ const getTotalChannelsUnread = (callback) => {
17666
+ const { _id: userId } = getActiveUser();
17667
+ if (!userId)
17668
+ throw new ASCError('The _id has not been defined in ActiveUser', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
17669
+ const { log, cache } = getActiveClient();
17670
+ if (!cache) {
17671
+ console.log('For using Live Object feature you need to enable Cache!');
17672
+ }
17673
+ const timestamp = Date.now();
17674
+ log(`liveTotalChannelsUnread(tmpid: ${timestamp}) > listen`);
17675
+ const disposers = [];
17676
+ let isUnsyncedModel = false; // for messages
17677
+ let model;
17678
+ const dispatcher = (data) => {
17679
+ const { data: userUnread } = data;
17680
+ const callbackModel = userUnread
17681
+ ? {
17682
+ unreadCount: userUnread.unreadCount,
17683
+ isMentioned: userUnread.isMentioned,
17684
+ }
17685
+ : undefined;
17686
+ model = callbackModel ? convertGetterPropsToStatic(callbackModel) : callbackModel;
17687
+ callback({
17688
+ data: callbackModel
17689
+ ? Object.assign(Object.assign({}, callbackModel), { isMentioned: callbackModel.isMentioned }) : callbackModel,
17690
+ loading: data.loading,
17691
+ error: data.error,
17692
+ });
17693
+ };
17694
+ const realtimeRouter = (userUnread) => {
17695
+ if (isEqual(model, userUnread))
17696
+ return;
17697
+ dispatcher({
17698
+ loading: false,
17699
+ data: userUnread,
17700
+ });
17701
+ };
17702
+ const onFetch = () => {
17703
+ const query = createQuery(async () => getTotalChannelsUnread$1());
17704
+ runQuery(query, ({ error, data, loading, origin, cachedAt }) => {
17705
+ if (cachedAt === UNSYNCED_OBJECT_CACHED_AT_VALUE) {
17706
+ dispatcher({
17707
+ data,
17708
+ origin,
17709
+ loading: false,
17710
+ error: new ASCApiError(UNSYNCED_OBJECT_CACHED_AT_MESSAGE, 800800 /* Amity.ClientError.DISALOOW_UNSYNCED_OBJECT */, "error" /* Amity.ErrorLevel.ERROR */),
17711
+ });
17712
+ isUnsyncedModel = true;
17713
+ disposers.forEach(fn => fn());
17714
+ }
17715
+ else if (!isUnsyncedModel) {
17716
+ dispatcher({ loading, data, origin, error });
17717
+ }
17718
+ if (error) {
17719
+ disposers.forEach(fn => fn());
17720
+ }
17721
+ });
17722
+ };
17723
+ disposers.push(onChannelUnreadUpdatedLocal(realtimeRouter));
17724
+ onFetch();
17725
+ return () => {
17293
17726
  disposers.forEach(fn => fn());
17294
17727
  };
17295
- };
17296
- /* end_public_function */
17728
+ };
17297
17729
 
17298
17730
  /* begin_public_function
17299
17731
  id: channel.member.add
@@ -17659,7 +18091,7 @@ const searchMembers$1 = (params, callback, config) => {
17659
18091
  };
17660
18092
  /* end_public_function */
17661
18093
 
17662
- var index$f = /*#__PURE__*/Object.freeze({
18094
+ var index$e = /*#__PURE__*/Object.freeze({
17663
18095
  __proto__: null,
17664
18096
  addMembers: addMembers$1,
17665
18097
  removeMembers: removeMembers$1,
@@ -17862,7 +18294,7 @@ const unmuteMembers = async (channelId, userIds) => {
17862
18294
  };
17863
18295
  /* end_public_function */
17864
18296
 
17865
- var index$e = /*#__PURE__*/Object.freeze({
18297
+ var index$d = /*#__PURE__*/Object.freeze({
17866
18298
  __proto__: null,
17867
18299
  addRole: addRole,
17868
18300
  removeRole: removeRole,
@@ -17872,10 +18304,10 @@ var index$e = /*#__PURE__*/Object.freeze({
17872
18304
  unmuteMembers: unmuteMembers
17873
18305
  });
17874
18306
 
17875
- var index$d = /*#__PURE__*/Object.freeze({
18307
+ var index$c = /*#__PURE__*/Object.freeze({
17876
18308
  __proto__: null,
17877
- Membership: index$f,
17878
- Moderation: index$e,
18309
+ Membership: index$e,
18310
+ Moderation: index$d,
17879
18311
  getChannelByIds: getChannelByIds$1,
17880
18312
  createChannel: createChannel,
17881
18313
  updateChannel: updateChannel,
@@ -17898,6 +18330,7 @@ var index$d = /*#__PURE__*/Object.freeze({
17898
18330
  onChannelMemberRoleRemoved: onChannelMemberRoleRemoved,
17899
18331
  getChannel: getChannel,
17900
18332
  getChannels: getChannels,
18333
+ getTotalChannelsUnread: getTotalChannelsUnread,
17901
18334
  MARKER_INCLUDED_CHANNEL_TYPE: MARKER_INCLUDED_CHANNEL_TYPE,
17902
18335
  isUnreadCountSupport: isUnreadCountSupport,
17903
18336
  convertFromRaw: convertFromRaw,
@@ -19254,7 +19687,7 @@ const searchMembers = (params, callback, config) => {
19254
19687
  };
19255
19688
  /* end_public_function */
19256
19689
 
19257
- var index$c = /*#__PURE__*/Object.freeze({
19690
+ var index$b = /*#__PURE__*/Object.freeze({
19258
19691
  __proto__: null,
19259
19692
  addMembers: addMembers,
19260
19693
  removeMembers: removeMembers,
@@ -20279,7 +20712,7 @@ const unbanMembers = async (communityId, userIds) => {
20279
20712
  };
20280
20713
  /* end_public_function */
20281
20714
 
20282
- var index$b = /*#__PURE__*/Object.freeze({
20715
+ var index$a = /*#__PURE__*/Object.freeze({
20283
20716
  __proto__: null,
20284
20717
  addRoles: addRoles,
20285
20718
  removeRoles: removeRoles,
@@ -20287,10 +20720,10 @@ var index$b = /*#__PURE__*/Object.freeze({
20287
20720
  unbanMembers: unbanMembers
20288
20721
  });
20289
20722
 
20290
- var index$a = /*#__PURE__*/Object.freeze({
20723
+ var index$9 = /*#__PURE__*/Object.freeze({
20291
20724
  __proto__: null,
20292
- Moderation: index$b,
20293
- Membership: index$c,
20725
+ Moderation: index$a,
20726
+ Membership: index$b,
20294
20727
  getCommunityByIds: getCommunities$1,
20295
20728
  createCommunity: createCommunity,
20296
20729
  updateCommunity: updateCommunity,
@@ -20523,7 +20956,7 @@ const getCategories = (params, callback, config) => {
20523
20956
  };
20524
20957
  /* end_public_function */
20525
20958
 
20526
- var index$9 = /*#__PURE__*/Object.freeze({
20959
+ var index$8 = /*#__PURE__*/Object.freeze({
20527
20960
  __proto__: null,
20528
20961
  getCategory: getCategory,
20529
20962
  getCategories: getCategories
@@ -20691,7 +21124,7 @@ getCustomRankingGlobalFeed.locally = (query) => {
20691
21124
  : undefined;
20692
21125
  };
20693
21126
 
20694
- var index$8 = /*#__PURE__*/Object.freeze({
21127
+ var index$7 = /*#__PURE__*/Object.freeze({
20695
21128
  __proto__: null,
20696
21129
  queryGlobalFeed: queryGlobalFeed,
20697
21130
  getCustomRankingGlobalFeed: getCustomRankingGlobalFeed
@@ -22006,7 +22439,7 @@ const getComments = (params, callback, config) => {
22006
22439
  };
22007
22440
  /* end_public_function */
22008
22441
 
22009
- var index$7 = /*#__PURE__*/Object.freeze({
22442
+ var index$6 = /*#__PURE__*/Object.freeze({
22010
22443
  __proto__: null,
22011
22444
  getCommentByIds: getCommentByIds,
22012
22445
  createComment: createComment,
@@ -23013,7 +23446,7 @@ const semanticSearchPosts = (params, callback, config) => {
23013
23446
  };
23014
23447
  };
23015
23448
 
23016
- var index$6 = /*#__PURE__*/Object.freeze({
23449
+ var index$5 = /*#__PURE__*/Object.freeze({
23017
23450
  __proto__: null,
23018
23451
  getPostByIds: getPostByIds,
23019
23452
  createPost: createPost,
@@ -23547,7 +23980,7 @@ const getStreams = (params, callback, config) => {
23547
23980
  };
23548
23981
  };
23549
23982
 
23550
- var index$5 = /*#__PURE__*/Object.freeze({
23983
+ var index$4 = /*#__PURE__*/Object.freeze({
23551
23984
  __proto__: null,
23552
23985
  createStream: createStream,
23553
23986
  updateStream: updateStream,
@@ -23834,7 +24267,7 @@ const getPoll = (pollId, callback) => {
23834
24267
  };
23835
24268
  /* end_public_function */
23836
24269
 
23837
- var index$4 = /*#__PURE__*/Object.freeze({
24270
+ var index$3 = /*#__PURE__*/Object.freeze({
23838
24271
  __proto__: null,
23839
24272
  createPoll: createPoll,
23840
24273
  closePoll: closePoll,
@@ -24205,7 +24638,7 @@ const getPlayer = async (parameters) => {
24205
24638
  return video;
24206
24639
  };
24207
24640
 
24208
- var index$3 = /*#__PURE__*/Object.freeze({
24641
+ var index$2 = /*#__PURE__*/Object.freeze({
24209
24642
  __proto__: null,
24210
24643
  getPlayer: getPlayer
24211
24644
  });
@@ -25378,7 +25811,7 @@ const getGlobalStoryTargets = (params, callback, config) => {
25378
25811
  };
25379
25812
  };
25380
25813
 
25381
- var index$2 = /*#__PURE__*/Object.freeze({
25814
+ var index$1 = /*#__PURE__*/Object.freeze({
25382
25815
  __proto__: null,
25383
25816
  createImageStory: createImageStory,
25384
25817
  createVideoStory: createVideoStory,
@@ -25415,7 +25848,7 @@ const getNetworkAds = async () => {
25415
25848
  };
25416
25849
  };
25417
25850
 
25418
- var index$1 = /*#__PURE__*/Object.freeze({
25851
+ var index = /*#__PURE__*/Object.freeze({
25419
25852
  __proto__: null,
25420
25853
  getNetworkAds: getNetworkAds
25421
25854
  });
@@ -25442,342 +25875,31 @@ const createUserToken = async (apiKey, apiRegion, params) => {
25442
25875
  return { accessToken: data.accessToken };
25443
25876
  };
25444
25877
 
25445
- /* begin_public_function
25446
- id: notificationTray.getNotificationTraySeen
25447
- */
25448
- /**
25449
- * ```js
25450
- * import { NotificationTrayRepository } from '@amityco/ts-sdk'
25451
- * const notificationTraySeen = await NotificationTrayRepository.getNotificationTraySeen()
25452
- * ```
25453
- *
25454
- *
25455
- * @returns A page of {@link Amity.NotificationTraySeen} objects
25456
- *
25457
- * @category NotificationTray API
25458
- * @async
25459
- * */
25460
- const getNotificationTraySeen$1 = async () => {
25461
- const client = getActiveClient();
25462
- client.log('notificationTray/getNotificationTraySeen', {});
25463
- const { data: payload } = await client.http.get(`api/v1/notification-tray/tray/seen`);
25464
- const cachedAt = client.cache && Date.now();
25465
- if (client.cache) {
25466
- const cacheKey = ['notificationTraySeen', 'get', client.userId];
25467
- pushToCache(cacheKey, {
25468
- userId: client.userId,
25469
- lastTraySeenAt: payload.lastTraySeenAt,
25470
- lastTrayOccuredAt: payload.lastTrayOccuredAt,
25471
- });
25472
- }
25473
- return {
25474
- data: {
25475
- userId: client.userId,
25476
- lastTraySeenAt: payload.lastTraySeenAt,
25477
- lastTrayOccuredAt: payload.lastTrayOccuredAt,
25478
- isSeen: payload.lastTraySeenAt > payload.lastTrayOccuredAt,
25479
- },
25480
- cachedAt,
25481
- };
25482
- };
25483
- /* end_public_function */
25484
- /**
25485
- * ```js
25486
- * import { NotificationTrayRepository } from '@amityco/ts-sdk'
25487
- * const notificationTraySeen = await NotificationTrayRepository.getNotificationTraySeen.locally()
25488
- * ```
25489
- *
25490
- * Queries a paginable list of {@link Amity.NotificationTraySeen} objects from cache
25491
- *
25492
- * @returns A page of {@link Amity.NotificationTraySeen} objects
25493
- *
25494
- * @category NotificationTray API
25495
- * @async
25496
- * */
25497
- getNotificationTraySeen$1.locally = () => {
25498
- var _a;
25499
- const client = getActiveClient();
25500
- client.log('notificationTray/getNotificationTraySeen.locally', {});
25501
- if (!client.cache)
25502
- return;
25503
- const queryKey = ['notificationTraySeen', 'get'];
25504
- const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
25505
- if (!(data === null || data === void 0 ? void 0 : data.notificationTraySeen))
25506
- return;
25507
- return { data: data.notificationTraySeen, cachedAt };
25508
- };
25509
-
25510
- /**
25511
- * ```js
25512
- * import { onNotificationTraySeenUpdated } from '@amityco/ts-sdk'
25513
- * const dispose = onNotificationTraySeenUpdated(data => {
25514
- * // ...
25515
- * })
25516
- * ```
25517
- *
25518
- * Fired when an {@link Amity.NotificationTraySeen} has been updated
25519
- *
25520
- * @param callback The function to call when the event was fired
25521
- * @returns an {@link Amity.Unsubscriber} function to stop listening
25522
- *
25523
- * @category NotificationTraySeen Events
25524
- */
25525
- const onNotificationTraySeenUpdated = (callback) => {
25526
- const client = getActiveClient();
25527
- const disposers = [
25528
- createEventSubscriber(client, 'onNotificationTraySeenUpdated', 'local.notificationTraySeen.updated', payload => callback(payload)),
25529
- ];
25530
- return () => {
25531
- disposers.forEach(fn => fn());
25532
- };
25533
- };
25534
-
25535
- /* begin_public_function
25536
- id: notificationTraySeen.get
25537
- */
25538
- /**
25539
- * ```js
25540
- * import { getNotificationTraySeen } from '@amityco/ts-sdk';
25541
- *
25542
- * let notificationTraySeen;
25543
- *
25544
- * const unsubscribe = getNotificationTraySeen(userId, response => {
25545
- * notificationTraySeen = response.data;
25546
- * });
25547
- * ```
25548
- *
25549
- * Observe all mutation on a given {@link Amity.NotificationTraySeen}
25550
- *
25551
- * @param userId the ID of the user to observe
25552
- * @param callback the function to call when new data are available
25553
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the message
25554
- *
25555
- * @category NotificationTraySeen Live Object
25556
- */
25557
- const getNotificationTraySeen = (callback) => {
25558
- const responder = (snapshot) => {
25559
- const { data } = snapshot;
25560
- callback(Object.assign(Object.assign({}, snapshot), { data }));
25561
- };
25562
- const { userId } = getActiveUser();
25563
- return liveObject(userId, responder, 'userId', getNotificationTraySeen$1, [
25564
- onNotificationTraySeenUpdated,
25565
- ]);
25566
- };
25567
- /* end_public_function */
25568
-
25569
- /**
25570
- * TODO: handle cache receive cache option, and cache policy
25571
- * TODO: check if querybyIds is supported
25572
- */
25573
- class NotificationTrayItemsPaginationController extends PaginationController {
25574
- async getRequest(queryParams, token) {
25575
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
25576
- const options = token ? { token } : { limit };
25577
- const { data: queryResponse } = await this.http.get(`/api/v1/notification-tray`, {
25578
- params: Object.assign(Object.assign({}, params), { options }),
25579
- });
25580
- return queryResponse;
25581
- }
25582
- }
25583
-
25584
- class NotificationTrayItemsQuerystreamController extends QueryStreamController {
25585
- constructor(query, cacheKey, notifyChange, preparePayload) {
25586
- super(query, cacheKey);
25587
- this.notifyChange = notifyChange;
25588
- this.preparePayload = preparePayload;
25589
- }
25590
- async saveToMainDB(response) {
25591
- const processedPayload = await this.preparePayload(response);
25592
- const client = getActiveClient();
25593
- const cachedAt = client.cache && Date.now();
25594
- if (client.cache) {
25595
- ingestInCache(processedPayload, { cachedAt });
25596
- }
25597
- }
25598
- appendToQueryStream(response, direction, refresh = false) {
25599
- var _a, _b;
25600
- if (refresh) {
25601
- pushToCache(this.cacheKey, {
25602
- data: response.notificationTrayItems.map(getResolver('notificationTrayItem')),
25603
- });
25604
- }
25605
- else {
25606
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25607
- const notifications = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
25608
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
25609
- ...new Set([
25610
- ...notifications,
25611
- ...response.notificationTrayItems.map(getResolver('notificationTrayItem')),
25612
- ]),
25613
- ] }));
25614
- }
25615
- }
25616
- }
25617
-
25618
- const prepareNotificationTrayItemsPayload = (rawPayload) => {
25619
- const users = rawPayload.users.map(convertRawUserToInternalUser);
25620
- return Object.assign(Object.assign({}, rawPayload), { users });
25621
- };
25622
-
25623
- class NotificationTrayItemsLiveCollectionController extends LiveCollectionController {
25624
- constructor(query, callback) {
25625
- const queryStreamId = hash__default["default"](query);
25626
- const cacheKey = ['notificationTrayItem', 'collection', queryStreamId];
25627
- const paginationController = new NotificationTrayItemsPaginationController(query);
25628
- super(paginationController, queryStreamId, cacheKey, callback);
25629
- this.query = query;
25630
- this.queryStreamController = new NotificationTrayItemsQuerystreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareNotificationTrayItemsPayload);
25631
- this.callback = callback.bind(this);
25632
- this.loadPage({ initial: true });
25633
- }
25634
- setup() {
25635
- var _a;
25636
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25637
- if (!collection) {
25638
- pushToCache(this.cacheKey, {
25639
- data: [],
25640
- params: {},
25641
- });
25642
- }
25643
- }
25644
- async persistModel(queryPayload) {
25645
- await this.queryStreamController.saveToMainDB(queryPayload);
25646
- }
25647
- persistQueryStream({ response, direction, refresh, }) {
25648
- this.queryStreamController.appendToQueryStream(response, direction, refresh);
25649
- }
25650
- // eslint-disable-next-line class-methods-use-this
25651
- startSubscription() {
25652
- return [];
25653
- }
25654
- notifyChange({ origin, loading, error }) {
25655
- var _a, _b;
25656
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25657
- if (!collection)
25658
- return;
25659
- const data = ((_b = collection.data
25660
- .map(id => pullFromCache(['notificationTrayItem', 'get', id]))
25661
- .filter(isNonNullable)
25662
- .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.notificationTray);
25663
- if (!this.shouldNotify(data) && origin === 'event')
25664
- return;
25665
- this.callback({
25666
- onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
25667
- data,
25668
- hasNextPage: !!this.paginationController.getNextToken(),
25669
- loading,
25670
- error,
25671
- });
25672
- }
25673
- }
25674
-
25675
- /**
25676
- * Get notification tray items for a notification tray page
25677
- *
25678
- * @param params the limit query parameters
25679
- * @param callback the callback to be called when the notification tray items are updated
25680
- * @returns items in the notification tray
25681
- *
25682
- * @category Notification tray items Live Collection
25683
- *
25684
- */
25685
- const getNotificationTrayItems = (params, callback, config) => {
25686
- const { log, cache } = getActiveClient();
25687
- if (!cache) {
25688
- console.log(ENABLE_CACHE_MESSAGE);
25689
- }
25690
- const timestamp = Date.now();
25691
- log(`getNotificationTrayItems(tmpid: ${timestamp}) > listen`);
25692
- const notiTrayItemsLiveCollection = new NotificationTrayItemsLiveCollectionController(params, callback);
25693
- const disposers = notiTrayItemsLiveCollection.startSubscription();
25694
- const cacheKey = notiTrayItemsLiveCollection.getCacheKey();
25695
- disposers.push(() => dropFromCache(cacheKey));
25696
- return () => {
25697
- log(`getNotificationTrayItems(tmpid: ${timestamp}) > dispose`);
25698
- disposers.forEach(fn => fn());
25699
- };
25700
- };
25701
-
25702
- /* begin_public_function
25703
- id: notificationTray.markSeen
25704
- */
25705
- /**
25706
- * ```js
25707
- * import { NotificationTrayRepository } from '@amityco/ts-sdk'
25708
- * const updated = await NotificationTrayRepository.markNotificationTraySeen({
25709
- * lastSeenAt: Amity.timestamp,
25710
- * })
25711
- * ```
25712
- *
25713
- * Updates an {@link Amity.NotificationTraySeen}
25714
- *
25715
- * @param userId The ID of the {@link Amity.NotificationTraySeen} to edit
25716
- * @param lastSeenAt The patch data to apply
25717
- * @returns the updated {@link Amity.NotificationTraySeen} object
25718
- *
25719
- * @category Post API
25720
- * @async
25721
- */
25722
- const markNotificationTraySeen = async (lastSeenAt) => {
25723
- var _a;
25724
- const client = getActiveClient();
25725
- client.log('notificationTray/markNotificationTraySeen', {});
25726
- const { data: payload } = await client.http.put(`api/v1/notification-tray/tray/seen`, {
25727
- lastSeenAt,
25728
- });
25729
- const cacheData = (_a = pullFromCache([
25730
- 'notificationTraySeen',
25731
- 'get',
25732
- ])) === null || _a === void 0 ? void 0 : _a.data;
25733
- const data = Object.assign({ userId: client.userId }, payload);
25734
- const updateCacheData = Object.assign(Object.assign({}, cacheData), data);
25735
- const cachedAt = client.cache && Date.now();
25736
- if (client.cache)
25737
- pushToCache(['notificationTraySeen', 'get', client.userId], updateCacheData, { cachedAt });
25738
- fireEvent('local.notificationTraySeen.updated', data);
25739
- return {
25740
- data: payload,
25741
- cachedAt,
25742
- };
25743
- };
25744
- /* end_public_function */
25745
-
25746
- var index = /*#__PURE__*/Object.freeze({
25747
- __proto__: null,
25748
- getNotificationTraySeen: getNotificationTraySeen,
25749
- getNotificationTrayItems: getNotificationTrayItems,
25750
- markNotificationItemsSeen: markNotificationItemsSeen,
25751
- markNotificationTraySeen: markNotificationTraySeen,
25752
- onNotificationTraySeenUpdated: onNotificationTraySeenUpdated
25753
- });
25754
-
25755
25878
  exports.API_REGIONS = API_REGIONS;
25756
- exports.AdRepository = index$1;
25757
- exports.CategoryRepository = index$9;
25758
- exports.ChannelRepository = index$d;
25759
- exports.Client = index$m;
25760
- exports.CommentRepository = index$7;
25879
+ exports.AdRepository = index;
25880
+ exports.CategoryRepository = index$8;
25881
+ exports.ChannelRepository = index$c;
25882
+ exports.Client = index$l;
25883
+ exports.CommentRepository = index$6;
25761
25884
  exports.CommunityPostSettingMaps = CommunityPostSettingMaps;
25762
25885
  exports.CommunityPostSettings = CommunityPostSettings;
25763
- exports.CommunityRepository = index$a;
25886
+ exports.CommunityRepository = index$9;
25764
25887
  exports.ContentFeedType = ContentFeedType;
25765
25888
  exports.DefaultCommunityPostSetting = DefaultCommunityPostSetting;
25766
- exports.FeedRepository = index$8;
25767
- exports.FileRepository = index$j;
25889
+ exports.FeedRepository = index$7;
25890
+ exports.FileRepository = index$i;
25768
25891
  exports.FileType = FileType;
25769
- exports.LiveStreamPlayer = index$3;
25892
+ exports.LiveStreamPlayer = index$2;
25770
25893
  exports.MessageContentType = MessageContentType;
25771
- exports.MessageRepository = index$h;
25772
- exports.NotificationTrayRepository = index;
25773
- exports.PollRepository = index$4;
25894
+ exports.MessageRepository = index$g;
25895
+ exports.PollRepository = index$3;
25774
25896
  exports.PostContentType = PostContentType;
25775
- exports.PostRepository = index$6;
25776
- exports.ReactionRepository = index$i;
25777
- exports.StoryRepository = index$2;
25778
- exports.StreamRepository = index$5;
25779
- exports.SubChannelRepository = index$g;
25780
- exports.UserRepository = index$k;
25897
+ exports.PostRepository = index$5;
25898
+ exports.ReactionRepository = index$h;
25899
+ exports.StoryRepository = index$1;
25900
+ exports.StreamRepository = index$4;
25901
+ exports.SubChannelRepository = index$f;
25902
+ exports.UserRepository = index$j;
25781
25903
  exports.VERSION = VERSION;
25782
25904
  exports.VideoResolution = VideoResolution;
25783
25905
  exports.VideoSize = VideoSize;