@amityco/ts-sdk-react-native 6.23.0 → 6.23.1-d5c2fe6.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 (131) hide show
  1. package/.env +26 -26
  2. package/dist/@types/core/events.d.ts +5 -0
  3. package/dist/@types/core/events.d.ts.map +1 -1
  4. package/dist/@types/domains/community.d.ts +16 -1
  5. package/dist/@types/domains/community.d.ts.map +1 -1
  6. package/dist/client/api/secureLogout.d.ts +1 -1
  7. package/dist/client/utils/ReadReceiptSync/readReceiptSyncEngine.d.ts.map +1 -1
  8. package/dist/commentRepository/api/deleteComment.d.ts.map +1 -1
  9. package/dist/commentRepository/events/utils.d.ts.map +1 -1
  10. package/dist/commentRepository/internalApi/createComment.d.ts.map +1 -1
  11. package/dist/communityRepository/api/createCommunity.d.ts.map +1 -1
  12. package/dist/communityRepository/api/getCommunities.d.ts.map +1 -1
  13. package/dist/communityRepository/api/getCommunity.d.ts.map +1 -1
  14. package/dist/communityRepository/api/queryCommunities.d.ts.map +1 -1
  15. package/dist/communityRepository/api/updateCommunity.d.ts.map +1 -1
  16. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.d.ts +14 -0
  17. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.d.ts.map +1 -0
  18. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.d.ts +9 -0
  19. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.d.ts.map +1 -0
  20. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts +15 -0
  21. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts.map +1 -0
  22. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts +10 -0
  23. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts.map +1 -0
  24. package/dist/communityRepository/communityMembership/observers/getMembers.d.ts.map +1 -1
  25. package/dist/communityRepository/communityMembership/observers/searchMembers.d.ts +20 -0
  26. package/dist/communityRepository/communityMembership/observers/searchMembers.d.ts.map +1 -0
  27. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts +14 -0
  28. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts.map +1 -0
  29. package/dist/communityRepository/observers/getCommunities/CommunitiesPaginationController.d.ts +9 -0
  30. package/dist/communityRepository/observers/getCommunities/CommunitiesPaginationController.d.ts.map +1 -0
  31. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts +15 -0
  32. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts.map +1 -0
  33. package/dist/communityRepository/observers/getCommunities/enums.d.ts +6 -0
  34. package/dist/communityRepository/observers/getCommunities/enums.d.ts.map +1 -0
  35. package/dist/communityRepository/observers/getCommunities.d.ts.map +1 -1
  36. package/dist/communityRepository/observers/index.d.ts +1 -0
  37. package/dist/communityRepository/observers/index.d.ts.map +1 -1
  38. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.d.ts +14 -0
  39. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.d.ts.map +1 -0
  40. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts +9 -0
  41. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts.map +1 -0
  42. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts +15 -0
  43. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts.map +1 -0
  44. package/dist/communityRepository/observers/searchCommunities/enums.d.ts +6 -0
  45. package/dist/communityRepository/observers/searchCommunities/enums.d.ts.map +1 -0
  46. package/dist/communityRepository/observers/searchCommunities.d.ts +20 -0
  47. package/dist/communityRepository/observers/searchCommunities.d.ts.map +1 -0
  48. package/dist/communityRepository/utils/payload.d.ts.map +1 -1
  49. package/dist/communityRepository/utils/saveCommunityUsers.d.ts +2 -0
  50. package/dist/communityRepository/utils/saveCommunityUsers.d.ts.map +1 -0
  51. package/dist/core/events.d.ts +3 -3
  52. package/dist/core/events.d.ts.map +1 -1
  53. package/dist/core/liveCollection/LiveCollectionController.d.ts +4 -1
  54. package/dist/core/liveCollection/LiveCollectionController.d.ts.map +1 -1
  55. package/dist/index.cjs.js +1149 -797
  56. package/dist/index.esm.js +1148 -796
  57. package/dist/index.umd.js +4 -4
  58. package/dist/marker/events/onChannelUnreadUpdatedLocal.d.ts +12 -0
  59. package/dist/marker/events/onChannelUnreadUpdatedLocal.d.ts.map +1 -0
  60. package/dist/marker/events/onSubChannelUnreadUpdatedLocal.d.ts +12 -0
  61. package/dist/marker/events/onSubChannelUnreadUpdatedLocal.d.ts.map +1 -0
  62. package/dist/marker/events/onUserFeedMarkerUpdated.d.ts.map +1 -1
  63. package/dist/marker/utils/reCalculateChannelUnreadInfo.d.ts +1 -1
  64. package/dist/marker/utils/reCalculateChannelUnreadInfo.d.ts.map +1 -1
  65. package/dist/postRepository/observers/getPost.d.ts.map +1 -1
  66. package/dist/postRepository/observers/getPosts.d.ts.map +1 -1
  67. package/dist/streamRepository/api/getStreams.d.ts +2 -2
  68. package/dist/streamRepository/events/onStreamFlagged.d.ts +17 -0
  69. package/dist/streamRepository/events/onStreamFlagged.d.ts.map +1 -0
  70. package/dist/streamRepository/events/onStreamTerminated.d.ts +17 -0
  71. package/dist/streamRepository/events/onStreamTerminated.d.ts.map +1 -0
  72. package/dist/streamRepository/observers/getStreams.d.ts +1 -1
  73. package/dist/utils/liveObject.d.ts +3 -0
  74. package/dist/utils/liveObject.d.ts.map +1 -1
  75. package/package.json +1 -1
  76. package/src/@types/core/events.ts +8 -0
  77. package/src/@types/domains/community.ts +26 -1
  78. package/src/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.ts +2 -2
  79. package/src/channelRepository/observers/getChannel.ts +2 -2
  80. package/src/channelRepository/observers/getChannels/ChannelLiveCollectionController.ts +7 -7
  81. package/src/client/api/secureLogout.ts +1 -1
  82. package/src/client/utils/ReadReceiptSync/readReceiptSyncEngine.ts +6 -3
  83. package/src/commentRepository/api/createComment.ts +2 -2
  84. package/src/commentRepository/api/deleteComment.ts +2 -4
  85. package/src/commentRepository/events/utils.ts +8 -5
  86. package/src/commentRepository/internalApi/createComment.ts +3 -2
  87. package/src/commentRepository/internalApi/deleteComment.ts +2 -2
  88. package/src/communityRepository/api/createCommunity.ts +5 -2
  89. package/src/communityRepository/api/getCommunities.ts +5 -1
  90. package/src/communityRepository/api/getCommunity.ts +5 -1
  91. package/src/communityRepository/api/queryCommunities.ts +2 -2
  92. package/src/communityRepository/api/updateCommunity.ts +5 -1
  93. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.ts +152 -0
  94. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.ts +26 -0
  95. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.ts +107 -0
  96. package/src/communityRepository/communityMembership/observers/getMembers/enums.ts +9 -0
  97. package/src/communityRepository/communityMembership/observers/getMembers.ts +15 -128
  98. package/src/communityRepository/communityMembership/observers/searchMembers.ts +60 -0
  99. package/src/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.ts +147 -0
  100. package/src/communityRepository/observers/getCommunities/CommunitiesPaginationController.ts +31 -0
  101. package/src/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.ts +88 -0
  102. package/src/communityRepository/observers/getCommunities/enums.ts +5 -0
  103. package/src/communityRepository/observers/getCommunities.ts +7 -150
  104. package/src/communityRepository/observers/index.ts +1 -0
  105. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.ts +129 -0
  106. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.ts +31 -0
  107. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.ts +81 -0
  108. package/src/communityRepository/observers/searchCommunities/enums.ts +5 -0
  109. package/src/communityRepository/observers/searchCommunities.ts +56 -0
  110. package/src/communityRepository/utils/payload.ts +35 -1
  111. package/src/communityRepository/utils/saveCommunityUsers.ts +16 -0
  112. package/src/core/liveCollection/LiveCollectionController.ts +6 -3
  113. package/src/marker/events/onChannelUnreadUpdatedLocal.ts +29 -0
  114. package/src/marker/events/onSubChannelMarkerFetched.ts +1 -1
  115. package/src/marker/events/onSubChannelUnreadUpdatedLocal.ts +29 -0
  116. package/src/marker/events/onUserFeedMarkerUpdated.ts +3 -4
  117. package/src/marker/utils/reCalculateChannelUnreadInfo.ts +7 -3
  118. package/src/messageRepository/observers/getMessages/MessageLiveCollectionController.ts +3 -3
  119. package/src/postRepository/api/editPost.ts +1 -1
  120. package/src/postRepository/api/updatePost.ts +1 -1
  121. package/src/postRepository/observers/getPost.ts +26 -0
  122. package/src/postRepository/observers/getPosts.ts +31 -0
  123. package/src/storyRepository/observers/getGlobalStoryTargets/GlobalStoryLiveCollectionController.ts +2 -2
  124. package/src/storyRepository/observers/getStoriesByTargetIds/StoryLiveCollectionController.ts +1 -1
  125. package/src/streamRepository/api/getStreams.ts +2 -2
  126. package/src/streamRepository/events/onStreamFlagged.ts +37 -0
  127. package/src/streamRepository/events/onStreamTerminated.ts +37 -0
  128. package/src/streamRepository/observers/getStreams.ts +1 -1
  129. package/src/subChannelRepository/observers/getSubChannel.ts +2 -2
  130. package/src/subChannelRepository/observers/getSubChannels/SubChannelLiveCollectionController.ts +4 -4
  131. package/src/utils/liveObject.ts +3 -0
package/dist/index.esm.js CHANGED
@@ -21499,7 +21499,7 @@ const markAsReadBySegment = async ({ subChannelId, readToSegment, }) => {
21499
21499
  }
21500
21500
  };
21501
21501
 
21502
- const reCalculateChannelUnreadInfo = async (channelId) => {
21502
+ const reCalculateChannelUnreadInfo = (channelId) => {
21503
21503
  var _a;
21504
21504
  const cacheKeyChannelUnread = ['channelUnreadInfo', 'get', channelId];
21505
21505
  const cacheChannelUnreadInfo = (_a = pullFromCache(cacheKeyChannelUnread)) === null || _a === void 0 ? void 0 : _a.data;
@@ -21516,10 +21516,12 @@ const reCalculateChannelUnreadInfo = async (channelId) => {
21516
21516
  .reduce((acc, cur) => acc + cur, 0);
21517
21517
  isMentioned = subChannelUnreadsInfo.some(({ data }) => data.isMentioned);
21518
21518
  }
21519
- pushToCache(cacheKeyChannelUnread, Object.assign(Object.assign({}, (cacheChannelUnreadInfo !== null && cacheChannelUnreadInfo !== void 0 ? cacheChannelUnreadInfo : {
21519
+ const channelUnreadInfo = Object.assign(Object.assign({}, (cacheChannelUnreadInfo !== null && cacheChannelUnreadInfo !== void 0 ? cacheChannelUnreadInfo : {
21520
21520
  channelId,
21521
21521
  createdAt: new Date().toISOString(),
21522
- })), { updatedAt: new Date().toISOString(), unreadCount: channelUnreads, isMentioned }));
21522
+ })), { updatedAt: new Date().toISOString(), unreadCount: channelUnreads, isMentioned });
21523
+ pushToCache(cacheKeyChannelUnread, channelUnreadInfo);
21524
+ return channelUnreadInfo;
21523
21525
  };
21524
21526
 
21525
21527
  class MessageReadReceiptSyncEngine {
@@ -21664,9 +21666,11 @@ class MessageReadReceiptSyncEngine {
21664
21666
  if (subChannelUnreadInfo && segment > subChannelUnreadInfo.readToSegment) {
21665
21667
  subChannelUnreadInfo.readToSegment = segment;
21666
21668
  subChannelUnreadInfo.unreadCount = Math.max(subChannelUnreadInfo.lastSegment - segment, 0);
21667
- reCalculateChannelUnreadInfo(subChannelUnreadInfo.channelId);
21669
+ const channelUnreadInfo = reCalculateChannelUnreadInfo(subChannelUnreadInfo.channelId);
21670
+ fireEvent('local.channelUnread.updated', channelUnreadInfo);
21671
+ pushToCache(cacheKey, subChannelUnreadInfo);
21672
+ fireEvent('local.subChannelUnread.updated', subChannelUnreadInfo);
21668
21673
  }
21669
- pushToCache(cacheKey, subChannelUnreadInfo);
21670
21674
  // Step 2: Enqueue the read receipt
21671
21675
  this.enqueueReadReceipt(subChannelId, segment);
21672
21676
  }
@@ -24661,9 +24665,9 @@ const enableUnreadCount = () => {
24661
24665
  const onUserFeedMarkerUpdated = (callback) => {
24662
24666
  const client = getActiveClient();
24663
24667
  const filter = (payload) => {
24664
- // update sub channel unread info and channel unread info in cache
24665
- persistUnreadCountInfo(payload);
24666
- callback(payload.feedMarkers[0]);
24668
+ payload.feedMarkers.forEach(feedMarker => {
24669
+ callback(feedMarker);
24670
+ });
24667
24671
  };
24668
24672
  return createEventSubscriber(client, 'feedMarker/onUserFeedMarkerUpdated', 'marker.userFeed-updated', filter);
24669
24673
  };
@@ -25173,7 +25177,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
25173
25177
  */
25174
25178
  /**
25175
25179
  * ```js
25176
- * import { Client } from '@amityco/ts-sdk'
25180
+ * import { Client } from '@amityco/ts-sdk-react-native'
25177
25181
  * const success = await Client.secureLogout()
25178
25182
  * ```
25179
25183
  *
@@ -25259,7 +25263,7 @@ const onChannelMarkerFetched = (callback) => {
25259
25263
  const onSubChannelMarkerFetched = (callback) => {
25260
25264
  const client = getActiveClient();
25261
25265
  const filter = (payload) => {
25262
- callback(payload.userFeedMarkers[0]);
25266
+ payload.userFeedMarkers.forEach(callback);
25263
25267
  };
25264
25268
  return createEventSubscriber(client, 'subChannelMarker/onSubChannelMarkerFetched', 'local.subChannelMarker.fetched', filter);
25265
25269
  };
@@ -25529,6 +25533,9 @@ function isEqual(x, y) {
25529
25533
  }));
25530
25534
  }
25531
25535
 
25536
+ /**
25537
+ * @deprecated This function is deprecated
25538
+ */
25532
25539
  const liveObject = (id, callback, key, fetcher, eventHandlers, options) => {
25533
25540
  const { forceDispatch, callbackDataSelector, callbackFilter } = Object.assign({ forceDispatch: false, callbackDataSelector: (data) => data }, options);
25534
25541
  const { cache } = getActiveClient();
@@ -29085,7 +29092,10 @@ const createCommentEventSubscriber = (event, callback) => {
29085
29092
  comments[0].parentId,
29086
29093
  ]);
29087
29094
  if (parentComment === null || parentComment === void 0 ? void 0 : parentComment.data) {
29088
- pushToCache(['comment', 'get', comments[0].parentId], Object.assign(Object.assign({}, parentComment.data), { childrenNumber: parentComment.data.childrenNumber + 1, children: [...new Set([...parentComment.data.children, comments[0].commentId])] }));
29095
+ // Skip to update parent childComment if current comment already exists
29096
+ if (!parentComment.data.children.includes(comments[0].commentId)) {
29097
+ pushToCache(['comment', 'get', comments[0].parentId], Object.assign(Object.assign({}, parentComment.data), { childrenNumber: parentComment.data.childrenNumber + 1, children: [...new Set([...parentComment.data.children, comments[0].commentId])] }));
29098
+ }
29089
29099
  }
29090
29100
  }
29091
29101
  const queries = (_a = queryCache(['comment', 'query'])) === null || _a === void 0 ? void 0 : _a.filter(({ key }) => { var _a; return ((_a = key[2]) === null || _a === void 0 ? void 0 : _a.referenceId) === comment.data.referenceId; });
@@ -31514,7 +31524,7 @@ class LiveCollectionController {
31514
31524
  this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
31515
31525
  }
31516
31526
  }
31517
- loadPage(initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
31527
+ loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
31518
31528
  this.setup();
31519
31529
  this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
31520
31530
  if (initial) {
@@ -31584,7 +31594,7 @@ class MessageLiveCollectionController extends LiveCollectionController {
31584
31594
  this.query = query;
31585
31595
  this.queryStreamController = new MessageQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareMessagePayload, this.paginationController);
31586
31596
  this.callback = callback.bind(this);
31587
- this.loadPage(true);
31597
+ this.loadPage({ initial: true });
31588
31598
  }
31589
31599
  setup() {
31590
31600
  var _a;
@@ -31632,8 +31642,8 @@ class MessageLiveCollectionController extends LiveCollectionController {
31632
31642
  if (!this.shouldNotify(data) && origin === 'event')
31633
31643
  return;
31634
31644
  this.callback({
31635
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
31636
- onPrevPage: () => this.loadPage(false, "prev" /* Amity.LiveCollectionPageDirection.PREV */),
31645
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
31646
+ onPrevPage: () => this.loadPage({ direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */ }),
31637
31647
  data,
31638
31648
  hasNextPage: !!this.paginationController.getNextToken(),
31639
31649
  hasPrevPage: !!this.paginationController.getPrevToken(),
@@ -31915,6 +31925,24 @@ var index$f = /*#__PURE__*/Object.freeze({
31915
31925
  convertQueryParams: convertQueryParams$1
31916
31926
  });
31917
31927
 
31928
+ /**
31929
+ * Internal used only
31930
+ *
31931
+ * Fired when an {@link Amity.userMessageFeedMarkers} has been resolved by Object Rsesolver
31932
+ *
31933
+ * @param callback The function to call when the event was fired
31934
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
31935
+ *
31936
+ * @category MessageMarker Events
31937
+ */
31938
+ const onSubChannelUnreadUpdatedLocal = (callback) => {
31939
+ const client = getActiveClient();
31940
+ const filter = (payload) => {
31941
+ callback(payload);
31942
+ };
31943
+ return createEventSubscriber(client, 'subChannelMarker/onSubChannelUnreadUpdatedLocal', 'local.subChannelUnread.updated', filter);
31944
+ };
31945
+
31918
31946
  /* begin_public_function
31919
31947
  id: subchannel.get
31920
31948
  */
@@ -32067,7 +32095,7 @@ const getSubChannel = (subChannelId, callback) => {
32067
32095
  };
32068
32096
  return onMessageDeleted(updateMessagePreview);
32069
32097
  }, 'subChannelId', 'subChannel'),
32070
- convertEventPayload(onUserFeedMarkerUpdated, 'feedId', 'subChannel'),
32098
+ convertEventPayload(onSubChannelUnreadUpdatedLocal, 'subChannelId', 'subChannel'),
32071
32099
  ], {
32072
32100
  forceDispatch: true,
32073
32101
  });
@@ -32157,7 +32185,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
32157
32185
  this.query = query;
32158
32186
  this.queryStreamController = new SubChannelQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareSubChannelPayload);
32159
32187
  this.callback = callback.bind(this);
32160
- this.loadPage(true);
32188
+ this.loadPage({ initial: true });
32161
32189
  }
32162
32190
  setup() {
32163
32191
  var _a;
@@ -32334,7 +32362,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
32334
32362
  action: 'onUpdate',
32335
32363
  },
32336
32364
  {
32337
- fn: convertEventPayload(onUserFeedMarkerUpdated, 'feedId', 'subChannel'),
32365
+ fn: convertEventPayload(onSubChannelUnreadUpdatedLocal, 'subChannelId', 'subChannel'),
32338
32366
  action: 'onUpdate',
32339
32367
  },
32340
32368
  ]);
@@ -32352,7 +32380,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
32352
32380
  if (!this.shouldNotify(data) && origin === 'event')
32353
32381
  return;
32354
32382
  this.callback({
32355
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
32383
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
32356
32384
  data,
32357
32385
  hasNextPage: !!this.paginationController.getNextToken(),
32358
32386
  loading,
@@ -32492,6 +32520,24 @@ var index$e = /*#__PURE__*/Object.freeze({
32492
32520
  stopMessageReceiptSync: stopMessageReceiptSync
32493
32521
  });
32494
32522
 
32523
+ /**
32524
+ * Internal used only
32525
+ *
32526
+ * Fired when an {@link Amity.userMessageFeedMarkers} has been resolved by Object Rsesolver
32527
+ *
32528
+ * @param callback The function to call when the event was fired
32529
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
32530
+ *
32531
+ * @category MessageMarker Events
32532
+ */
32533
+ const onChannelUnreadUpdatedLocal = (callback) => {
32534
+ const client = getActiveClient();
32535
+ const filter = (payload) => {
32536
+ callback(payload);
32537
+ };
32538
+ return createEventSubscriber(client, 'channelMarker/onChannelUnreadUpdatedLocal', 'local.channelUnread.updated', filter);
32539
+ };
32540
+
32495
32541
  /* begin_public_function
32496
32542
  id: channel.get
32497
32543
  */
@@ -32667,7 +32713,7 @@ const getChannel = (channelId, callback) => {
32667
32713
  return onSubChannelUpdated(updateMessagePreview);
32668
32714
  }, 'channelId', 'channel'),
32669
32715
  convertEventPayload(onSubChannelCreated, 'channelId', 'channel'),
32670
- convertEventPayload(onUserFeedMarkerUpdated, 'entityId', 'channel'),
32716
+ convertEventPayload(onChannelUnreadUpdatedLocal, 'channelId', 'channel'),
32671
32717
  ], {
32672
32718
  forceDispatch: true,
32673
32719
  });
@@ -32827,7 +32873,7 @@ class ChannelLiveCollectionController extends LiveCollectionController {
32827
32873
  }, paginationController);
32828
32874
  this.paginationController = paginationController;
32829
32875
  this.callback = callback.bind(this);
32830
- this.loadPage(true);
32876
+ this.loadPage({ initial: true });
32831
32877
  }
32832
32878
  setup() {
32833
32879
  var _a;
@@ -32866,7 +32912,7 @@ class ChannelLiveCollectionController extends LiveCollectionController {
32866
32912
  return;
32867
32913
  this.callback({
32868
32914
  onNextPage: this.paginationController instanceof ChannelPaginationController
32869
- ? () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */)
32915
+ ? () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ })
32870
32916
  : undefined,
32871
32917
  data,
32872
32918
  hasNextPage: this.paginationController instanceof ChannelPaginationController
@@ -33146,10 +33192,6 @@ class ChannelLiveCollectionController extends LiveCollectionController {
33146
33192
  }, 'channelId', 'channel'),
33147
33193
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
33148
33194
  },
33149
- {
33150
- fn: convertEventPayload(onUserFeedMarkerUpdated, 'entityId', 'channel'),
33151
- action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
33152
- },
33153
33195
  {
33154
33196
  fn: convertEventPayload(onSubChannelCreated, 'channelId', 'channel'),
33155
33197
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
@@ -33175,6 +33217,10 @@ class ChannelLiveCollectionController extends LiveCollectionController {
33175
33217
  },
33176
33218
  action: "onResolve" /* Amity.ChannelActionType.OnResolve */,
33177
33219
  },
33220
+ {
33221
+ fn: convertEventPayload(onChannelUnreadUpdatedLocal, 'channelId', 'channel'),
33222
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
33223
+ },
33178
33224
  ];
33179
33225
  if (this.paginationController instanceof PaginationController) {
33180
33226
  return [
@@ -33389,7 +33435,7 @@ class ChannelMemberLiveCollectionController extends LiveCollectionController {
33389
33435
  this.query = query;
33390
33436
  this.queryStreamController = new ChannelMemberQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareChannelPayload);
33391
33437
  this.callback = callback.bind(this);
33392
- this.loadPage(true);
33438
+ this.loadPage({ initial: true });
33393
33439
  }
33394
33440
  setup() {
33395
33441
  var _a;
@@ -33431,7 +33477,7 @@ class ChannelMemberLiveCollectionController extends LiveCollectionController {
33431
33477
  if (!this.shouldNotify(data) && origin === 'event')
33432
33478
  return;
33433
33479
  this.callback({
33434
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
33480
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
33435
33481
  data,
33436
33482
  hasNextPage: !!this.paginationController.getNextToken(),
33437
33483
  loading,
@@ -33821,12 +33867,30 @@ var index$b = /*#__PURE__*/Object.freeze({
33821
33867
  prepareChannelPayload: prepareChannelPayload
33822
33868
  });
33823
33869
 
33870
+ const saveCommunityUsers = (communities, communityUsers) => {
33871
+ if (communities.length === 0 || communityUsers.length === 0)
33872
+ return;
33873
+ communities.forEach(({ communityId }) => {
33874
+ const collection = communityUsers.filter(({ communityId: userCommunityId }) => communityId === userCommunityId);
33875
+ pushToCache(['communityUsers', 'collection', communityId], collection);
33876
+ });
33877
+ };
33878
+
33824
33879
  const getMatchPostSetting = (value) => {
33825
33880
  var _a;
33826
33881
  return (_a = Object.keys(CommunityPostSettingMaps).find(key => value.needApprovalOnPostCreation ===
33827
33882
  CommunityPostSettingMaps[key].needApprovalOnPostCreation &&
33828
33883
  value.onlyAdminCanPost === CommunityPostSettingMaps[key].onlyAdminCanPost)) !== null && _a !== void 0 ? _a : DefaultCommunityPostSetting;
33829
33884
  };
33885
+ const convertCommunityUsersToUniqueObject = (communityUsers) => {
33886
+ if (!communityUsers)
33887
+ return communityUsers;
33888
+ const result = {};
33889
+ communityUsers.forEach(user => {
33890
+ result[`${user.userId}#${user.communityId}`] = user;
33891
+ });
33892
+ return result;
33893
+ };
33830
33894
  const prepareCommunityPayload = (rawPayload) => {
33831
33895
  // Unpack community payload by mapping payload field to postSetting value.
33832
33896
  const communities = rawPayload.communities.map((_a) => {
@@ -33836,7 +33900,18 @@ const prepareCommunityPayload = (rawPayload) => {
33836
33900
  onlyAdminCanPost,
33837
33901
  }) }, restCommunityPayload));
33838
33902
  });
33839
- const communityUsers = withUsers(rawPayload.communityUsers);
33903
+ const mergeCommunityUsers = communities.reduce((acc, { communityId }) => {
33904
+ var _a;
33905
+ const users = (_a = pullFromCache([
33906
+ 'communityUsers',
33907
+ 'collection',
33908
+ communityId,
33909
+ ])) === null || _a === void 0 ? void 0 : _a.data;
33910
+ if (!users)
33911
+ return acc;
33912
+ return Object.assign(Object.assign({}, convertCommunityUsersToUniqueObject(users)), acc);
33913
+ }, convertCommunityUsersToUniqueObject(rawPayload.communityUsers));
33914
+ const communityUsers = withUsers(Object.values(mergeCommunityUsers));
33840
33915
  const communityWithMembershipStatus = updateMembershipStatus(communities, communityUsers);
33841
33916
  return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers });
33842
33917
  };
@@ -33870,8 +33945,10 @@ const getCommunities$1 = async (communityIds) => {
33870
33945
  });
33871
33946
  const data = prepareCommunityPayload(payload);
33872
33947
  const cachedAt = client.cache && Date.now();
33873
- if (client.cache)
33948
+ if (client.cache) {
33874
33949
  ingestInCache(data, { cachedAt });
33950
+ saveCommunityUsers(data.communities, data.communityUsers);
33951
+ }
33875
33952
  return {
33876
33953
  data: data.communities,
33877
33954
  cachedAt,
@@ -33933,8 +34010,10 @@ const createCommunity = async (bundle) => {
33933
34010
  fireEvent('community.created', payload);
33934
34011
  const data = prepareCommunityPayload(payload);
33935
34012
  const cachedAt = client.cache && Date.now();
33936
- if (client.cache)
34013
+ if (client.cache) {
33937
34014
  ingestInCache(data, { cachedAt });
34015
+ saveCommunityUsers(data.communities, data.communityUsers);
34016
+ }
33938
34017
  const { communities } = data;
33939
34018
  return {
33940
34019
  data: communities[0],
@@ -33968,8 +34047,10 @@ const updateCommunity = async (communityId, patch) => {
33968
34047
  fireEvent('community.updated', payload);
33969
34048
  const data = prepareCommunityPayload(payload);
33970
34049
  const cachedAt = client.cache && Date.now();
33971
- if (client.cache)
34050
+ if (client.cache) {
33972
34051
  ingestInCache(data, { cachedAt });
34052
+ saveCommunityUsers(data.communities, data.communityUsers);
34053
+ }
33973
34054
  const { communities } = data;
33974
34055
  return {
33975
34056
  data: communities.find(community => community.communityId === communityId),
@@ -33999,8 +34080,10 @@ const getCommunity$1 = async (communityId) => {
33999
34080
  const { data: payload } = await client.http.get(`/api/v3/communities/${communityId}`);
34000
34081
  const data = prepareCommunityPayload(payload);
34001
34082
  const cachedAt = client.cache && Date.now();
34002
- if (client.cache)
34083
+ if (client.cache) {
34003
34084
  ingestInCache(data, { cachedAt });
34085
+ saveCommunityUsers(data.communities, data.communityUsers);
34086
+ }
34004
34087
  const { communities } = data;
34005
34088
  return {
34006
34089
  data: communities.find(community => community.communityId === communityId),
@@ -34540,50 +34623,140 @@ const observeCommunity = (communityId, callback) => {
34540
34623
  };
34541
34624
 
34542
34625
  /**
34543
- * ```js
34544
- * import { queryCommunities } from '@amityco/ts-sdk-react-native'
34545
- * const communities = await queryCommunities()
34546
- * ```
34547
- *
34548
- * Queries a paginable list of {@link Amity.Community} objects
34549
- * Search is performed by displayName such as `.startsWith(search)`
34550
- *
34551
- * @param query The query parameters
34552
- * @returns A page of {@link Amity.Community} objects
34553
- *
34554
- * @category Community API
34555
- * @async
34626
+ * TODO: handle cache receive cache option, and cache policy
34627
+ * TODO: check if querybyIds is supported
34556
34628
  */
34557
- const queryCommunities = async (query) => {
34558
- const client = getActiveClient();
34559
- client.log('channel/queryCommunities', query);
34560
- // safe decapsulation
34561
- const _a = query !== null && query !== void 0 ? query : {}, { page, limit = 10 } = _a, params = __rest(_a, ["page", "limit"]);
34562
- const _b = params !== null && params !== void 0 ? params : {}, { displayName, membership, includeDeleted } = _b, restParams = __rest(_b, ["displayName", "membership", "includeDeleted"]);
34563
- const options = (() => {
34564
- if (page)
34565
- return { token: page };
34566
- if (limit)
34567
- return { limit };
34568
- return undefined;
34569
- })();
34570
- // API-FIX: parameters should be querystring.
34571
- // API-FIX: backend doesn't answer Amity.Response
34572
- // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<CommunityPayload>>>(
34573
- const { data } = await client.http.get(`/api/v3/communities`, {
34574
- params: Object.assign(Object.assign({}, restParams), { isDeleted: inferIsDeleted(includeDeleted), keyword: displayName, filter: membership, options }),
34575
- });
34576
- const { paging } = data, payload = __rest(data, ["paging"]);
34577
- const unpackedPayload = prepareCommunityPayload(payload);
34578
- const { communities } = unpackedPayload;
34579
- const cachedAt = client.cache && Date.now();
34580
- if (client.cache) {
34581
- ingestInCache(unpackedPayload, { cachedAt });
34582
- const cacheKey = ['community', 'query', Object.assign(Object.assign({}, params), { options })];
34583
- pushToCache(cacheKey, { communities: communities.map(getResolver('community')), paging });
34629
+ class CommunitiesPaginationController$1 extends PaginationController {
34630
+ async getRequest(queryParams, token) {
34631
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
34632
+ const options = token ? { token } : { limit };
34633
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
34634
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
34635
+ });
34636
+ return queryResponse;
34584
34637
  }
34585
- return { data: communities, cachedAt, paging };
34586
- };
34638
+ }
34639
+
34640
+ class CommunitiesQueryStreamController$1 extends QueryStreamController {
34641
+ constructor(query, cacheKey, notifyChange, preparePayload) {
34642
+ super(query, cacheKey);
34643
+ this.notifyChange = notifyChange;
34644
+ this.preparePayload = preparePayload;
34645
+ }
34646
+ async saveToMainDB(response) {
34647
+ const processedPayload = await this.preparePayload(response);
34648
+ const client = getActiveClient();
34649
+ const cachedAt = client.cache && Date.now();
34650
+ if (client.cache) {
34651
+ ingestInCache(processedPayload, { cachedAt });
34652
+ }
34653
+ }
34654
+ appendToQueryStream(response, direction, refresh = false) {
34655
+ var _a, _b;
34656
+ if (refresh) {
34657
+ pushToCache(this.cacheKey, {
34658
+ data: response.communities.map(getResolver('community')),
34659
+ });
34660
+ }
34661
+ else {
34662
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34663
+ const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
34664
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
34665
+ }
34666
+ }
34667
+ reactor(action) {
34668
+ return (community) => {
34669
+ var _a;
34670
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34671
+ if (!collection)
34672
+ return;
34673
+ pushToCache(this.cacheKey, collection);
34674
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
34675
+ };
34676
+ }
34677
+ subscribeRTE(createSubscriber) {
34678
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
34679
+ }
34680
+ }
34681
+
34682
+ var EnumCommunityActions$1;
34683
+ (function (EnumCommunityActions) {
34684
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
34685
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
34686
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
34687
+ })(EnumCommunityActions$1 || (EnumCommunityActions$1 = {}));
34688
+
34689
+ /* eslint-disable no-use-before-define */
34690
+ class SearchCommunityLiveCollectionController extends LiveCollectionController {
34691
+ constructor(query, callback) {
34692
+ const queryStreamId = hash(query);
34693
+ const cacheKey = ['community', 'collection', queryStreamId];
34694
+ const paginationController = new CommunitiesPaginationController$1(query);
34695
+ super(paginationController, queryStreamId, cacheKey, callback);
34696
+ this.query = query;
34697
+ this.queryStreamController = new CommunitiesQueryStreamController$1(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
34698
+ this.callback = callback.bind(this);
34699
+ this.loadPage({ initial: true });
34700
+ }
34701
+ setup() {
34702
+ var _a;
34703
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34704
+ if (!collection) {
34705
+ pushToCache(this.cacheKey, {
34706
+ data: [],
34707
+ params: {},
34708
+ });
34709
+ }
34710
+ }
34711
+ async persistModel(queryPayload) {
34712
+ await this.queryStreamController.saveToMainDB(queryPayload);
34713
+ }
34714
+ persistQueryStream({ response, direction, refresh, }) {
34715
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
34716
+ }
34717
+ startSubscription() {
34718
+ return this.queryStreamController.subscribeRTE([
34719
+ { fn: onCommunityDeleted, action: EnumCommunityActions$1.OnCommunityDeleted },
34720
+ { fn: onCommunityUpdated, action: EnumCommunityActions$1.OnCommunityUpdated },
34721
+ ]);
34722
+ }
34723
+ notifyChange({ origin, loading, error }) {
34724
+ var _a, _b;
34725
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34726
+ if (!collection)
34727
+ return;
34728
+ const data = this.applyFilter((_b = collection.data
34729
+ .map(id => pullFromCache(['community', 'get', id]))
34730
+ .filter(Boolean)
34731
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
34732
+ if (!this.shouldNotify(data) && origin === 'event')
34733
+ return;
34734
+ this.callback({
34735
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
34736
+ data,
34737
+ hasNextPage: !!this.paginationController.getNextToken(),
34738
+ loading,
34739
+ error,
34740
+ });
34741
+ }
34742
+ applyFilter(data) {
34743
+ const { userId } = getActiveClient();
34744
+ let communities = data;
34745
+ if (this.query.includeDeleted) {
34746
+ communities = filterByPropEquality(communities, 'isDeleted', false);
34747
+ }
34748
+ if (this.query.categoryId) {
34749
+ communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
34750
+ }
34751
+ if (this.query.tags) {
34752
+ communities = communities.filter(c => { var _a; return (_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = this.query.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
34753
+ }
34754
+ if (this.query.membership && userId) {
34755
+ communities = filterByCommunityMembership(communities, this.query.membership, userId);
34756
+ }
34757
+ return communities;
34758
+ }
34759
+ }
34587
34760
 
34588
34761
  /* begin_public_function
34589
34762
  id: community.query
@@ -34593,7 +34766,7 @@ const queryCommunities = async (query) => {
34593
34766
  * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
34594
34767
  *
34595
34768
  * let communities = []
34596
- * const unsub = CommunityRepository.getCommunities({
34769
+ * const unsub = CommunityRepository.searchCommunities({
34597
34770
  * displayName: Amity.Community['displayName'],
34598
34771
  * }, response => merge(communities, response.data))
34599
34772
  * ```
@@ -34606,99 +34779,215 @@ const queryCommunities = async (query) => {
34606
34779
  *
34607
34780
  * @category Community Live Collection
34608
34781
  */
34609
- const getCommunities = (params, callback, config) => {
34610
- const { log, cache, userId } = getActiveClient();
34782
+ const searchCommunities = (params, callback, config) => {
34783
+ const { log, cache } = getActiveClient();
34611
34784
  if (!cache) {
34612
34785
  console.log(ENABLE_CACHE_MESSAGE);
34613
34786
  }
34614
34787
  const timestamp = Date.now();
34615
- log(`getCommunities(tmpid: ${timestamp}) > listen`);
34616
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
34617
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
34618
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
34619
- const disposers = [];
34620
- const cacheKey = ['community', 'collection', queryParams];
34621
- const responder = (data) => {
34622
- var _a, _b;
34623
- let communities = (_a = data.data
34624
- .map(communityId => pullFromCache(['community', 'get', communityId]))
34625
- .filter(Boolean)
34626
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
34627
- communities = filterByStringComparePartially(communities, 'displayName', params.displayName);
34628
- if (!params.includeDeleted) {
34629
- communities = filterByPropEquality(communities, 'isDeleted', false);
34630
- }
34631
- if (params.categoryId) {
34632
- communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(params.categoryId); });
34633
- }
34634
- if (params.tags) {
34635
- communities = communities.filter(c => { var _a; return (_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = params.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
34636
- }
34637
- if (params.membership && userId) {
34638
- communities = filterByCommunityMembership(communities, params.membership, userId);
34788
+ log(`searchCommunities(tmpid: ${timestamp}) > listen`);
34789
+ const searchCommunitiesLiveCollection = new SearchCommunityLiveCollectionController(params, callback);
34790
+ const disposers = searchCommunitiesLiveCollection.startSubscription();
34791
+ const cacheKey = searchCommunitiesLiveCollection.getCacheKey();
34792
+ disposers.push(() => dropFromCache(cacheKey));
34793
+ return () => {
34794
+ log(`searchCommunities(tmpid: ${timestamp}) > dispose`);
34795
+ disposers.forEach(fn => fn());
34796
+ };
34797
+ };
34798
+ /* end_public_function */
34799
+
34800
+ /**
34801
+ * TODO: handle cache receive cache option, and cache policy
34802
+ * TODO: check if querybyIds is supported
34803
+ */
34804
+ class CommunitiesPaginationController extends PaginationController {
34805
+ async getRequest(queryParams, token) {
34806
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
34807
+ const options = token ? { token } : { limit };
34808
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
34809
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
34810
+ });
34811
+ return queryResponse;
34812
+ }
34813
+ }
34814
+
34815
+ var EnumCommunityActions;
34816
+ (function (EnumCommunityActions) {
34817
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
34818
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
34819
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
34820
+ })(EnumCommunityActions || (EnumCommunityActions = {}));
34821
+
34822
+ class CommunitiesQueryStreamController extends QueryStreamController {
34823
+ constructor(query, cacheKey, notifyChange, preparePayload) {
34824
+ super(query, cacheKey);
34825
+ this.notifyChange = notifyChange;
34826
+ this.preparePayload = preparePayload;
34827
+ }
34828
+ async saveToMainDB(response) {
34829
+ const processedPayload = await this.preparePayload(response);
34830
+ const client = getActiveClient();
34831
+ const cachedAt = client.cache && Date.now();
34832
+ if (client.cache) {
34833
+ ingestInCache(processedPayload, { cachedAt });
34834
+ saveCommunityUsers(response.communities, response.communityUsers);
34639
34835
  }
34640
- const sortBy = params.sortBy || 'lastCreated';
34641
- if (sortBy === 'lastCreated' || sortBy === 'firstCreated') {
34642
- communities = communities.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
34836
+ }
34837
+ appendToQueryStream(response, direction, refresh = false) {
34838
+ var _a, _b;
34839
+ if (refresh) {
34840
+ pushToCache(this.cacheKey, {
34841
+ data: response.communities.map(getResolver('community')),
34842
+ });
34643
34843
  }
34644
- /*
34645
- * The server returns communities with empty | null displayName's first before
34646
- * returning sorted list of communities with displayNames
34647
- *
34648
- * This section needs to be updated as displayNames can be null as well
34649
- */
34650
- if (sortBy === 'displayName') {
34651
- communities = communities
34652
- // this needs to be aligned with the backend data type
34653
- .map(c => (c.displayName ? c : Object.assign(Object.assign({}, c), { displayName: '' })))
34654
- // @ts-ignore
34655
- .sort(sortByDisplayName);
34844
+ else {
34845
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34846
+ const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
34847
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
34656
34848
  }
34657
- callback({
34658
- onNextPage: onFetch,
34659
- data: communities,
34660
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
34661
- loading: data.loading,
34662
- error: data.error,
34663
- });
34664
- };
34665
- const realtimeRouter = (_) => (community) => {
34849
+ }
34850
+ reactor(action) {
34851
+ return (community) => {
34852
+ var _a;
34853
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34854
+ if (!collection)
34855
+ return;
34856
+ if (this.query.displayName && action === EnumCommunityActions.OnCommunityCreated) {
34857
+ return;
34858
+ }
34859
+ /*
34860
+ * Simply update a collection and let responder decide what to do with data
34861
+ */
34862
+ collection.data = [...new Set([community.communityId, ...collection.data])];
34863
+ pushToCache(this.cacheKey, collection);
34864
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
34865
+ };
34866
+ }
34867
+ subscribeRTE(createSubscriber) {
34868
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
34869
+ }
34870
+ }
34871
+
34872
+ /* eslint-disable no-use-before-define */
34873
+ class CommunityLiveCollectionController extends LiveCollectionController {
34874
+ constructor(query, callback) {
34875
+ const queryStreamId = hash(query);
34876
+ const cacheKey = ['community', 'collection', queryStreamId];
34877
+ const paginationController = new CommunitiesPaginationController(query);
34878
+ super(paginationController, queryStreamId, cacheKey, callback);
34879
+ this.query = query;
34880
+ this.queryStreamController = new CommunitiesQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
34881
+ this.callback = callback.bind(this);
34882
+ this.loadPage({ initial: true });
34883
+ }
34884
+ setup() {
34666
34885
  var _a;
34667
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34886
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34887
+ if (!collection) {
34888
+ pushToCache(this.cacheKey, {
34889
+ data: [],
34890
+ params: {},
34891
+ });
34892
+ }
34893
+ }
34894
+ async persistModel(queryPayload) {
34895
+ await this.queryStreamController.saveToMainDB(queryPayload);
34896
+ }
34897
+ persistQueryStream({ response, direction, refresh, }) {
34898
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
34899
+ }
34900
+ startSubscription() {
34901
+ return this.queryStreamController.subscribeRTE([
34902
+ { fn: onCommunityCreated, action: EnumCommunityActions.OnCommunityCreated },
34903
+ { fn: onCommunityDeleted, action: EnumCommunityActions.OnCommunityDeleted },
34904
+ { fn: onCommunityUpdated, action: EnumCommunityActions.OnCommunityUpdated },
34905
+ ]);
34906
+ }
34907
+ notifyChange({ origin, loading, error }) {
34908
+ var _a, _b;
34909
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34668
34910
  if (!collection)
34669
34911
  return;
34670
- /*
34671
- * Simply update collection and let responder decide what to do with data
34672
- */
34673
- collection.data = [...new Set([community.communityId, ...collection.data])];
34674
- pushToCache(cacheKey, collection);
34675
- responder(collection);
34676
- };
34677
- const onFetch = (initial = false) => {
34678
- var _a, _b;
34679
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34680
- const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
34681
- if (!initial && communities.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
34912
+ const data = this.applyFilter((_b = collection.data
34913
+ .map(id => pullFromCache(['community', 'get', id]))
34914
+ .filter(Boolean)
34915
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
34916
+ if (!this.shouldNotify(data) && origin === 'event')
34682
34917
  return;
34683
- const query = createQuery(queryCommunities, Object.assign(Object.assign({}, queryParams), { limit: initial ? limit : undefined, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
34684
- runQuery(query, ({ data: result, error, loading, paging }) => {
34685
- const data = {
34686
- loading,
34687
- error,
34688
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
34689
- data: communities,
34690
- };
34691
- if (result) {
34692
- data.data = initial
34693
- ? result.map(getResolver('community'))
34694
- : [...new Set([...communities, ...result.map(getResolver('community'))])];
34695
- }
34696
- pushToCache(cacheKey, data);
34697
- responder(data);
34698
- }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
34699
- };
34700
- disposers.push(onCommunityCreated(realtimeRouter()), onCommunityDeleted(realtimeRouter()), onCommunityUpdated(realtimeRouter()), onCommunityJoined(realtimeRouter()), onCommunityLeft(realtimeRouter()), onCommunityUserChanged(realtimeRouter()));
34701
- onFetch(true);
34918
+ this.callback({
34919
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
34920
+ data,
34921
+ hasNextPage: !!this.paginationController.getNextToken(),
34922
+ loading,
34923
+ error,
34924
+ });
34925
+ }
34926
+ applyFilter(data) {
34927
+ const { userId } = getActiveClient();
34928
+ let communities = data;
34929
+ if (this.query.includeDeleted) {
34930
+ communities = filterByPropEquality(communities, 'isDeleted', false);
34931
+ }
34932
+ if (this.query.categoryId) {
34933
+ communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
34934
+ }
34935
+ if (this.query.tags) {
34936
+ communities = communities.filter(c => { var _a; return (_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = this.query.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
34937
+ }
34938
+ if (this.query.membership && userId) {
34939
+ communities = filterByCommunityMembership(communities, this.query.membership, userId);
34940
+ }
34941
+ if (!this.query.displayName) {
34942
+ const sortFn = (() => {
34943
+ switch (this.query.sortBy) {
34944
+ case 'firstCreated':
34945
+ return sortByFirstCreated;
34946
+ case 'lastCreated':
34947
+ return sortByLastCreated;
34948
+ case 'displayName':
34949
+ return sortByDisplayName;
34950
+ default:
34951
+ return sortByLastCreated;
34952
+ }
34953
+ })();
34954
+ communities = communities.sort(sortFn);
34955
+ }
34956
+ return communities;
34957
+ }
34958
+ }
34959
+
34960
+ /* begin_public_function
34961
+ id: community.query
34962
+ */
34963
+ /**
34964
+ * ```js
34965
+ * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
34966
+ *
34967
+ * let communities = []
34968
+ * const unsub = CommunityRepository.getCommunities({
34969
+ * displayName: Amity.Community['displayName'],
34970
+ * }, response => merge(communities, response.data))
34971
+ * ```
34972
+ *
34973
+ * Observe all mutations on a list of {@link Amity.Community}s
34974
+ *
34975
+ * @param params for querying communities
34976
+ * @param callback the function to call when new data are available
34977
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the communities
34978
+ *
34979
+ * @category Community Live Collection
34980
+ */
34981
+ const getCommunities = (params, callback, config) => {
34982
+ const { log, cache } = getActiveClient();
34983
+ if (!cache) {
34984
+ console.log(ENABLE_CACHE_MESSAGE);
34985
+ }
34986
+ const timestamp = Date.now();
34987
+ log(`getCommunities(tmpid: ${timestamp}) > listen`);
34988
+ const communitiesLiveCollection = new CommunityLiveCollectionController(params, callback);
34989
+ const disposers = communitiesLiveCollection.startSubscription();
34990
+ const cacheKey = communitiesLiveCollection.getCacheKey();
34702
34991
  disposers.push(() => dropFromCache(cacheKey));
34703
34992
  return () => {
34704
34993
  log(`getCommunities(tmpid: ${timestamp}) > dispose`);
@@ -35227,208 +35516,238 @@ const removeMembers = async (communityId, userIds) => {
35227
35516
  /* end_public_function */
35228
35517
 
35229
35518
  /**
35230
- * ```js
35231
- * import { queryCommunityMembers } from '@amityco/ts-sdk-react-native'
35232
- * const communityMembers = await queryCommunityMembers({ communityId: 'foo' })
35233
- * ```
35234
- *
35235
- * Queries a paginable list of {@link Amity.CommunityUser} objects
35236
- *
35237
- * @param query The query parameters
35238
- * @returns A page of {@link Amity.CommunityUser} objects
35239
- *
35240
- * @category Community API
35241
- * @async
35242
- * */
35243
- const queryCommunityMembers = async (query) => {
35244
- const client = getActiveClient();
35245
- client.log('community/queryCommunityMembers', query);
35246
- const _a = query !== null && query !== void 0 ? query : {}, { page, limit } = _a, params = __rest(_a, ["page", "limit"]);
35247
- const options = (() => {
35248
- if (page)
35249
- return { token: page };
35250
- if (limit)
35251
- return { limit };
35252
- return undefined;
35253
- })();
35254
- const { data: queryPayload } = await client.http.get(`/api/v3/communities/${params.communityId}/users`, {
35255
- params: Object.assign(Object.assign({}, params), { options }),
35256
- });
35257
- const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
35258
- const preparedPayload = prepareMembershipPayload(payload, 'communityUsers');
35259
- const { communityUsers } = preparedPayload;
35260
- const cachedAt = client.cache && Date.now();
35261
- if (client.cache) {
35262
- ingestInCache(preparedPayload, { cachedAt });
35263
- const cacheKey = ['communityUsers', 'query', Object.assign(Object.assign({}, params), { options })];
35264
- pushToCache(cacheKey, {
35265
- communityUsers: communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
35266
- paging,
35267
- });
35268
- }
35269
- return { data: communityUsers, cachedAt, paging };
35270
- };
35271
- /**
35272
- * ```js
35273
- * import { queryCommunityMembers } from '@amityco/ts-sdk-react-native'
35274
- * const communityMembers = await queryCommunityMembers(query)
35275
- * ```
35276
- *
35277
- * Queries a paginable list of {@link Amity.InternalPost} objects from cache
35278
- *
35279
- * @param query The query parameters
35280
- * @returns posts
35281
- *
35282
- * @category Post API
35283
- */
35284
- queryCommunityMembers.locally = (query) => {
35285
- var _a, _b;
35286
- const client = getActiveClient();
35287
- client.log('community/queryCommunityMembers', query);
35288
- if (!client.cache)
35289
- return;
35290
- const _c = query !== null && query !== void 0 ? query : {}, { page, limit } = _c, params = __rest(_c, ["page", "limit"]);
35291
- const options = (() => {
35292
- if (page)
35293
- return { token: page };
35294
- if (limit)
35295
- return { limit };
35296
- return undefined;
35297
- })();
35298
- const cacheKey = ['communityUsers', 'query', Object.assign(Object.assign({}, params), { options })];
35299
- const { data, cachedAt } = (_a = pullFromCache(cacheKey)) !== null && _a !== void 0 ? _a : {};
35300
- if (!(data === null || data === void 0 ? void 0 : data.communityUsers.length))
35301
- return;
35302
- const communityUsers = data.communityUsers
35303
- .map(key => pullFromCache(['communityUsers', 'get', key]))
35304
- .filter(Boolean)
35305
- .map(({ data }) => data);
35306
- const { paging } = data;
35307
- return communityUsers.length === ((_b = data === null || data === void 0 ? void 0 : data.communityUsers) === null || _b === void 0 ? void 0 : _b.length)
35308
- ? { data: communityUsers, cachedAt, paging }
35309
- : undefined;
35310
- };
35311
-
35312
- /*
35313
- * Exported for testing
35314
- * @hidden
35519
+ * TODO: handle cache receive cache option, and cache policy
35520
+ * TODO: check if querybyIds is supported
35315
35521
  */
35316
- const applyFilter = (data, params) => {
35317
- let communityMembers = filterByPropIntersection(data, 'roles', params.roles);
35318
- if (params.memberships) {
35319
- communityMembers = communityMembers.filter(({ communityMembership }) => {
35320
- const membership = params.memberships;
35321
- return membership.includes(communityMembership);
35522
+ class CommunityMembersPaginationController extends PaginationController {
35523
+ async getRequest(queryParams, token) {
35524
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
35525
+ const options = token ? { token } : { limit };
35526
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
35527
+ params: Object.assign(Object.assign({}, params), { options }),
35322
35528
  });
35529
+ return queryResponse;
35323
35530
  }
35324
- if (params.search) {
35325
- communityMembers = filterBySearchTerm(communityMembers, params.search);
35531
+ }
35532
+
35533
+ class CommunityMembersQueryStreamController extends QueryStreamController {
35534
+ constructor(query, cacheKey, notifyChange, preparePayload) {
35535
+ super(query, cacheKey);
35536
+ this.notifyChange = notifyChange;
35537
+ this.preparePayload = preparePayload;
35326
35538
  }
35327
- const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
35328
- communityMembers = communityMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
35329
- return communityMembers;
35330
- };
35331
- /* begin_public_function
35332
- id: community.membership.query
35333
- */
35334
- /**
35335
- * ```js
35336
- * import { getMembers } from '@amityco/ts-sdk-react-native'
35337
- *
35338
- * let communityMembers = []
35339
- * const unsub = getMembers({
35340
- * communityId: Amity.Community['communityId'],
35341
- * }, response => merge(communityMembers, response.data))
35342
- * ```
35343
- *
35344
- * Observe all mutations on a list of {@link Amity.CommunityUser}s
35345
- *
35346
- * @param params for querying community users
35347
- * @param callback the function to call when new data are available
35348
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community users
35349
- *
35350
- * @category Community Live Collection
35351
- */
35352
- const getMembers = (params, callback, config) => {
35353
- const { log, cache } = getActiveClient();
35354
- if (!cache) {
35355
- console.log(ENABLE_CACHE_MESSAGE);
35539
+ async saveToMainDB(response) {
35540
+ const processedPayload = await this.preparePayload(response);
35541
+ const client = getActiveClient();
35542
+ const cachedAt = client.cache && Date.now();
35543
+ if (client.cache) {
35544
+ ingestInCache(processedPayload, { cachedAt });
35545
+ }
35356
35546
  }
35357
- const timestamp = Date.now();
35358
- log(`getMembers(tmpid: ${timestamp}) > listen`);
35359
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
35360
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
35361
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
35362
- const disposers = [];
35363
- const cacheKey = ['communityUsers', 'collection', queryParams];
35364
- const cacheByCommunityIdKey = [
35365
- 'communityUsers',
35366
- 'collection',
35367
- { communityId: params.communityId },
35368
- ];
35369
- const responder = (data, isEventModel = false) => {
35547
+ appendToQueryStream(response, direction, refresh = false) {
35370
35548
  var _a, _b;
35371
- const communityMembers = (_a = data.data
35372
- .map(id => pullFromCache(['communityUsers', 'get', id]))
35373
- .filter(Boolean)
35374
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
35375
- callback({
35376
- onNextPage: onFetch,
35377
- data: isEventModel ? applyFilter(communityMembers, params) : communityMembers,
35378
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
35379
- loading: data.loading,
35380
- error: data.error,
35381
- });
35382
- };
35383
- const realtimeRouter = (_) => (_, communityMembers) => {
35384
- var _a;
35385
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35386
- if (!collection) {
35387
- return;
35549
+ if (refresh) {
35550
+ pushToCache(this.cacheKey, {
35551
+ data: response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
35552
+ });
35553
+ }
35554
+ else {
35555
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35556
+ const communityUsers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
35557
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
35558
+ ...new Set([
35559
+ ...communityUsers,
35560
+ ...response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
35561
+ ]),
35562
+ ] }));
35388
35563
  }
35389
- const communityMemberCacheIds = communityMembers
35390
- .map(communityMember => {
35391
- if (params.communityId !== communityMember.communityId) {
35564
+ }
35565
+ reactor(action) {
35566
+ return (community, communityMembers) => {
35567
+ var _a;
35568
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35569
+ if (!collection)
35392
35570
  return;
35393
- }
35394
- const communityMemberCacheId = getResolver('communityUsers')({
35395
- communityId: params.communityId,
35396
- userId: communityMember.userId,
35571
+ communityMembers.forEach(communityMember => {
35572
+ const communityMemberCacheId = getResolver('communityUsers')({
35573
+ communityId: this.query.communityId,
35574
+ userId: communityMember.userId,
35575
+ });
35576
+ if (communityMember.communityMembership === 'none') {
35577
+ collection.data = collection.data.filter(m => m !== communityMemberCacheId);
35578
+ }
35579
+ else if (!collection.data.includes(communityMemberCacheId)) {
35580
+ collection.data = [communityMemberCacheId, ...collection.data];
35581
+ }
35397
35582
  });
35398
- return communityMemberCacheId;
35399
- })
35400
- .filter(isNonNullable);
35401
- collection.data = [...new Set([...communityMemberCacheIds, ...collection.data])];
35402
- pushToCache(cacheKey, collection);
35403
- pushToCache(cacheByCommunityIdKey, collection);
35404
- responder(collection, true);
35405
- };
35406
- const onFetch = (initial = false) => {
35583
+ pushToCache(this.cacheKey, collection);
35584
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
35585
+ };
35586
+ }
35587
+ subscribeRTE(createSubscriber) {
35588
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
35589
+ }
35590
+ }
35591
+
35592
+ var EnumCommunityMemberActions;
35593
+ (function (EnumCommunityMemberActions) {
35594
+ EnumCommunityMemberActions["OnCommunityJoined"] = "onCommunityJoined";
35595
+ EnumCommunityMemberActions["OnCommunityLeft"] = "onCommunityLeft";
35596
+ EnumCommunityMemberActions["OnCommunityUserBanned"] = "onCommunityUserBanned";
35597
+ EnumCommunityMemberActions["OnCommunityUserChanged"] = "onCommunityUserChanged";
35598
+ EnumCommunityMemberActions["OnCommunityUserRoleAdded"] = "onCommunityUserRoleAdded";
35599
+ EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
35600
+ EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
35601
+ })(EnumCommunityMemberActions || (EnumCommunityMemberActions = {}));
35602
+
35603
+ /* eslint-disable no-use-before-define */
35604
+ class CommunityMembersLiveCollectionController extends LiveCollectionController {
35605
+ constructor(query, callback) {
35606
+ const queryStreamId = hash(query);
35607
+ const cacheKey = ['communityUsers', 'collection', queryStreamId];
35608
+ const paginationController = new CommunityMembersPaginationController(query);
35609
+ super(paginationController, queryStreamId, cacheKey, callback);
35610
+ this.query = query;
35611
+ this.queryStreamController = new CommunityMembersQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
35612
+ this.callback = callback.bind(this);
35613
+ this.loadPage({ initial: true });
35614
+ }
35615
+ setup() {
35616
+ var _a;
35617
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35618
+ if (!collection) {
35619
+ pushToCache(this.cacheKey, {
35620
+ data: [],
35621
+ params: {},
35622
+ });
35623
+ }
35624
+ }
35625
+ async persistModel(queryPayload) {
35626
+ await this.queryStreamController.saveToMainDB(queryPayload);
35627
+ }
35628
+ persistQueryStream({ response, direction, refresh, }) {
35629
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
35630
+ }
35631
+ startSubscription() {
35632
+ return this.queryStreamController.subscribeRTE([
35633
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions.OnCommunityJoined },
35634
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions.OnCommunityLeft },
35635
+ { fn: onCommunityUserBanned, action: EnumCommunityMemberActions.OnCommunityUserBanned },
35636
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions.OnCommunityUserChanged },
35637
+ { fn: onCommunityUserRoleAdded, action: EnumCommunityMemberActions.OnCommunityUserRoleAdded },
35638
+ {
35639
+ fn: onCommunityUserRoleRemoved,
35640
+ action: EnumCommunityMemberActions.OnCommunityUserRoleRemoved,
35641
+ },
35642
+ { fn: onCommunityUserUnbanned, action: EnumCommunityMemberActions.OnCommunityUserUnbanned },
35643
+ ]);
35644
+ }
35645
+ notifyChange({ origin, loading, error }) {
35407
35646
  var _a, _b;
35408
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35409
- const communityMembers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
35410
- if (!initial && communityMembers.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
35647
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35648
+ if (!collection)
35411
35649
  return;
35412
- const query = createQuery(queryCommunityMembers, Object.assign(Object.assign({}, queryParams), { limit: initial ? limit : undefined, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
35413
- runQuery(query, ({ data: result, error, loading, paging }) => {
35414
- const data = {
35415
- loading,
35416
- error,
35417
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
35418
- data: communityMembers,
35419
- };
35420
- if (result) {
35421
- data.data = [
35422
- ...new Set([...communityMembers, ...result.map(getResolver('communityUsers'))]),
35423
- ];
35424
- }
35425
- pushToCache(cacheKey, data);
35426
- pushToCache(cacheByCommunityIdKey, data);
35427
- responder(data);
35428
- }, queryOptions(policy));
35429
- };
35430
- disposers.push(onCommunityLeft(realtimeRouter()), onCommunityJoined(realtimeRouter()), onCommunityUserBanned(realtimeRouter()), onCommunityUserUnbanned(realtimeRouter()), onCommunityUserChanged(realtimeRouter()), onCommunityUserRoleAdded(realtimeRouter()), onCommunityUserRoleRemoved(realtimeRouter()));
35431
- onFetch(true);
35650
+ const data = this.applyFilter((_b = collection.data
35651
+ .map(id => pullFromCache(['communityUsers', 'get', id]))
35652
+ .filter(isNonNullable)
35653
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
35654
+ if (!this.shouldNotify(data) && origin === 'event')
35655
+ return;
35656
+ this.callback({
35657
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
35658
+ data,
35659
+ hasNextPage: !!this.paginationController.getNextToken(),
35660
+ loading,
35661
+ error,
35662
+ });
35663
+ }
35664
+ applyFilter(data) {
35665
+ let communityMembers = filterByPropIntersection(data, 'roles', this.query.roles);
35666
+ if (this.query.memberships) {
35667
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
35668
+ const memberships = this.query.memberships || [];
35669
+ return memberships.includes(communityMembership);
35670
+ });
35671
+ }
35672
+ if (this.query.search) {
35673
+ communityMembers = filterBySearchTerm(communityMembers, this.query.search);
35674
+ }
35675
+ const sortBy = this.query.sortBy ? this.query.sortBy : 'lastCreated';
35676
+ switch (sortBy) {
35677
+ case 'lastCreated':
35678
+ communityMembers = communityMembers.sort(sortByLastCreated);
35679
+ break;
35680
+ case 'firstCreated':
35681
+ communityMembers = communityMembers.sort(sortByFirstCreated);
35682
+ break;
35683
+ case 'displayName':
35684
+ communityMembers = communityMembers.sort((memberA, memberB) => {
35685
+ if (!memberA.user || !memberB.user)
35686
+ return 0;
35687
+ return sortByDisplayName(memberA.user, memberB.user);
35688
+ });
35689
+ break;
35690
+ }
35691
+ return communityMembers;
35692
+ }
35693
+ }
35694
+
35695
+ /*
35696
+ * Exported for testing
35697
+ * @hidden
35698
+ */
35699
+ const applyFilter = (data, params) => {
35700
+ let communityMembers = filterByPropIntersection(data, 'roles', params.roles);
35701
+ if (params.memberships) {
35702
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
35703
+ const membership = params.memberships;
35704
+ return membership.includes(communityMembership);
35705
+ });
35706
+ }
35707
+ if (params.search) {
35708
+ communityMembers = filterBySearchTerm(communityMembers, params.search);
35709
+ }
35710
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
35711
+ communityMembers = communityMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
35712
+ return communityMembers;
35713
+ };
35714
+ /* begin_public_function
35715
+ id: community.membership.query
35716
+ */
35717
+ /**
35718
+ * ```js
35719
+ * import { getMembers } from '@amityco/ts-sdk-react-native'
35720
+ *
35721
+ * let communityMembers = []
35722
+ * const unsub = getMembers({
35723
+ * communityId: Amity.Community['communityId'],
35724
+ * }, response => merge(communityMembers, response.data))
35725
+ * ```
35726
+ *
35727
+ * Observe all mutations on a list of {@link Amity.CommunityUser}s
35728
+ *
35729
+ * @param params for querying community users
35730
+ * @param callback the function to call when new data are available
35731
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community users
35732
+ *
35733
+ * @category Community Live Collection
35734
+ */
35735
+ const getMembers = (params, callback, config) => {
35736
+ const { log, cache } = getActiveClient();
35737
+ if (!cache) {
35738
+ console.log(ENABLE_CACHE_MESSAGE);
35739
+ }
35740
+ const timestamp = Date.now();
35741
+ log(`getMembers(tmpid: ${timestamp}) > listen`);
35742
+ const communityMemberLiveCollection = new CommunityMembersLiveCollectionController(params, resp => {
35743
+ console.log('resp', resp);
35744
+ callback(resp);
35745
+ });
35746
+ const disposers = communityMemberLiveCollection.startSubscription();
35747
+ const cacheKey = communityMemberLiveCollection.getCacheKey();
35748
+ disposers.push(() => {
35749
+ dropFromCache(cacheKey);
35750
+ });
35432
35751
  return () => {
35433
35752
  log(`getMembers(tmpid: ${timestamp}) > dispose`);
35434
35753
  disposers.forEach(fn => fn());
@@ -35468,6 +35787,7 @@ var index$8 = /*#__PURE__*/Object.freeze({
35468
35787
  onCommunityUpdated: onCommunityUpdated,
35469
35788
  onCommunityDeleted: onCommunityDeleted,
35470
35789
  observeCommunity: observeCommunity,
35790
+ searchCommunities: searchCommunities,
35471
35791
  getCommunities: getCommunities,
35472
35792
  getCommunity: getCommunity,
35473
35793
  getTrendingCommunities: getTrendingCommunities,
@@ -36054,7 +36374,7 @@ const updatePost = async (postId, patch) => {
36054
36374
  const cachedAt = client.cache && Date.now();
36055
36375
  if (client.cache)
36056
36376
  ingestInCache(data, { cachedAt });
36057
- fireEvent('post.updated', data);
36377
+ fireEvent('local.post.updated', data);
36058
36378
  const { posts } = data;
36059
36379
  return {
36060
36380
  data: LinkedObject.post(posts.find(post => post.postId === postId)),
@@ -36091,7 +36411,7 @@ const editPost = async (postId, patch) => {
36091
36411
  const cachedAt = client.cache && Date.now();
36092
36412
  if (client.cache)
36093
36413
  ingestInCache(data, { cachedAt });
36094
- fireEvent('post.updated', data);
36414
+ fireEvent('local.post.updated', data);
36095
36415
  const { posts } = data;
36096
36416
  return {
36097
36417
  data: LinkedObject.post(posts.find(post => post.postId === postId)),
@@ -36465,347 +36785,63 @@ const observePost = (postId, callback, policy = 'cache_then_server') => {
36465
36785
  };
36466
36786
 
36467
36787
  /* begin_public_function
36468
- id: post.get
36788
+ id: comment.get_by_ids
36469
36789
  */
36470
36790
  /**
36471
36791
  * ```js
36472
- * import { PostRepository } from '@amityco/ts-sdk-react-native';
36792
+ * import { CommentRepository } from '@amityco/ts-sdk-react-native'
36793
+ * const comments = await CommentRepository.getCommentByIds(['foo', 'bar'])
36794
+ * ```
36473
36795
  *
36474
- * let post;
36796
+ * Fetches a collection of {@link Amity.Comment} objects
36475
36797
  *
36476
- * const unsub = PostRepository.getPost(postId, response => {
36477
- * post = response.data;
36478
- * });
36798
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
36799
+ * @returns the associated collection of {@link Amity.Comment} objects
36800
+ *
36801
+ * @category Comment API
36802
+ * @async
36803
+ */
36804
+ const getCommentByIds = async (commentIds) => {
36805
+ const client = getActiveClient();
36806
+ client.log('comment/getCommentByIds', commentIds);
36807
+ const encodedCommentIds = commentIds.map(commentId => encodeURIComponent(commentId));
36808
+ let data;
36809
+ try {
36810
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
36811
+ const response = await client.http.get(`/api/v3/comments/list`, {
36812
+ params: { commentIds: encodedCommentIds },
36813
+ });
36814
+ data = response.data;
36815
+ }
36816
+ catch (error) {
36817
+ commentIds.forEach(commentId => {
36818
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
36819
+ pushToTombstone('comment', commentId);
36820
+ }
36821
+ });
36822
+ throw error;
36823
+ }
36824
+ const cachedAt = client.cache && Date.now();
36825
+ if (client.cache)
36826
+ ingestInCache(data, { cachedAt });
36827
+ return {
36828
+ data: data.comments.map(comment => LinkedObject.comment(comment)),
36829
+ cachedAt,
36830
+ };
36831
+ };
36832
+ /* end_public_function */
36833
+ /**
36834
+ * ```js
36835
+ * import { getCommentByIds } from '@amityco/ts-sdk-react-native'
36836
+ * const comments = getCommentByIds.locally(['foo', 'bar'])
36479
36837
  * ```
36480
36838
  *
36481
- * Observe all mutation on a given {@link Amity.Post}
36839
+ * Fetches a collection of {@link Amity.Comment} objects from cache
36482
36840
  *
36483
- * @param postId the ID of the message to observe
36484
- * @param callback the function to call when new data are available
36485
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the sub channel
36841
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
36842
+ * @returns the associated collection of {@link Amity.Comment} objects
36486
36843
  *
36487
- * @category Post Live Object
36488
- */
36489
- const getPost = (postId, callback) => {
36490
- return liveObject(postId, callback, 'postId', getPost$1, [
36491
- onPostApproved,
36492
- onPostDeclined,
36493
- (callback) => {
36494
- return onPostDeleted((post) => {
36495
- var _a;
36496
- let targetPost = post;
36497
- // check if the deleted post is a child of the target post
36498
- if (post.parentPostId === postId && post.isDeleted) {
36499
- const parentPost = (_a = pullFromCache([
36500
- 'post',
36501
- 'get',
36502
- post.parentPostId,
36503
- ])) === null || _a === void 0 ? void 0 : _a.data;
36504
- if (parentPost) {
36505
- parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
36506
- pushToCache(['post', 'get', parentPost.postId], parentPost);
36507
- // if the deleted post is a child of the target post, then the target post is the parent post
36508
- targetPost = parentPost;
36509
- }
36510
- }
36511
- callback(targetPost);
36512
- });
36513
- },
36514
- onPostFlagged,
36515
- (callback) => {
36516
- return onPostReactionAdded((post) => {
36517
- callback(LinkedObject.post(post));
36518
- });
36519
- },
36520
- (callback) => {
36521
- return onPostReactionRemoved((post) => {
36522
- callback(LinkedObject.post(post));
36523
- });
36524
- },
36525
- onPostUnflagged,
36526
- onPostUpdated,
36527
- ]);
36528
- };
36529
- /* end_public_function */
36530
-
36531
- /**
36532
- * ```js
36533
- * import { queryPosts } from '@amityco/ts-sdk-react-native'
36534
- * const { data: posts, prevPage, nextPage } = await queryPosts({ targetId, targetType })
36535
- * ```
36536
- *
36537
- * Queries a paginable list of {@link Amity.Post} objects
36538
- *
36539
- * @param query The query parameters
36540
- * @returns posts
36541
- *
36542
- * @category Post API
36543
- * @async
36544
- */
36545
- const queryPosts = async (query) => {
36546
- const client = getActiveClient();
36547
- client.log('post/queryPosts', query);
36548
- const { page, limit = 10, includeDeleted } = query, params = __rest(query, ["page", "limit", "includeDeleted"]);
36549
- const { dataTypes, matchingOnlyParentPost } = params;
36550
- const options = (() => {
36551
- if (page)
36552
- return { token: page };
36553
- if (limit)
36554
- return { limit };
36555
- return undefined;
36556
- })();
36557
- // API-FIX: parameters should be querystring. (1)
36558
- // API-FIX: backend should answer Amity.Response (2)
36559
- // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.PostPayload>>>(
36560
- const { data } = await client.http.get(`/api/v4/posts`, {
36561
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted),
36562
- /*
36563
- * when creating post like image, file, video BE will create 2 posts
36564
- * 1. parent post to store text with dataType=text
36565
- * 2. child post to store dataTypes post data
36566
- *
36567
- * By default, BE queries only parent post
36568
- */
36569
- matchingOnlyParentPost: matchingOnlyParentPost !== null && matchingOnlyParentPost !== void 0 ? matchingOnlyParentPost : !(dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length), options }),
36570
- });
36571
- // API-FIX: backend should answer Amity.Response (2)
36572
- // const { paging, posts } = unwrapPayload(data)
36573
- // unpacking
36574
- const { paging } = data, payload = __rest(data, ["paging"]);
36575
- const paperedPayload = prepareMembershipPayload(payload, 'communityUsers');
36576
- const { posts } = payload;
36577
- const cachedAt = client.cache && Date.now();
36578
- if (client.cache) {
36579
- ingestInCache(paperedPayload, { cachedAt });
36580
- const cacheKey = ['post', 'query', Object.assign(Object.assign({}, params), { options })];
36581
- pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
36582
- }
36583
- return { data: posts.map(LinkedObject.post), cachedAt, paging };
36584
- };
36585
-
36586
- /* begin_public_function
36587
- id: post.query
36588
- */
36589
- /**
36590
- * ```js
36591
- * import { PostRepository } from '@amityco/ts-sdk-react-native'
36592
- *
36593
- * let posts = []
36594
- * const unsub = PostRepository.getPosts({
36595
- * targetType: Amity.PostTargetType,
36596
- * targetId: Amity.Post['targetId'],
36597
- * }, response => merge(posts, response.data))
36598
- * ```
36599
- *
36600
- * Observe all mutations on a list of {@link Amity.Post} for a given target object
36601
- *
36602
- * @param params.targetType the type of the target
36603
- * @param params.targetId the ID of the target
36604
- * @param callback the function to call when new data are available
36605
- * @param config
36606
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
36607
- *
36608
- * @category Posts Live Collection
36609
- */
36610
- const getPosts = (params, callback, config) => {
36611
- const { log, cache } = getActiveClient();
36612
- if (!cache) {
36613
- console.log(ENABLE_CACHE_MESSAGE);
36614
- }
36615
- const timestamp = Date.now();
36616
- log(`getPosts(tmpid: ${timestamp}) > listen`);
36617
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
36618
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
36619
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
36620
- const disposers = [];
36621
- const cacheKey = [
36622
- 'post',
36623
- 'collection',
36624
- { targetId: params.targetId, targetType: params.targetType },
36625
- ];
36626
- const responder = (data) => {
36627
- var _a, _b, _c;
36628
- let posts = (_a = data.data
36629
- .map(postId => pullFromCache(['post', 'get', postId]))
36630
- .filter(Boolean)
36631
- .map(({ data }) => LinkedObject.post(data))) !== null && _a !== void 0 ? _a : [];
36632
- const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
36633
- posts = posts.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
36634
- if (!params.includeDeleted) {
36635
- posts = filterByPropEquality(posts, 'isDeleted', false);
36636
- }
36637
- if (params.tags) {
36638
- posts = posts.filter(p => { var _a; return (_a = p.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = params.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
36639
- }
36640
- if (params.targetType === 'community' && params.feedType) {
36641
- posts = filterByFeedType(posts, params.feedType);
36642
- }
36643
- if ((_b = params.dataTypes) === null || _b === void 0 ? void 0 : _b.length) {
36644
- posts = filterByPostDataTypes(posts, params.dataTypes);
36645
- }
36646
- callback({
36647
- onNextPage: onFetch,
36648
- data: posts,
36649
- hasNextPage: !!((_c = data.params) === null || _c === void 0 ? void 0 : _c.page),
36650
- loading: data.loading,
36651
- error: data.error,
36652
- });
36653
- };
36654
- const realtimeRouter = (action) => (post) => {
36655
- var _a, _b;
36656
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
36657
- if (!collection)
36658
- return;
36659
- if (post.parentPostId && post.isDeleted) {
36660
- const parentPost = (_b = pullFromCache([
36661
- 'post',
36662
- 'get',
36663
- post.parentPostId,
36664
- ])) === null || _b === void 0 ? void 0 : _b.data;
36665
- if (!parentPost || (parentPost === null || parentPost === void 0 ? void 0 : parentPost.targetId) !== params.targetId)
36666
- return;
36667
- parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
36668
- pushToCache(['post', 'get', parentPost.postId], parentPost);
36669
- }
36670
- else {
36671
- if (params.targetId !== post.targetId)
36672
- return;
36673
- if (params.targetType !== post.targetType)
36674
- return;
36675
- }
36676
- /*
36677
- * This is not ideal, but currently this is the only way to update the
36678
- * collection on post declined
36679
- */
36680
- if (action === 'onDeclined') {
36681
- collection.data = collection.data.filter(postId => postId !== post.postId);
36682
- }
36683
- else {
36684
- collection.data = [...new Set([post.postId, ...collection.data])];
36685
- }
36686
- pushToCache(cacheKey, collection);
36687
- responder(collection);
36688
- };
36689
- const onFetch = (initial = false) => {
36690
- var _a, _b, _c;
36691
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
36692
- const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
36693
- if (!initial && posts.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
36694
- return;
36695
- const query = createQuery(queryPosts, Object.assign(Object.assign({}, queryParams), { limit: initial ? limit : undefined, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
36696
- runQuery(query, ({ data: result, error, loading, paging }) => {
36697
- const data = {
36698
- loading,
36699
- error,
36700
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
36701
- data: posts,
36702
- };
36703
- if (result) {
36704
- data.data = initial
36705
- ? result.map(getResolver('post'))
36706
- : [...new Set([...posts, ...result.map(getResolver('post'))])];
36707
- }
36708
- pushToCache(cacheKey, data);
36709
- responder(data);
36710
- }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
36711
- };
36712
- disposers.push(onPostCreated(realtimeRouter('onCreate')), onPostApproved(realtimeRouter('onApproved')), onPostDeclined(realtimeRouter('onDeclined')), onPostDeleted(realtimeRouter('onDelete')), onPostUpdated(realtimeRouter('onUpdate')), onPostFlagged(realtimeRouter('onFlagged')), onPostUnflagged(realtimeRouter('onUnflagged')), onPostReactionAdded(realtimeRouter('onReactionAdded')), onPostReactionRemoved(realtimeRouter('onReactionRemoved')));
36713
- onFetch(true);
36714
- disposers.push(() => dropFromCache(cacheKey));
36715
- return () => {
36716
- log(`getPosts(tmpid: ${timestamp}) > dispose`);
36717
- disposers.forEach(fn => fn());
36718
- };
36719
- };
36720
- /* end_public_function */
36721
-
36722
- var index$5 = /*#__PURE__*/Object.freeze({
36723
- __proto__: null,
36724
- getPostByIds: getPostByIds,
36725
- createPost: createPost,
36726
- updatePost: updatePost,
36727
- editPost: editPost,
36728
- deletePost: deletePost,
36729
- softDeletePost: softDeletePost,
36730
- hardDeletePost: hardDeletePost,
36731
- approvePost: approvePost,
36732
- declinePost: declinePost,
36733
- flagPost: flagPost,
36734
- unflagPost: unflagPost,
36735
- isPostFlaggedByMe: isPostFlaggedByMe,
36736
- onPostCreated: onPostCreated,
36737
- onPostUpdated: onPostUpdated,
36738
- onPostDeleted: onPostDeleted,
36739
- onPostApproved: onPostApproved,
36740
- onPostDeclined: onPostDeclined,
36741
- onPostFlagged: onPostFlagged,
36742
- onPostUnflagged: onPostUnflagged,
36743
- onPostReactionAdded: onPostReactionAdded,
36744
- onPostReactionRemoved: onPostReactionRemoved,
36745
- observePosts: observePosts,
36746
- observePost: observePost,
36747
- getPost: getPost,
36748
- getPosts: getPosts
36749
- });
36750
-
36751
- /* begin_public_function
36752
- id: comment.get_by_ids
36753
- */
36754
- /**
36755
- * ```js
36756
- * import { CommentRepository } from '@amityco/ts-sdk-react-native'
36757
- * const comments = await CommentRepository.getCommentByIds(['foo', 'bar'])
36758
- * ```
36759
- *
36760
- * Fetches a collection of {@link Amity.Comment} objects
36761
- *
36762
- * @param commentIds the IDs of the {@link Amity.Comment} to fetch
36763
- * @returns the associated collection of {@link Amity.Comment} objects
36764
- *
36765
- * @category Comment API
36766
- * @async
36767
- */
36768
- const getCommentByIds = async (commentIds) => {
36769
- const client = getActiveClient();
36770
- client.log('comment/getCommentByIds', commentIds);
36771
- const encodedCommentIds = commentIds.map(commentId => encodeURIComponent(commentId));
36772
- let data;
36773
- try {
36774
- // API-FIX: endpoint should not be /list, parameters should be querystring.
36775
- const response = await client.http.get(`/api/v3/comments/list`, {
36776
- params: { commentIds: encodedCommentIds },
36777
- });
36778
- data = response.data;
36779
- }
36780
- catch (error) {
36781
- commentIds.forEach(commentId => {
36782
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
36783
- pushToTombstone('comment', commentId);
36784
- }
36785
- });
36786
- throw error;
36787
- }
36788
- const cachedAt = client.cache && Date.now();
36789
- if (client.cache)
36790
- ingestInCache(data, { cachedAt });
36791
- return {
36792
- data: data.comments.map(comment => LinkedObject.comment(comment)),
36793
- cachedAt,
36794
- };
36795
- };
36796
- /* end_public_function */
36797
- /**
36798
- * ```js
36799
- * import { getCommentByIds } from '@amityco/ts-sdk-react-native'
36800
- * const comments = getCommentByIds.locally(['foo', 'bar'])
36801
- * ```
36802
- *
36803
- * Fetches a collection of {@link Amity.Comment} objects from cache
36804
- *
36805
- * @param commentIds the IDs of the {@link Amity.Comment} to fetch
36806
- * @returns the associated collection of {@link Amity.Comment} objects
36807
- *
36808
- * @category Comment API
36844
+ * @category Comment API
36809
36845
  */
36810
36846
  getCommentByIds.locally = (commentIds) => {
36811
36847
  var _a;
@@ -36856,7 +36892,7 @@ const createComment = async (bundle) => {
36856
36892
  ingestInCache(data, { cachedAt });
36857
36893
  if (['post', 'content'].includes(bundle.referenceType)) {
36858
36894
  const post = await getPost$1(bundle.referenceId);
36859
- fireEvent('post.updated', {
36895
+ fireEvent('local.post.updated', {
36860
36896
  posts: [post.data],
36861
36897
  categories: [],
36862
36898
  comments: [],
@@ -36894,7 +36930,7 @@ const createComment = async (bundle) => {
36894
36930
  }
36895
36931
  }
36896
36932
  }
36897
- fireEvent('comment.created', data);
36933
+ fireEvent('local.comment.created', data);
36898
36934
  return {
36899
36935
  data: LinkedObject.comment(comments[0]),
36900
36936
  cachedAt,
@@ -37050,8 +37086,7 @@ const deleteComment = async (commentId, permanent = false) => {
37050
37086
  }
37051
37087
  else {
37052
37088
  const post = await getPost$1(comment.data.referenceId);
37053
- // @TODO: Need to separate Local / MQTT later
37054
- fireEvent('post.updated', {
37089
+ fireEvent('local.post.updated', {
37055
37090
  posts: [post.data],
37056
37091
  categories: [],
37057
37092
  comments: [],
@@ -37063,8 +37098,7 @@ const deleteComment = async (commentId, permanent = false) => {
37063
37098
  users: [],
37064
37099
  });
37065
37100
  }
37066
- // @TODO: Need to separate Local / MQTT later
37067
- fireEvent('comment.deleted', {
37101
+ fireEvent('local.comment.deleted', {
37068
37102
  comments: [deleted],
37069
37103
  commentChildren: [],
37070
37104
  files: [],
@@ -37376,125 +37410,421 @@ const getComment = (commentId, callback) => {
37376
37410
  };
37377
37411
  /* end_public_function */
37378
37412
 
37379
- const convertToInternalComment = (commentPayload) => {
37380
- const { comments } = commentPayload;
37381
- return Object.assign(Object.assign({}, commentPayload), { comments: comments.map(comment => {
37382
- if (comment.hasOwnProperty('myReactions'))
37383
- return comment;
37384
- // Sometimes `myReactions` field will not come with BE response because that field is empty
37385
- // We need to put it with an empty array manually to make it show up in client side
37386
- return Object.assign({ myReactions: [] }, comment);
37387
- }) });
37388
- };
37389
-
37390
- const queryComments = async (query) => {
37413
+ const convertToInternalComment = (commentPayload) => {
37414
+ const { comments } = commentPayload;
37415
+ return Object.assign(Object.assign({}, commentPayload), { comments: comments.map(comment => {
37416
+ if (comment.hasOwnProperty('myReactions'))
37417
+ return comment;
37418
+ // Sometimes `myReactions` field will not come with BE response because that field is empty
37419
+ // We need to put it with an empty array manually to make it show up in client side
37420
+ return Object.assign({ myReactions: [] }, comment);
37421
+ }) });
37422
+ };
37423
+
37424
+ const queryComments = async (query) => {
37425
+ const client = getActiveClient();
37426
+ client.log('comment/queryComments', query);
37427
+ const { limit = 10, includeDeleted } = query, params = __rest(query, ["limit", "includeDeleted"]);
37428
+ const options = {
37429
+ type: params.sortBy || query.limit ? 'pagination' : undefined,
37430
+ limit: query.limit,
37431
+ token: query.page,
37432
+ };
37433
+ // const filterByParentId = query.parentId !== undefined
37434
+ // API-FIX: parameters should be querystring. (1)
37435
+ // API-FIX: backend should answer Amity.Response (2)
37436
+ // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.CommentPayload>>>(
37437
+ const { data } = await client.http.get(`/api/v3/comments`, {
37438
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted),
37439
+ // filterByParentId, API-FIX: backend does not support this boolean LOL. what the hell seriously.
37440
+ options }),
37441
+ });
37442
+ // API-FIX: backend should answer Amity.Response (2)
37443
+ // const { paging, comments } = unwrapPayload(data)
37444
+ const { paging } = data, payload = __rest(data, ["paging"]);
37445
+ const processedData = convertToInternalComment(payload);
37446
+ const { comments } = processedData;
37447
+ const cachedAt = client.cache && Date.now();
37448
+ if (client.cache) {
37449
+ ingestInCache(processedData, { cachedAt });
37450
+ const cacheKey = ['comment', 'query', Object.assign(Object.assign({}, params), { options: { limit } })];
37451
+ pushToCache(cacheKey, { comments: comments.map(getResolver('comment')), paging });
37452
+ }
37453
+ return { data: comments, cachedAt, paging };
37454
+ };
37455
+
37456
+ /* begin_public_function
37457
+ id: comment.query
37458
+ */
37459
+ /**
37460
+ * ```js
37461
+ * import { getComments } from '@amityco/ts-sdk-react-native'
37462
+ *
37463
+ * let comments = []
37464
+ * const unsub = getComments({
37465
+ * referenceType: Amity.InternalComment['referenceType'];
37466
+ * referenceId: Amity.InternalComment['referenceId'];
37467
+ * }, response => merge(comments, response.data))
37468
+ * ```
37469
+ *
37470
+ * Observe all mutations on a list of {@link Amity.InternalComment} for a given target object
37471
+ *
37472
+ * @param referenceType the type of the target
37473
+ * @param referenceId the ID of the target
37474
+ * @param callback the function to call when new data are available
37475
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
37476
+ *
37477
+ * @category Comments Live Collection
37478
+ */
37479
+ const getComments = (params, callback, config) => {
37480
+ const { log, cache } = getActiveClient();
37481
+ if (!cache) {
37482
+ console.log('For using Live Collection feature you need to enable Cache!');
37483
+ }
37484
+ const timestamp = Date.now();
37485
+ log(`getComments(tmpid: ${timestamp}) > listen`);
37486
+ const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
37487
+ const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
37488
+ const disposers = [];
37489
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
37490
+ const cacheKey = [
37491
+ 'comment',
37492
+ 'collection',
37493
+ {
37494
+ referenceId: params.referenceType,
37495
+ referenceType: params.referenceId,
37496
+ parentId: (params === null || params === void 0 ? void 0 : params.parentId) || '',
37497
+ sortBy,
37498
+ },
37499
+ ];
37500
+ const responder = (data) => {
37501
+ var _a, _b;
37502
+ let comments = (_a = data.data
37503
+ .map(commentId => pullFromCache(['comment', 'get', commentId]))
37504
+ .filter(({ data }) => data.parentId === (params === null || params === void 0 ? void 0 : params.parentId))
37505
+ .filter(Boolean)
37506
+ .map(({ data }) => LinkedObject.comment(data))) !== null && _a !== void 0 ? _a : [];
37507
+ if (!params.includeDeleted) {
37508
+ comments = filterByPropEquality(comments, 'isDeleted', false);
37509
+ }
37510
+ comments = comments.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
37511
+ callback({
37512
+ onNextPage: onFetch,
37513
+ data: comments,
37514
+ hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
37515
+ loading: data.loading,
37516
+ error: data.error,
37517
+ });
37518
+ };
37519
+ const realtimeRouter = (action) => (comment) => {
37520
+ var _a;
37521
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
37522
+ if (params.referenceId !== comment.referenceId ||
37523
+ params.referenceType !== comment.referenceType ||
37524
+ !collection) {
37525
+ return;
37526
+ }
37527
+ if (action === 'onCreate') {
37528
+ collection.data = [...new Set([comment.commentId, ...collection.data])];
37529
+ }
37530
+ else if (action === 'onDelete') {
37531
+ collection.data = collection.data.filter(p => p !== comment.commentId);
37532
+ }
37533
+ pushToCache(cacheKey, collection);
37534
+ responder(collection);
37535
+ };
37536
+ const onFetch = (initial = false) => {
37537
+ var _a, _b, _c;
37538
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
37539
+ const comments = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
37540
+ if (!initial && comments.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
37541
+ return;
37542
+ const query = createQuery(queryComments, Object.assign(Object.assign({}, queryParams), { limit: queryLimit, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
37543
+ runQuery(query, ({ data: result, error, loading, paging }) => {
37544
+ const page = paging === null || paging === void 0 ? void 0 : paging.next;
37545
+ const data = {
37546
+ loading,
37547
+ error,
37548
+ params: { page },
37549
+ data: comments,
37550
+ };
37551
+ if (result) {
37552
+ data.data = initial
37553
+ ? result.map(getResolver('comment')) // Replace a collection list with new data from BE
37554
+ : [...new Set([...comments, ...result.map(getResolver('comment'))])];
37555
+ }
37556
+ pushToCache(cacheKey, data);
37557
+ responder(data);
37558
+ }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
37559
+ };
37560
+ disposers.push(onCommentCreated(realtimeRouter('onCreate')), onCommentUpdated(realtimeRouter('onUpdate')), onCommentDeleted(realtimeRouter('onDelete')), onCommentFlagged(realtimeRouter('onFlagged')), onCommentUnflagged(realtimeRouter('onUnflagged')), onCommentReactionAdded(realtimeRouter('onReactionAdded')), onCommentReactionRemoved(realtimeRouter('onReactionRemoved')));
37561
+ onFetch(true);
37562
+ disposers.push(() => dropFromCache(cacheKey));
37563
+ return () => {
37564
+ log(`getComments(tmpid: ${timestamp}) > dispose`);
37565
+ disposers.forEach(fn => fn());
37566
+ };
37567
+ };
37568
+ /* end_public_function */
37569
+
37570
+ var index$5 = /*#__PURE__*/Object.freeze({
37571
+ __proto__: null,
37572
+ getCommentByIds: getCommentByIds,
37573
+ createComment: createComment,
37574
+ updateComment: updateComment,
37575
+ deleteComment: deleteComment,
37576
+ softDeleteComment: softDeleteComment,
37577
+ hardDeleteComment: hardDeleteComment,
37578
+ flagComment: flagComment,
37579
+ unflagComment: unflagComment,
37580
+ isCommentFlaggedByMe: isCommentFlaggedByMe,
37581
+ onCommentCreated: onCommentCreated,
37582
+ onCommentUpdated: onCommentUpdated,
37583
+ onCommentDeleted: onCommentDeleted,
37584
+ onCommentFlagged: onCommentFlagged,
37585
+ onCommentUnflagged: onCommentUnflagged,
37586
+ onCommentReactionAdded: onCommentReactionAdded,
37587
+ onCommentReactionRemoved: onCommentReactionRemoved,
37588
+ observeComments: observeComments,
37589
+ observeComment: observeComment,
37590
+ getComment: getComment,
37591
+ getComments: getComments
37592
+ });
37593
+
37594
+ /* begin_public_function
37595
+ id: post.get
37596
+ */
37597
+ /**
37598
+ * ```js
37599
+ * import { PostRepository } from '@amityco/ts-sdk-react-native';
37600
+ *
37601
+ * let post;
37602
+ *
37603
+ * const unsub = PostRepository.getPost(postId, response => {
37604
+ * post = response.data;
37605
+ * });
37606
+ * ```
37607
+ *
37608
+ * Observe all mutation on a given {@link Amity.Post}
37609
+ *
37610
+ * @param postId the ID of the message to observe
37611
+ * @param callback the function to call when new data are available
37612
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the sub channel
37613
+ *
37614
+ * @category Post Live Object
37615
+ */
37616
+ const getPost = (postId, callback) => {
37617
+ return liveObject(postId, callback, 'postId', getPost$1, [
37618
+ onPostApproved,
37619
+ onPostDeclined,
37620
+ (callback) => {
37621
+ return onPostDeleted((post) => {
37622
+ var _a;
37623
+ let targetPost = post;
37624
+ // check if the deleted post is a child of the target post
37625
+ if (post.parentPostId === postId && post.isDeleted) {
37626
+ const parentPost = (_a = pullFromCache([
37627
+ 'post',
37628
+ 'get',
37629
+ post.parentPostId,
37630
+ ])) === null || _a === void 0 ? void 0 : _a.data;
37631
+ if (parentPost) {
37632
+ parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
37633
+ pushToCache(['post', 'get', parentPost.postId], parentPost);
37634
+ // if the deleted post is a child of the target post, then the target post is the parent post
37635
+ targetPost = parentPost;
37636
+ }
37637
+ }
37638
+ callback(targetPost);
37639
+ });
37640
+ },
37641
+ onPostFlagged,
37642
+ (callback) => {
37643
+ return onPostReactionAdded((post) => {
37644
+ callback(LinkedObject.post(post));
37645
+ });
37646
+ },
37647
+ (callback) => {
37648
+ return onPostReactionRemoved((post) => {
37649
+ callback(LinkedObject.post(post));
37650
+ });
37651
+ },
37652
+ onPostUnflagged,
37653
+ onPostUpdated,
37654
+ convertEventPayload((callback) => {
37655
+ return onCommentCreated(async (comment) => {
37656
+ if (comment.referenceId === postId) {
37657
+ await getPost$1(postId);
37658
+ callback(comment);
37659
+ }
37660
+ });
37661
+ }, 'referenceId', 'post'),
37662
+ convertEventPayload((callback) => {
37663
+ return onCommentDeleted(async (comment) => {
37664
+ if (comment.referenceId === postId) {
37665
+ await getPost$1(postId);
37666
+ callback(comment);
37667
+ }
37668
+ });
37669
+ }, 'referenceId', 'post'),
37670
+ ]);
37671
+ };
37672
+ /* end_public_function */
37673
+
37674
+ /**
37675
+ * ```js
37676
+ * import { queryPosts } from '@amityco/ts-sdk-react-native'
37677
+ * const { data: posts, prevPage, nextPage } = await queryPosts({ targetId, targetType })
37678
+ * ```
37679
+ *
37680
+ * Queries a paginable list of {@link Amity.Post} objects
37681
+ *
37682
+ * @param query The query parameters
37683
+ * @returns posts
37684
+ *
37685
+ * @category Post API
37686
+ * @async
37687
+ */
37688
+ const queryPosts = async (query) => {
37391
37689
  const client = getActiveClient();
37392
- client.log('comment/queryComments', query);
37393
- const { limit = 10, includeDeleted } = query, params = __rest(query, ["limit", "includeDeleted"]);
37394
- const options = {
37395
- type: params.sortBy || query.limit ? 'pagination' : undefined,
37396
- limit: query.limit,
37397
- token: query.page,
37398
- };
37399
- // const filterByParentId = query.parentId !== undefined
37690
+ client.log('post/queryPosts', query);
37691
+ const { page, limit = 10, includeDeleted } = query, params = __rest(query, ["page", "limit", "includeDeleted"]);
37692
+ const { dataTypes, matchingOnlyParentPost } = params;
37693
+ const options = (() => {
37694
+ if (page)
37695
+ return { token: page };
37696
+ if (limit)
37697
+ return { limit };
37698
+ return undefined;
37699
+ })();
37400
37700
  // API-FIX: parameters should be querystring. (1)
37401
37701
  // API-FIX: backend should answer Amity.Response (2)
37402
- // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.CommentPayload>>>(
37403
- const { data } = await client.http.get(`/api/v3/comments`, {
37702
+ // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.PostPayload>>>(
37703
+ const { data } = await client.http.get(`/api/v4/posts`, {
37404
37704
  params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted),
37405
- // filterByParentId, API-FIX: backend does not support this boolean LOL. what the hell seriously.
37406
- options }),
37705
+ /*
37706
+ * when creating post like image, file, video BE will create 2 posts
37707
+ * 1. parent post to store text with dataType=text
37708
+ * 2. child post to store dataTypes post data
37709
+ *
37710
+ * By default, BE queries only parent post
37711
+ */
37712
+ matchingOnlyParentPost: matchingOnlyParentPost !== null && matchingOnlyParentPost !== void 0 ? matchingOnlyParentPost : !(dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length), options }),
37407
37713
  });
37408
37714
  // API-FIX: backend should answer Amity.Response (2)
37409
- // const { paging, comments } = unwrapPayload(data)
37715
+ // const { paging, posts } = unwrapPayload(data)
37716
+ // unpacking
37410
37717
  const { paging } = data, payload = __rest(data, ["paging"]);
37411
- const processedData = convertToInternalComment(payload);
37412
- const { comments } = processedData;
37718
+ const paperedPayload = prepareMembershipPayload(payload, 'communityUsers');
37719
+ const { posts } = payload;
37413
37720
  const cachedAt = client.cache && Date.now();
37414
37721
  if (client.cache) {
37415
- ingestInCache(processedData, { cachedAt });
37416
- const cacheKey = ['comment', 'query', Object.assign(Object.assign({}, params), { options: { limit } })];
37417
- pushToCache(cacheKey, { comments: comments.map(getResolver('comment')), paging });
37722
+ ingestInCache(paperedPayload, { cachedAt });
37723
+ const cacheKey = ['post', 'query', Object.assign(Object.assign({}, params), { options })];
37724
+ pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
37418
37725
  }
37419
- return { data: comments, cachedAt, paging };
37726
+ return { data: posts.map(LinkedObject.post), cachedAt, paging };
37420
37727
  };
37421
37728
 
37422
37729
  /* begin_public_function
37423
- id: comment.query
37730
+ id: post.query
37424
37731
  */
37425
37732
  /**
37426
37733
  * ```js
37427
- * import { getComments } from '@amityco/ts-sdk-react-native'
37734
+ * import { PostRepository } from '@amityco/ts-sdk-react-native'
37428
37735
  *
37429
- * let comments = []
37430
- * const unsub = getComments({
37431
- * referenceType: Amity.InternalComment['referenceType'];
37432
- * referenceId: Amity.InternalComment['referenceId'];
37433
- * }, response => merge(comments, response.data))
37736
+ * let posts = []
37737
+ * const unsub = PostRepository.getPosts({
37738
+ * targetType: Amity.PostTargetType,
37739
+ * targetId: Amity.Post['targetId'],
37740
+ * }, response => merge(posts, response.data))
37434
37741
  * ```
37435
37742
  *
37436
- * Observe all mutations on a list of {@link Amity.InternalComment} for a given target object
37743
+ * Observe all mutations on a list of {@link Amity.Post} for a given target object
37437
37744
  *
37438
- * @param referenceType the type of the target
37439
- * @param referenceId the ID of the target
37745
+ * @param params.targetType the type of the target
37746
+ * @param params.targetId the ID of the target
37440
37747
  * @param callback the function to call when new data are available
37748
+ * @param config
37441
37749
  * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
37442
37750
  *
37443
- * @category Comments Live Collection
37751
+ * @category Posts Live Collection
37444
37752
  */
37445
- const getComments = (params, callback, config) => {
37753
+ const getPosts = (params, callback, config) => {
37446
37754
  const { log, cache } = getActiveClient();
37447
37755
  if (!cache) {
37448
- console.log('For using Live Collection feature you need to enable Cache!');
37756
+ console.log(ENABLE_CACHE_MESSAGE);
37449
37757
  }
37450
37758
  const timestamp = Date.now();
37451
- log(`getComments(tmpid: ${timestamp}) > listen`);
37759
+ log(`getPosts(tmpid: ${timestamp}) > listen`);
37452
37760
  const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
37761
+ const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
37453
37762
  const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
37454
37763
  const disposers = [];
37455
- const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
37456
37764
  const cacheKey = [
37457
- 'comment',
37765
+ 'post',
37458
37766
  'collection',
37459
- {
37460
- referenceId: params.referenceType,
37461
- referenceType: params.referenceId,
37462
- parentId: (params === null || params === void 0 ? void 0 : params.parentId) || '',
37463
- sortBy,
37464
- },
37767
+ { targetId: params.targetId, targetType: params.targetType },
37465
37768
  ];
37466
37769
  const responder = (data) => {
37467
- var _a, _b;
37468
- let comments = (_a = data.data
37469
- .map(commentId => pullFromCache(['comment', 'get', commentId]))
37470
- .filter(({ data }) => data.parentId === (params === null || params === void 0 ? void 0 : params.parentId))
37770
+ var _a, _b, _c;
37771
+ let posts = (_a = data.data
37772
+ .map(postId => pullFromCache(['post', 'get', postId]))
37471
37773
  .filter(Boolean)
37472
- .map(({ data }) => LinkedObject.comment(data))) !== null && _a !== void 0 ? _a : [];
37774
+ .map(({ data }) => LinkedObject.post(data))) !== null && _a !== void 0 ? _a : [];
37775
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
37776
+ posts = posts.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
37473
37777
  if (!params.includeDeleted) {
37474
- comments = filterByPropEquality(comments, 'isDeleted', false);
37778
+ posts = filterByPropEquality(posts, 'isDeleted', false);
37779
+ }
37780
+ if (params.tags) {
37781
+ posts = posts.filter(p => { var _a; return (_a = p.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = params.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
37782
+ }
37783
+ if (params.targetType === 'community' && params.feedType) {
37784
+ posts = filterByFeedType(posts, params.feedType);
37785
+ }
37786
+ if ((_b = params.dataTypes) === null || _b === void 0 ? void 0 : _b.length) {
37787
+ posts = filterByPostDataTypes(posts, params.dataTypes);
37475
37788
  }
37476
- comments = comments.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
37477
37789
  callback({
37478
37790
  onNextPage: onFetch,
37479
- data: comments,
37480
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
37791
+ data: posts,
37792
+ hasNextPage: !!((_c = data.params) === null || _c === void 0 ? void 0 : _c.page),
37481
37793
  loading: data.loading,
37482
37794
  error: data.error,
37483
37795
  });
37484
37796
  };
37485
- const realtimeRouter = (action) => (comment) => {
37486
- var _a;
37797
+ const realtimeRouter = (action) => (post) => {
37798
+ var _a, _b;
37487
37799
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
37488
- if (params.referenceId !== comment.referenceId ||
37489
- params.referenceType !== comment.referenceType ||
37490
- !collection) {
37800
+ if (!collection)
37491
37801
  return;
37802
+ if (post.parentPostId && post.isDeleted) {
37803
+ const parentPost = (_b = pullFromCache([
37804
+ 'post',
37805
+ 'get',
37806
+ post.parentPostId,
37807
+ ])) === null || _b === void 0 ? void 0 : _b.data;
37808
+ if (!parentPost || (parentPost === null || parentPost === void 0 ? void 0 : parentPost.targetId) !== params.targetId)
37809
+ return;
37810
+ parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
37811
+ pushToCache(['post', 'get', parentPost.postId], parentPost);
37492
37812
  }
37493
- if (action === 'onCreate') {
37494
- collection.data = [...new Set([comment.commentId, ...collection.data])];
37813
+ else {
37814
+ if (params.targetId !== post.targetId)
37815
+ return;
37816
+ if (params.targetType !== post.targetType)
37817
+ return;
37495
37818
  }
37496
- else if (action === 'onDelete') {
37497
- collection.data = collection.data.filter(p => p !== comment.commentId);
37819
+ /*
37820
+ * This is not ideal, but currently this is the only way to update the
37821
+ * collection on post declined
37822
+ */
37823
+ if (action === 'onDeclined') {
37824
+ collection.data = collection.data.filter(postId => postId !== post.postId);
37825
+ }
37826
+ else {
37827
+ collection.data = [...new Set([post.postId, ...collection.data])];
37498
37828
  }
37499
37829
  pushToCache(cacheKey, collection);
37500
37830
  responder(collection);
@@ -37502,32 +37832,49 @@ const getComments = (params, callback, config) => {
37502
37832
  const onFetch = (initial = false) => {
37503
37833
  var _a, _b, _c;
37504
37834
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
37505
- const comments = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
37506
- if (!initial && comments.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
37835
+ const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
37836
+ if (!initial && posts.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
37507
37837
  return;
37508
- const query = createQuery(queryComments, Object.assign(Object.assign({}, queryParams), { limit: queryLimit, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
37838
+ const query = createQuery(queryPosts, Object.assign(Object.assign({}, queryParams), { limit: initial ? limit : undefined, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
37509
37839
  runQuery(query, ({ data: result, error, loading, paging }) => {
37510
- const page = paging === null || paging === void 0 ? void 0 : paging.next;
37511
37840
  const data = {
37512
37841
  loading,
37513
37842
  error,
37514
- params: { page },
37515
- data: comments,
37843
+ params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
37844
+ data: posts,
37516
37845
  };
37517
37846
  if (result) {
37518
37847
  data.data = initial
37519
- ? result.map(getResolver('comment')) // Replace a collection list with new data from BE
37520
- : [...new Set([...comments, ...result.map(getResolver('comment'))])];
37848
+ ? result.map(getResolver('post'))
37849
+ : [...new Set([...posts, ...result.map(getResolver('post'))])];
37521
37850
  }
37522
37851
  pushToCache(cacheKey, data);
37523
37852
  responder(data);
37524
37853
  }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
37525
37854
  };
37526
- disposers.push(onCommentCreated(realtimeRouter('onCreate')), onCommentUpdated(realtimeRouter('onUpdate')), onCommentDeleted(realtimeRouter('onDelete')), onCommentFlagged(realtimeRouter('onFlagged')), onCommentUnflagged(realtimeRouter('onUnflagged')), onCommentReactionAdded(realtimeRouter('onReactionAdded')), onCommentReactionRemoved(realtimeRouter('onReactionRemoved')));
37855
+ disposers.push(onPostCreated(realtimeRouter('onCreate')), onPostApproved(realtimeRouter('onApproved')), onPostDeclined(realtimeRouter('onDeclined')), onPostDeleted(realtimeRouter('onDelete')), onPostUpdated(realtimeRouter('onUpdate')), onPostFlagged(realtimeRouter('onFlagged')), onPostUnflagged(realtimeRouter('onUnflagged')), onPostReactionAdded(realtimeRouter('onReactionAdded')), onPostReactionRemoved(realtimeRouter('onReactionRemoved')), convertEventPayload((callback) => {
37856
+ return onCommentCreated(async (comment) => {
37857
+ var _a;
37858
+ const currentCollection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
37859
+ if (!currentCollection || currentCollection.data.includes(comment.referenceId))
37860
+ return;
37861
+ await getPost$1(comment.referenceId);
37862
+ callback(comment);
37863
+ });
37864
+ }, 'referenceId', 'post')(realtimeRouter('onUpdate')), convertEventPayload((callback) => {
37865
+ return onCommentDeleted(async (comment) => {
37866
+ var _a;
37867
+ const currentCollection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
37868
+ if (!currentCollection || currentCollection.data.includes(comment.referenceId))
37869
+ return;
37870
+ await getPost$1(comment.referenceId);
37871
+ callback(comment);
37872
+ });
37873
+ }, 'referenceId', 'post')(realtimeRouter('onUpdate')));
37527
37874
  onFetch(true);
37528
37875
  disposers.push(() => dropFromCache(cacheKey));
37529
37876
  return () => {
37530
- log(`getComments(tmpid: ${timestamp}) > dispose`);
37877
+ log(`getPosts(tmpid: ${timestamp}) > dispose`);
37531
37878
  disposers.forEach(fn => fn());
37532
37879
  };
37533
37880
  };
@@ -37535,26 +37882,31 @@ const getComments = (params, callback, config) => {
37535
37882
 
37536
37883
  var index$4 = /*#__PURE__*/Object.freeze({
37537
37884
  __proto__: null,
37538
- getCommentByIds: getCommentByIds,
37539
- createComment: createComment,
37540
- updateComment: updateComment,
37541
- deleteComment: deleteComment,
37542
- softDeleteComment: softDeleteComment,
37543
- hardDeleteComment: hardDeleteComment,
37544
- flagComment: flagComment,
37545
- unflagComment: unflagComment,
37546
- isCommentFlaggedByMe: isCommentFlaggedByMe,
37547
- onCommentCreated: onCommentCreated,
37548
- onCommentUpdated: onCommentUpdated,
37549
- onCommentDeleted: onCommentDeleted,
37550
- onCommentFlagged: onCommentFlagged,
37551
- onCommentUnflagged: onCommentUnflagged,
37552
- onCommentReactionAdded: onCommentReactionAdded,
37553
- onCommentReactionRemoved: onCommentReactionRemoved,
37554
- observeComments: observeComments,
37555
- observeComment: observeComment,
37556
- getComment: getComment,
37557
- getComments: getComments
37885
+ getPostByIds: getPostByIds,
37886
+ createPost: createPost,
37887
+ updatePost: updatePost,
37888
+ editPost: editPost,
37889
+ deletePost: deletePost,
37890
+ softDeletePost: softDeletePost,
37891
+ hardDeletePost: hardDeletePost,
37892
+ approvePost: approvePost,
37893
+ declinePost: declinePost,
37894
+ flagPost: flagPost,
37895
+ unflagPost: unflagPost,
37896
+ isPostFlaggedByMe: isPostFlaggedByMe,
37897
+ onPostCreated: onPostCreated,
37898
+ onPostUpdated: onPostUpdated,
37899
+ onPostDeleted: onPostDeleted,
37900
+ onPostApproved: onPostApproved,
37901
+ onPostDeclined: onPostDeclined,
37902
+ onPostFlagged: onPostFlagged,
37903
+ onPostUnflagged: onPostUnflagged,
37904
+ onPostReactionAdded: onPostReactionAdded,
37905
+ onPostReactionRemoved: onPostReactionRemoved,
37906
+ observePosts: observePosts,
37907
+ observePost: observePost,
37908
+ getPost: getPost,
37909
+ getPosts: getPosts
37558
37910
  });
37559
37911
 
37560
37912
  /* begin_public_function
@@ -37955,7 +38307,7 @@ const queryStreams = async (query) => {
37955
38307
  */
37956
38308
  /**
37957
38309
  * ```js
37958
- * import { StreamRepository } from '@amityco/ts-sdk-react-native'
38310
+ * import { StreamRepository } from '@amityco/ts-sdk'
37959
38311
  * const streams = await StreamRepository.getStreams()
37960
38312
  * ```
37961
38313
  *
@@ -38386,7 +38738,7 @@ var index$2 = /*#__PURE__*/Object.freeze({
38386
38738
  getPoll: getPoll
38387
38739
  });
38388
38740
 
38389
- const privateKey = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHo80SecH7FuF2\nhFYnb+l26/VN8UMLXAQFLnxciNTEwkGVFMpdezlH8rU2HtUJL4RETogbAOLVY0XM\njs6sPn8G1nALmh9qeDpUtVqFOVtBHxEZ910TLOtQiunjqJKO5nWdqZ71EC3OFluR\niGQkO84BiIFbv37ub7xl3S8XarbtKoLcyVpkDHi+1wx1pgCAn6gtBUgckPL5NR8j\nLseabl3HAXQfhTCKo4tmOFM2Dxwl1IUMmIJrJg/aIU/U0tj/1Eoo7mG0JcNWX19l\nW3EecCbi0ncCJOrkUdwlBrcjaMayaX/ubEwyUeTGiLdyc4L3GRLHjyK8xgVNXRMH\nbZWJ2a5NAgMBAAECggEASxuE+35zTFO/XydKgmvIGcWL9FbgMlXb7Vcf0nBoG945\nbiz0NVc2paraIhJXc608xbYF3qLmtAE1MVBI0ORyRdBHNxY024l/6H6SH60Ed+uI\nM4ysp5ourY6Vj+DLwpdRiI9YDjqYAQDIUmhNxJP7XPhOMoZI6st+xZQBM34ic/bv\nAMSJm9OZphSp3+qXVkFZztr2mxD2EZSJJLYxi8BCdgM2qhazalbcJ6zDKHCZWVWm\n8RRxDGldyMb/237JxETzP40tAlzOZDmBAbUgEnurDJ93RVDIE3rbZUshwgeQd18a\nem096mWgvB1AIKYgsTAR3pw+V19YWAjq/glP6fz8wQKBgQD/oQq+ukKF0PRgBeM5\ngeTjSwsdGppQLmf5ndujvoiz/TpdjDEPu6R8kigQr1rG2t4K/yfdZoI8RdmJD1al\n3Q7N9hofooSy4rj6E3txzWZCHJjHad2cnCp/O26HiReGAl7wTcfTmNdiFHhZQzm5\nJBkvWAiwuvQMNfEbnXxw6/vIDwKBgQDH7fX8gsc77JLvAWgp1MaQN/sbqVb6JeT1\nFQfR8E/WFCSmzQBtNzd5KgYuCeelwr/8DyYytvN2BzCYZXp73gI1jF3YlW5jVn74\nOY6TwQ095digwo6Z0yuxopdIOApKgAkL9PRKgNrqAf3NAyMua6lOGifzjDojC3KU\nfylQmxMn4wKBgHp2B9O/H0dEBw5JQ8W0+JX6yWQz7mEjGiR2/1W+XXb8hQ1zr709\nw1r6Gb+EghRpnZ3fBpYGGbYOMFx8wKHM+N6qW3F0ReX8v2juFGE8aRSa5oYBrWzt\nU16Idjbv8hj84cZ1PJmdyvDtpYn9rpWHOZl4rxEbPvbqkIsOMyNVqdT5AoGAOSge\nmwIIU2le2FVeohbibXiToWTYKMuMmURZ5/r72AgKMmWJKbAPe+Q3wBG01/7FRBpQ\noU8Ma0HC8s6QJbliiEyIx9JwrJWd1vkdecBHONrtA4ibm/5zD2WcOllLF+FitLhi\n3qnX6+6F0IaFGFBPJrTzlv0P4dTz/OAdv52V7GECgYEA2TttOKBAqWllgOaZOkql\nLVMJVmgR7s6tLi1+cEP8ZcapV9aRbRzTAKXm4f8AEhtlG9F9kCOvHYCYGi6JaiWJ\nZkHjeex3T+eE6Di6y5Bm/Ift5jtVhJ4jCVwHOKTMej79NPUFTJfv8hCo29haBDv6\nRXFrv+T21KCcw8k3sJeJWWQ=\n-----END PRIVATE KEY-----";
38741
+ const privateKey = "-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDAARz+hmBgi8pJ\nQb8LeY41gtHhk+ACMwRfhsn7GqpqRQNG2qU0755mzZuVDUqjQMGSo8THJB7O+OJs\nflbZRkFXlFoFOVNw1UpNOgwEQZ6wB9oRwzepTJAfF1sVhm/o/ixvXh1zDFNDy6yZ\npXyiiJHUVxqyjllZhxnwdvjoVtDs6hW6awG09bB9nh/TTejlUKXoAgzqVwu/1QMu\nUVViET495elEe19aUarEy+oL2iKeXCEvqda/pWNBdbieFyJvvZ08HN8dPuT88wq2\njZLEAth1vrwQ2IAa4ktaLcBQdLJgIkrbDvAiVZ8lQAjS/bq5vXQikTGvoPlC5bbn\nvuOM/3eLAgMBAAECggEAVZ+peHAghq2QVj71nX5lxsNCKaCyYwixSJBpfouTt7Rz\nE6PpzMOXFi1W1o+I22jDakuSM2SOQKqI/u0QefB0r0O/KVk5NrZHXk0mkrdYtxOp\nUgaGyf8UvmjB+8VqHrNKyZdk9qtmbnNj01kTTcAtmE4H39zPR7eR/8Rul94vaZbs\nwCnKJS3mLT3JxyGug6lxanveKkjG+CKC1nJQYWaxCJxaFSzbwXQPvDhB+TvrIbee\npd5v4EAyEJohpr+T9oDGGJkb/KARBZCtwLyB976PKJwwBA8MRVL1i5QwawuMiMq5\nUtnOnbGKtCeFzaLbNU0Qi8bqyims84EQxC6DOu1fkQKBgQDdvsoBsEhsOXV7hlIJ\naEd0eSJZVkdqimxH8uGoMM2FeNaOrcB6yBXqTSP0R3OIyf8eaY6yjRvP30ZNXcll\n/gD3O1Mu6YmWQdt1W2WA6pKOsUuPXasf0pdOF7IiFZKlSabz5YHXFqwVuqm8loaj\nsXel3YWqPVdHiankE7tz+3ssnQKBgQDdqi4TNdD1MdEpihx19jr0QjUiXW3939FK\nqp30HESPEGDGQzXdmJgif9HhZb+cJSuWaHEbjgBrYahvgCF+y6LbEpOD+D/dmT+s\nDEAQaR84sah6dokwPjV8fjBSrcVFjCS+doxv0d3p/9OUEeyUhFrY03nxtIEYkLIE\n/Zvn37b4RwKBgQCLENVFe9XfsaVhQ5r9dV2iyTlmh7qgMZG5CbTFs12hQGhm8McO\n+Z7s41YSJCFr/yq1WwP4LJDtrBw99vyQr1zRsG35tNLp3gGRNzGQSQyC2uQFVHw2\np+7mNewsfhUK/gbrXNsyFnDz6635rPlhfbII3sWuP2wWXFqkxE9CbMwR7QKBgQC6\nawDMzxmo2/iYArrkyevSuEuPVxvFwpF1RgAI6C0QVCnPE38dmdN4UB7mfHekje4W\nVEercMURidPp0cxZolCYBQtilUjAyL0vqC3In1/Ogjq6oy3FEMxSop1pKxMY5j+Q\nnoqFD+6deLUrddeNH7J3X4LSr4dSbX4JjG+tlgt+yQKBgQCuwTL4hA6KqeInQ0Ta\n9VQX5Qr8hFlqJz1gpymi/k63tW/Ob8yedbg3WWNWyShwRMFYyY9S81ITFWM95uL6\nvF3x9rmRjwElJw9PMwVu6dmf/CO0Z1wzXSp2VVD12gbrUD/0/d7MUoJ9LgC8X8f/\nn0txLHYGHbx+nf95+JUg6lV3hg==\n-----END PRIVATE KEY-----";
38390
38742
  /*
38391
38743
  * The crypto algorithm used for importing key and signing string
38392
38744
  */
@@ -39531,7 +39883,7 @@ class StoryLiveCollectionController extends LiveCollectionController {
39531
39883
  this.queryStreamController = new StoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
39532
39884
  this.paginationController = paginationController;
39533
39885
  this.callback = callback.bind(this);
39534
- this.loadPage(true);
39886
+ this.loadPage({ initial: true });
39535
39887
  }
39536
39888
  setup() {
39537
39889
  var _a;
@@ -39713,7 +40065,7 @@ class GlobalStoryLiveCollectionController extends LiveCollectionController {
39713
40065
  this.queryStreamController = new GlobalStoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
39714
40066
  this.paginationController = paginationController;
39715
40067
  this.callback = callback.bind(this);
39716
- this.loadPage(true);
40068
+ this.loadPage({ initial: true });
39717
40069
  }
39718
40070
  setup() {
39719
40071
  var _a;
@@ -39749,7 +40101,7 @@ class GlobalStoryLiveCollectionController extends LiveCollectionController {
39749
40101
  return rest;
39750
40102
  });
39751
40103
  this.callback({
39752
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
40104
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
39753
40105
  data,
39754
40106
  hasNextPage: !!this.paginationController.getNextToken(),
39755
40107
  loading,
@@ -39855,4 +40207,4 @@ const createUserToken = async (apiKey, apiRegion, params) => {
39855
40207
  return { accessToken: data.accessToken };
39856
40208
  };
39857
40209
 
39858
- export { API_REGIONS, index$7 as CategoryRepository, index$b as ChannelRepository, index$k as Client, index$4 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$8 as CommunityRepository, ContentFeedType, DefaultCommunityPostSetting, index$6 as FeedRepository, index$h as FileRepository, FileType, index$1 as LiveStreamPlayer, MessageContentType, index$f as MessageRepository, index$2 as PollRepository, PostContentType, index$5 as PostRepository, index$g as ReactionRepository, index as StoryRepository, index$3 as StreamRepository, index$e as SubChannelRepository, SubscriptionLevels, index$i 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, 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 };
40210
+ export { API_REGIONS, index$7 as CategoryRepository, index$b as ChannelRepository, index$k as Client, index$5 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$8 as CommunityRepository, ContentFeedType, DefaultCommunityPostSetting, index$6 as FeedRepository, index$h as FileRepository, FileType, index$1 as LiveStreamPlayer, MessageContentType, index$f as MessageRepository, index$2 as PollRepository, PostContentType, index$4 as PostRepository, index$g as ReactionRepository, index as StoryRepository, index$3 as StreamRepository, index$e as SubChannelRepository, SubscriptionLevels, index$i 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, 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 };