@amityco/ts-sdk 6.26.3 → 6.27.1-061592b.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/model.d.ts +5 -5
  3. package/dist/@types/core/model.d.ts.map +1 -1
  4. package/dist/@types/core/payload.d.ts +1 -1
  5. package/dist/@types/core/payload.d.ts.map +1 -1
  6. package/dist/@types/domains/ad.d.ts +14 -2
  7. package/dist/@types/domains/ad.d.ts.map +1 -1
  8. package/dist/@types/domains/file.d.ts +6 -0
  9. package/dist/@types/domains/file.d.ts.map +1 -1
  10. package/dist/@types/domains/message.d.ts +4 -1
  11. package/dist/@types/domains/message.d.ts.map +1 -1
  12. package/dist/@types/domains/post.d.ts +3 -3
  13. package/dist/@types/domains/post.d.ts.map +1 -1
  14. package/dist/adRepository/api/getNetworkAds.d.ts.map +1 -1
  15. package/dist/analytic/service/analytic/AnalyticsEngine.d.ts +2 -2
  16. package/dist/analytic/service/analytic/AnalyticsEngine.d.ts.map +1 -1
  17. package/dist/analytic/service/analytic/AnalyticsEventCapturer.d.ts +11 -5
  18. package/dist/analytic/service/analytic/AnalyticsEventCapturer.d.ts.map +1 -1
  19. package/dist/client/api/getToken.d.ts +10 -5
  20. package/dist/client/api/getToken.d.ts.map +1 -1
  21. package/dist/client/api/index.d.ts +1 -0
  22. package/dist/client/api/index.d.ts.map +1 -1
  23. package/dist/client/api/login.d.ts.map +1 -1
  24. package/dist/client/api/logout.d.ts.map +1 -1
  25. package/dist/client/api/renewal.d.ts.map +1 -1
  26. package/dist/client/api/setUploadedFileAccessType.d.ts +2 -0
  27. package/dist/client/api/setUploadedFileAccessType.d.ts.map +1 -0
  28. package/dist/client/events/index.d.ts +1 -0
  29. package/dist/client/events/index.d.ts.map +1 -1
  30. package/dist/client/events/onNetworkActivities.d.ts +11 -0
  31. package/dist/client/events/onNetworkActivities.d.ts.map +1 -0
  32. package/dist/client/utils/GlobalFileAccessType.d.ts +10 -0
  33. package/dist/client/utils/GlobalFileAccessType.d.ts.map +1 -0
  34. package/dist/client/utils/NetworkActivitiesWatcher.d.ts +12 -0
  35. package/dist/client/utils/NetworkActivitiesWatcher.d.ts.map +1 -0
  36. package/dist/commentRepository/observers/getComments.d.ts +1 -1
  37. package/dist/commentRepository/observers/getComments.d.ts.map +1 -1
  38. package/dist/communityRepository/utils/payload.d.ts +7 -0
  39. package/dist/communityRepository/utils/payload.d.ts.map +1 -1
  40. package/dist/core/transports/http.d.ts.map +1 -1
  41. package/dist/fileRepository/api/createFile.d.ts.map +1 -1
  42. package/dist/fileRepository/api/createImage.d.ts.map +1 -1
  43. package/dist/fileRepository/api/createVideo.d.ts.map +1 -1
  44. package/dist/fileRepository/api/uploadFile.d.ts.map +1 -1
  45. package/dist/fileRepository/api/uploadImage.d.ts.map +1 -1
  46. package/dist/fileRepository/api/uploadVideo.d.ts.map +1 -1
  47. package/dist/index.cjs.js +898 -688
  48. package/dist/index.esm.js +729 -517
  49. package/dist/index.umd.js +4 -4
  50. package/dist/messageRepository/api/createMessage.d.ts +7 -25
  51. package/dist/messageRepository/api/createMessage.d.ts.map +1 -1
  52. package/dist/messageRepository/events/onMessageCreated.d.ts.map +1 -1
  53. package/dist/messageRepository/observers/getMessages/MessageLiveCollectionController.d.ts +4 -4
  54. package/dist/messageRepository/observers/getMessages/MessageLiveCollectionController.d.ts.map +1 -1
  55. package/dist/messageRepository/observers/getMessages/MessageQueryStreamController.d.ts.map +1 -1
  56. package/dist/messageRepository/utils/prepareMessagePayload.d.ts.map +1 -1
  57. package/dist/postRepository/api/editPost.d.ts +1 -1
  58. package/dist/postRepository/api/editPost.d.ts.map +1 -1
  59. package/dist/postRepository/api/updatePost.d.ts +1 -1
  60. package/dist/postRepository/api/updatePost.d.ts.map +1 -1
  61. package/dist/postRepository/internalApi/getPost.d.ts +5 -0
  62. package/dist/postRepository/internalApi/getPost.d.ts.map +1 -0
  63. package/dist/postRepository/internalApi/index.d.ts +13 -0
  64. package/dist/postRepository/internalApi/index.d.ts.map +1 -0
  65. package/dist/postRepository/observers/getPost.d.ts.map +1 -1
  66. package/dist/postRepository/observers/getPosts/PostLiveCollectionController.d.ts +14 -0
  67. package/dist/postRepository/observers/getPosts/PostLiveCollectionController.d.ts.map +1 -0
  68. package/dist/postRepository/observers/getPosts/PostPaginationController.d.ts +5 -0
  69. package/dist/postRepository/observers/getPosts/PostPaginationController.d.ts.map +1 -0
  70. package/dist/postRepository/observers/getPosts/PostQueryStreamController.d.ts +15 -0
  71. package/dist/postRepository/observers/getPosts/PostQueryStreamController.d.ts.map +1 -0
  72. package/dist/postRepository/observers/getPosts/enums.d.ts +12 -0
  73. package/dist/postRepository/observers/getPosts/enums.d.ts.map +1 -0
  74. package/dist/postRepository/observers/getPosts.d.ts.map +1 -1
  75. package/dist/postRepository/utils/payload.d.ts +2 -0
  76. package/dist/postRepository/utils/payload.d.ts.map +1 -0
  77. package/dist/utils/linkedObject/adLinkedObject.d.ts +1 -1
  78. package/dist/utils/linkedObject/adLinkedObject.d.ts.map +1 -1
  79. package/dist/utils/linkedObject/categoryLinkedObject.d.ts.map +1 -1
  80. package/dist/utils/linkedObject/index.d.ts +1 -1
  81. package/dist/utils/linkedObject/userLinkedObject.d.ts.map +1 -1
  82. package/dist/utils/tests/dummy/post.d.ts +3 -3
  83. package/package.json +1 -1
  84. package/src/@types/core/model.ts +5 -5
  85. package/src/@types/core/payload.ts +1 -1
  86. package/src/@types/domains/ad.ts +17 -6
  87. package/src/@types/domains/file.ts +8 -0
  88. package/src/@types/domains/message.ts +6 -1
  89. package/src/@types/domains/post.ts +3 -4
  90. package/src/adRepository/api/getNetworkAds.ts +22 -8
  91. package/src/analytic/service/analytic/AnalyticsEngine.ts +2 -2
  92. package/src/analytic/service/analytic/AnalyticsEventCapturer.ts +45 -27
  93. package/src/client/api/getToken.ts +15 -7
  94. package/src/client/api/index.ts +2 -0
  95. package/src/client/api/login.ts +11 -7
  96. package/src/client/api/logout.ts +4 -0
  97. package/src/client/api/renewal.ts +6 -1
  98. package/src/client/api/setUploadedFileAccessType.ts +5 -0
  99. package/src/client/api/tests/getToken.test.ts +3 -3
  100. package/src/client/events/index.ts +2 -0
  101. package/src/client/events/onNetworkActivities.ts +14 -0
  102. package/src/client/utils/GlobalFileAccessType.ts +23 -0
  103. package/src/client/utils/NetworkActivitiesWatcher.ts +31 -0
  104. package/src/commentRepository/observers/getComments.ts +1 -1
  105. package/src/communityRepository/utils/payload.ts +19 -3
  106. package/src/core/model/idResolvers.ts +1 -1
  107. package/src/core/transports/http.ts +25 -1
  108. package/src/fileRepository/api/createFile.ts +4 -0
  109. package/src/fileRepository/api/createImage.ts +4 -0
  110. package/src/fileRepository/api/createVideo.ts +4 -0
  111. package/src/fileRepository/api/uploadFile.ts +4 -0
  112. package/src/fileRepository/api/uploadImage.ts +4 -0
  113. package/src/fileRepository/api/uploadVideo.ts +4 -0
  114. package/src/messageRepository/api/createMessage.ts +83 -98
  115. package/src/messageRepository/events/onMessageCreated.ts +12 -6
  116. package/src/messageRepository/observers/getMessages/MessageLiveCollectionController.ts +26 -24
  117. package/src/messageRepository/observers/getMessages/MessageQueryStreamController.ts +3 -2
  118. package/src/messageRepository/observers/observeMessages.ts +3 -3
  119. package/src/messageRepository/utils/prepareMessagePayload.ts +1 -1
  120. package/src/postRepository/internalApi/getPost.ts +65 -0
  121. package/src/postRepository/internalApi/index.ts +16 -0
  122. package/src/postRepository/observers/getPost.ts +8 -1
  123. package/src/postRepository/observers/getPosts/PostLiveCollectionController.ts +190 -0
  124. package/src/postRepository/observers/getPosts/PostPaginationController.ts +45 -0
  125. package/src/postRepository/observers/getPosts/PostQueryStreamController.ts +102 -0
  126. package/src/postRepository/observers/getPosts/enums.ts +11 -0
  127. package/src/postRepository/observers/getPosts.ts +6 -197
  128. package/src/postRepository/utils/payload.ts +17 -0
  129. package/src/utils/linkedObject/adLinkedObject.ts +11 -11
  130. package/src/utils/linkedObject/categoryLinkedObject.ts +6 -28
  131. package/src/utils/linkedObject/userLinkedObject.ts +8 -27
package/dist/index.esm.js CHANGED
@@ -31,7 +31,12 @@ const VideoSize = Object.freeze({
31
31
  MEDIUM: 'medium',
32
32
  HIGH: 'high',
33
33
  ORIGINAL: 'original',
34
- });
34
+ });
35
+ var FileAccessTypeEnum;
36
+ (function (FileAccessTypeEnum) {
37
+ FileAccessTypeEnum["PUBLIC"] = "public";
38
+ FileAccessTypeEnum["NETWORK"] = "network";
39
+ })(FileAccessTypeEnum || (FileAccessTypeEnum = {}));
35
40
 
36
41
  const CommunityPostSettings = Object.freeze({
37
42
  ONLY_ADMIN_CAN_POST: 'ONLY_ADMIN_CAN_POST',
@@ -82,8 +87,8 @@ const PostContentType = Object.freeze({
82
87
 
83
88
  function getVersion() {
84
89
  try {
85
- // the string ''v6.26.3-esm'' should be replaced by actual value by @rollup/plugin-replace
86
- return 'v6.26.3-esm';
90
+ // the string ''v6.27.0-esm'' should be replaced by actual value by @rollup/plugin-replace
91
+ return 'v6.27.0-esm';
87
92
  }
88
93
  catch (error) {
89
94
  return '__dev__';
@@ -491,7 +496,7 @@ const idResolvers = {
491
496
  channel: ({ channelInternalId }) => channelInternalId,
492
497
  subChannel: ({ subChannelId }) => subChannelId,
493
498
  channelUsers: ({ channelId, userId }) => `${channelId}#${userId}`,
494
- message: ({ messageId }) => messageId,
499
+ message: ({ messageId, referenceId }) => referenceId !== null && referenceId !== void 0 ? referenceId : messageId,
495
500
  messagePreviewChannel: ({ channelId }) => `${channelId}`,
496
501
  messagePreviewSubChannel: ({ subChannelId }) => `${subChannelId}`,
497
502
  channelUnreadInfo: ({ channelId }) => channelId,
@@ -1573,6 +1578,33 @@ const unwrapPayload = (response) => {
1573
1578
  return undefined;
1574
1579
  };
1575
1580
 
1581
+ class NetworkActivitiesWatcher {
1582
+ constructor() {
1583
+ this._listener = new Map();
1584
+ }
1585
+ onNetworkActivities(callback) {
1586
+ this._listener.set(callback, callback);
1587
+ return () => {
1588
+ this._listener.delete(callback);
1589
+ };
1590
+ }
1591
+ setNetworkActivities(request, response) {
1592
+ this._listener.forEach(cb => cb(request, response));
1593
+ }
1594
+ destroy() {
1595
+ this._listener.clear();
1596
+ }
1597
+ }
1598
+ let instance$5;
1599
+ var NetworkActivitiesWatcher$1 = {
1600
+ getInstance: () => {
1601
+ if (!instance$5) {
1602
+ instance$5 = new NetworkActivitiesWatcher();
1603
+ }
1604
+ return instance$5;
1605
+ },
1606
+ };
1607
+
1576
1608
  /*
1577
1609
  * Defined here as transport is a private module. Also, outside of this module
1578
1610
  * this enum holds no meaning.
@@ -1680,7 +1712,24 @@ const createHttpTransport = (endpoint) => {
1680
1712
  }
1681
1713
  return config;
1682
1714
  });
1683
- instance.interceptors.response.use(response => response, error => {
1715
+ instance.interceptors.response.use(response => {
1716
+ const headers = new Headers();
1717
+ Object.entries(response.headers).forEach(([key, value]) => {
1718
+ if (typeof value === 'string') {
1719
+ headers.append(key, value);
1720
+ }
1721
+ });
1722
+ NetworkActivitiesWatcher$1.getInstance().setNetworkActivities(new Request(response.request.url, {
1723
+ method: response.request.method,
1724
+ headers: response.request.headers,
1725
+ body: response.request.data,
1726
+ }), new Response(response.data, {
1727
+ status: response.status,
1728
+ statusText: response.statusText,
1729
+ headers,
1730
+ }));
1731
+ return response;
1732
+ }, error => {
1684
1733
  var _a, _b;
1685
1734
  const { response } = error;
1686
1735
  // handle unauthorized request
@@ -20742,6 +20791,19 @@ function __rest(s, e) {
20742
20791
  t[p[i]] = s[p[i]];
20743
20792
  }
20744
20793
  return t;
20794
+ }
20795
+
20796
+ function __classPrivateFieldGet(receiver, state, kind, f) {
20797
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
20798
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20799
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
20800
+ }
20801
+
20802
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
20803
+ if (kind === "m") throw new TypeError("Private method is not writable");
20804
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
20805
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
20806
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
20745
20807
  }
20746
20808
 
20747
20809
  /**
@@ -20948,12 +21010,12 @@ class AnalyticsEventCapturer {
20948
21010
  this._throttleStoryTimer = undefined;
20949
21011
  this._bufferNewSeenStoryReferenceIds = [];
20950
21012
  }
20951
- isAbleToEnqueue({ itemId, expireTime, isHighPriority = false, }) {
21013
+ isAbleToEnqueue({ uniqueId, expireTime, isHighPriority = false, }) {
20952
21014
  const now = new Date();
20953
21015
  const getRecentViewedDate = () => {
20954
21016
  if (isHighPriority)
20955
- return this._recentHighPriorityViewed[itemId];
20956
- return this._recentViewed[itemId];
21017
+ return this._recentHighPriorityViewed[uniqueId];
21018
+ return this._recentViewed[uniqueId];
20957
21019
  };
20958
21020
  const recentViewedDate = getRecentViewedDate() || new Date(DAY * -1);
20959
21021
  const timeDiff = now.getTime() - recentViewedDate.getTime();
@@ -20963,8 +21025,8 @@ class AnalyticsEventCapturer {
20963
21025
  }
20964
21026
  return true;
20965
21027
  }
20966
- markAs(itemId, contentType, activityType, metadata = undefined) {
20967
- if (!this.isAbleToEnqueue({ itemId, expireTime: this._expireTime }))
21028
+ markAs({ uniqueId, contentId, contentType, activityType, metadata, }) {
21029
+ if (!this.isAbleToEnqueue({ uniqueId, expireTime: this._expireTime }))
20968
21030
  return;
20969
21031
  const now = new Date();
20970
21032
  const currentData = { event: [] };
@@ -20978,7 +21040,7 @@ class AnalyticsEventCapturer {
20978
21040
  currentData.event.shift();
20979
21041
  }
20980
21042
  const analyticItem = {
20981
- contentId: itemId,
21043
+ contentId,
20982
21044
  contentType,
20983
21045
  activityType,
20984
21046
  timestamp: now.toISOString(),
@@ -20988,10 +21050,15 @@ class AnalyticsEventCapturer {
20988
21050
  }
20989
21051
  currentData.event.push(analyticItem);
20990
21052
  upsertInCache(ANALYTIC_CACHE_KEY, currentData);
20991
- this._recentViewed[itemId] = now;
21053
+ this._recentViewed[uniqueId] = now;
20992
21054
  }
20993
21055
  markPostAsViewed(postId) {
20994
- this.markAs(postId, "post" /* Amity.AnalyticEventContentType.Post */, "view" /* Amity.AnalyticEventActivityType.View */);
21056
+ this.markAs({
21057
+ uniqueId: postId,
21058
+ contentId: postId,
21059
+ contentType: "post" /* Amity.AnalyticEventContentType.Post */,
21060
+ activityType: "view" /* Amity.AnalyticEventActivityType.View */,
21061
+ });
20995
21062
  }
20996
21063
  markStory(story, activityType) {
20997
21064
  if (!story.expiresAt)
@@ -20999,7 +21066,7 @@ class AnalyticsEventCapturer {
20999
21066
  const now = new Date();
21000
21067
  const expireTime = new Date(story.expiresAt);
21001
21068
  if (!this.isAbleToEnqueue({
21002
- itemId: story.storyId,
21069
+ uniqueId: story.storyId,
21003
21070
  expireTime: expireTime.getTime(),
21004
21071
  isHighPriority: true,
21005
21072
  }))
@@ -21065,13 +21132,27 @@ class AnalyticsEventCapturer {
21065
21132
  const metadata = {
21066
21133
  placement,
21067
21134
  };
21068
- this.markAs(`${ad.adId}.${"view" /* Amity.AnalyticEventActivityType.View */}.${placement}`, "ad" /* Amity.AnalyticEventContentType.Ad */, "view" /* Amity.AnalyticEventActivityType.View */, metadata);
21135
+ const activityType = "view" /* Amity.AnalyticEventActivityType.View */;
21136
+ this.markAs({
21137
+ uniqueId: `${ad.adId}.${activityType}.${placement}`,
21138
+ contentId: ad.adId,
21139
+ contentType: "ad" /* Amity.AnalyticEventContentType.Ad */,
21140
+ activityType,
21141
+ metadata,
21142
+ });
21069
21143
  }
21070
21144
  markAdAsClicked(ad, placement) {
21071
21145
  const metadata = {
21072
21146
  placement,
21073
21147
  };
21074
- this.markAs(`${ad.adId}.${"view" /* Amity.AnalyticEventActivityType.View */}.${placement}`, "ad" /* Amity.AnalyticEventContentType.Ad */, "linkClicked" /* Amity.AnalyticEventActivityType.Click */, metadata);
21148
+ const activityType = "linkClicked" /* Amity.AnalyticEventActivityType.Click */;
21149
+ this.markAs({
21150
+ uniqueId: `${ad.adId}.${activityType}.${placement}`,
21151
+ contentId: ad.adId,
21152
+ contentType: "ad" /* Amity.AnalyticEventContentType.Ad */,
21153
+ activityType,
21154
+ metadata,
21155
+ });
21075
21156
  }
21076
21157
  }
21077
21158
 
@@ -21127,13 +21208,13 @@ class AnalyticsEngine {
21127
21208
  this._eventCapturer.resetAllBuckets();
21128
21209
  }
21129
21210
  }
21130
- let instance$3;
21211
+ let instance$4;
21131
21212
  var AnalyticsEngine$1 = {
21132
21213
  getInstance: () => {
21133
- if (!instance$3) {
21134
- instance$3 = new AnalyticsEngine();
21214
+ if (!instance$4) {
21215
+ instance$4 = new AnalyticsEngine();
21135
21216
  }
21136
- return instance$3;
21217
+ return instance$4;
21137
21218
  },
21138
21219
  };
21139
21220
 
@@ -21141,30 +21222,12 @@ const userLinkedObject = (user) => {
21141
21222
  return Object.assign(Object.assign({}, user), { get avatar() {
21142
21223
  var _a;
21143
21224
  if (!user.avatarFileId)
21144
- return null;
21145
- let avatar = {
21146
- fileId: ((_a = user.avatarFileId) === null || _a === void 0 ? void 0 : _a.toString()) ? user.avatarFileId.toString() : '',
21147
- type: 'image',
21148
- fileUrl: '',
21149
- createdAt: '',
21150
- attributes: {
21151
- name: '',
21152
- extension: '',
21153
- size: '',
21154
- mimeType: '',
21155
- metadata: {
21156
- exif: {},
21157
- gps: {},
21158
- width: 0,
21159
- height: 0,
21160
- isFull: false,
21161
- },
21162
- },
21163
- };
21164
- const cacheData = pullFromCache(['file', 'get', `${user.avatarFileId}`]);
21165
- if (cacheData === null || cacheData === void 0 ? void 0 : cacheData.data) {
21166
- avatar = cacheData === null || cacheData === void 0 ? void 0 : cacheData.data;
21167
- }
21225
+ return undefined;
21226
+ const avatar = (_a = pullFromCache([
21227
+ 'file',
21228
+ 'get',
21229
+ `${user.avatarFileId}`,
21230
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21168
21231
  return avatar;
21169
21232
  } });
21170
21233
  };
@@ -21379,34 +21442,12 @@ const categoryLinkedObject = (category) => {
21379
21442
  return Object.assign(Object.assign({}, category), { get avatar() {
21380
21443
  var _a;
21381
21444
  if (!category.avatarFileId)
21382
- return null;
21383
- let avatar = {
21384
- fileId: ((_a = category.avatarFileId) === null || _a === void 0 ? void 0 : _a.toString()) ? category.avatarFileId.toString() : '',
21385
- type: 'image',
21386
- fileUrl: '',
21387
- createdAt: '',
21388
- attributes: {
21389
- name: '',
21390
- extension: '',
21391
- size: '',
21392
- mimeType: '',
21393
- metadata: {
21394
- exif: {},
21395
- gps: {},
21396
- width: 0,
21397
- height: 0,
21398
- isFull: false,
21399
- },
21400
- },
21401
- };
21402
- const cacheData = pullFromCache([
21445
+ return undefined;
21446
+ const avatar = (_a = pullFromCache([
21403
21447
  'file',
21404
21448
  'get',
21405
21449
  `${category.avatarFileId}`,
21406
- ]);
21407
- if (cacheData === null || cacheData === void 0 ? void 0 : cacheData.data) {
21408
- avatar = cacheData === null || cacheData === void 0 ? void 0 : cacheData.data;
21409
- }
21450
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21410
21451
  return avatar;
21411
21452
  } });
21412
21453
  };
@@ -21764,12 +21805,12 @@ class MessageReadReceiptSyncEngine {
21764
21805
  }
21765
21806
  }
21766
21807
  }
21767
- let instance$2 = null;
21808
+ let instance$3 = null;
21768
21809
  var ReadReceiptSyncEngine = {
21769
21810
  getInstance: () => {
21770
- if (!instance$2)
21771
- instance$2 = new MessageReadReceiptSyncEngine();
21772
- return instance$2;
21811
+ if (!instance$3)
21812
+ instance$3 = new MessageReadReceiptSyncEngine();
21813
+ return instance$3;
21773
21814
  },
21774
21815
  };
21775
21816
 
@@ -21838,20 +21879,17 @@ const channelLinkedObject = (channel) => {
21838
21879
  return Object.assign(Object.assign({}, channel), { markAsRead: () => markAsRead(channel.channelInternalId) });
21839
21880
  };
21840
21881
 
21841
- // import AnalyticsEngine from '~/analytic/service/analytic/AnalyticsEngine';
21842
21882
  const adLinkedObject = (ad) => {
21843
- // const analyticsEngineInstance = AnalyticsEngine.getInstance();
21883
+ const analyticsEngineInstance = AnalyticsEngine$1.getInstance();
21844
21884
  const { image9_16: image916, image1_1: image11 } = ad, restAds = __rest(ad, ["image9_16", "image1_1"]);
21845
- return Object.assign(Object.assign({}, restAds), {
21846
- // analytics: {
21847
- // markAsSeen: (placement: Amity.AdPlacement) => {
21848
- // analyticsEngineInstance.markAdAsViewed(ad, placement);
21849
- // },
21850
- // markLinkAsClicked: (placement: Amity.AdPlacement) => {
21851
- // analyticsEngineInstance.markAdAsClicked(ad, placement);
21852
- // },
21853
- // },
21854
- get advertiser() {
21885
+ return Object.assign(Object.assign({}, restAds), { analytics: {
21886
+ markAsSeen: (placement) => {
21887
+ analyticsEngineInstance.markAdAsViewed(ad, placement);
21888
+ },
21889
+ markLinkAsClicked: (placement) => {
21890
+ analyticsEngineInstance.markAdAsClicked(ad, placement);
21891
+ },
21892
+ }, get advertiser() {
21855
21893
  var _a, _b;
21856
21894
  const advertiserData = (_a = pullFromCache([
21857
21895
  'advertiser',
@@ -22739,7 +22777,7 @@ function convertFromRaw(message, reactors, event) {
22739
22777
  *
22740
22778
  * Check git blame for previous iteration
22741
22779
  */
22742
- myReactions: myReactions || ((_a = cache === null || cache === void 0 ? void 0 : cache.data.myReactions) !== null && _a !== void 0 ? _a : []), reactionsCount: reactionCount, subChannelId: messageFeedId, uniqueId: cache ? cache.data.uniqueId : messageId, referenceId });
22780
+ myReactions: myReactions || ((_a = cache === null || cache === void 0 ? void 0 : cache.data.myReactions) !== null && _a !== void 0 ? _a : []), reactionsCount: reactionCount, subChannelId: messageFeedId, uniqueId: cache ? cache.data.uniqueId : messageId, referenceId, syncState: "synced" /* Amity.SyncState.Synced */ });
22743
22781
  if (mentionedUsers) {
22744
22782
  out.mentionees = mentionedUsers.map(mention => {
22745
22783
  if (mention.type === 'channel') {
@@ -22882,13 +22920,13 @@ class SessionWatcher {
22882
22920
  this._listener.clear();
22883
22921
  }
22884
22922
  }
22885
- let instance$1;
22923
+ let instance$2;
22886
22924
  var SessionWatcher$1 = {
22887
22925
  getInstance: () => {
22888
- if (!instance$1) {
22889
- instance$1 = new SessionWatcher();
22926
+ if (!instance$2) {
22927
+ instance$2 = new SessionWatcher();
22890
22928
  }
22891
- return instance$1;
22929
+ return instance$2;
22892
22930
  },
22893
22931
  };
22894
22932
 
@@ -23600,13 +23638,15 @@ const setSessionState = (state) => {
23600
23638
  * @category Client API
23601
23639
  * @hidden
23602
23640
  */
23603
- const getToken = async (params) => {
23641
+ const getToken = async ({ params, options, }) => {
23604
23642
  const client = getActiveClient();
23605
23643
  client.log('client/api/getToken', params);
23606
23644
  const deviceInfo = getDeviceInfo();
23607
23645
  const { data } = await client.http.post('/api/v5/sessions', Object.assign(Object.assign({}, params), { deviceInfo }), {
23608
- // @ts-ignore
23609
- headers: { 'X-API-Key': client.apiKey },
23646
+ headers: {
23647
+ 'X-API-Key': client.apiKey,
23648
+ 'set-access-token-cookie': (options === null || options === void 0 ? void 0 : options.setAccessTokenCookie) || false,
23649
+ },
23610
23650
  });
23611
23651
  return data;
23612
23652
  };
@@ -23918,12 +23958,12 @@ class ObjectResolverEngine {
23918
23958
  this.stopResolver();
23919
23959
  }
23920
23960
  }
23921
- let instance = null;
23961
+ let instance$1 = null;
23922
23962
  var ObjectResolverEngine$1 = {
23923
23963
  getInstance: () => {
23924
- if (!instance)
23925
- instance = new ObjectResolverEngine();
23926
- return instance;
23964
+ if (!instance$1)
23965
+ instance$1 = new ObjectResolverEngine();
23966
+ return instance$1;
23927
23967
  },
23928
23968
  };
23929
23969
 
@@ -23998,6 +24038,9 @@ const logout = async () => {
23998
24038
  isUserDeleted: false,
23999
24039
  };
24000
24040
  client.ws.io.opts.query = { token: '' };
24041
+ if (typeof document !== 'undefined') {
24042
+ document.cookie = '_ascSession=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
24043
+ }
24001
24044
  /*
24002
24045
  * Cache should be usable if tokenExpired
24003
24046
  * https://ekoapp.atlassian.net/wiki/spaces/UP/pages/2082537485/ASC+Core+-+Session+Management+3.0#SDK-usability-based-on-Session-State
@@ -24105,6 +24148,17 @@ const onClientBanned = (callback) => {
24105
24148
  return createEventSubscriber(client, `client/onConnectionError(user.didGlobalBan)`, 'user.didGlobalBan', callback);
24106
24149
  };
24107
24150
 
24151
+ /**
24152
+ *
24153
+ * Fired when any {@link Amity.Client} has a session state change
24154
+ *
24155
+ * @param callback The function to call when the event was fired
24156
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
24157
+ *
24158
+ * @category Client Events
24159
+ */
24160
+ const onNetworkActivities = (callback) => NetworkActivitiesWatcher$1.getInstance().onNetworkActivities(callback);
24161
+
24108
24162
  /**
24109
24163
  * ```js
24110
24164
  * import { onTokenExpired } from '@amityco/ts-sdk'
@@ -24539,9 +24593,12 @@ const onMessageCreatedMqtt = (callback) => {
24539
24593
  const onMessageCreatedLocal = (callback) => {
24540
24594
  const client = getActiveClient();
24541
24595
  const disposers = [
24542
- createEventSubscriber(client, 'message/onMessageCreated', 'local.message.created', payload => payload.messages.forEach(message => {
24543
- callback(message);
24544
- })),
24596
+ createEventSubscriber(client, 'message/onMessageCreated', 'local.message.created', async (payload) => {
24597
+ ingestInCache(payload);
24598
+ return payload.messages.forEach(message => {
24599
+ callback(message);
24600
+ });
24601
+ }),
24545
24602
  ];
24546
24603
  return () => {
24547
24604
  disposers.forEach(fn => fn());
@@ -24944,7 +25001,12 @@ const login = async (params, sessionHandler, config) => {
24944
25001
  // default values
24945
25002
  const defaultDeviceId = await getDeviceId();
24946
25003
  try {
24947
- const { users } = await setClientToken(Object.assign(Object.assign({}, params), { displayName: params === null || params === void 0 ? void 0 : params.displayName, deviceId: (params === null || params === void 0 ? void 0 : params.deviceId) || defaultDeviceId }));
25004
+ const { users } = await setClientToken({
25005
+ params: Object.assign(Object.assign({}, params), { displayName: params === null || params === void 0 ? void 0 : params.displayName, deviceId: (params === null || params === void 0 ? void 0 : params.deviceId) || defaultDeviceId }),
25006
+ options: {
25007
+ setAccessTokenCookie: true,
25008
+ },
25009
+ });
24948
25010
  const user = users.find(u => u.userId === params.userId);
24949
25011
  if (user == null) {
24950
25012
  throw new ASCError(`${params.userId} has not been founded`, 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
@@ -24975,7 +25037,7 @@ const login = async (params, sessionHandler, config) => {
24975
25037
  * if getting token failed session state reverts to initial state when app
24976
25038
  * is first launched
24977
25039
  */
24978
- setSessionState("notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */);
25040
+ SessionWatcher$1.getInstance().setSessionState("notLoggedIn" /* Amity.SessionStates.NOT_LOGGED_IN */);
24979
25041
  // pass error down tree so the calling function handle it
24980
25042
  throw error;
24981
25043
  }
@@ -25001,7 +25063,7 @@ const login = async (params, sessionHandler, config) => {
25001
25063
  unsubWatcher();
25002
25064
  }
25003
25065
  }), onTokenExpired(state => {
25004
- setSessionState(state);
25066
+ SessionWatcher$1.getInstance().setSessionState(state);
25005
25067
  logout();
25006
25068
  subscriptions.forEach(fn => fn());
25007
25069
  }),
@@ -25046,7 +25108,12 @@ const renewal = () => {
25046
25108
  }
25047
25109
  else {
25048
25110
  // about to expire
25049
- await setClientToken(params);
25111
+ await setClientToken({
25112
+ params,
25113
+ options: {
25114
+ setAccessTokenCookie: true,
25115
+ },
25116
+ });
25050
25117
  }
25051
25118
  tokenRenewed = true;
25052
25119
  if (renewTimeoutId)
@@ -25271,6 +25338,33 @@ const isConnected = () => {
25271
25338
  client.ws.connected);
25272
25339
  };
25273
25340
 
25341
+ var _GlobalFileAccessType_fileAccessType;
25342
+ class GlobalFileAccessType {
25343
+ constructor() {
25344
+ _GlobalFileAccessType_fileAccessType.set(this, FileAccessTypeEnum.PUBLIC);
25345
+ }
25346
+ setFileAccessType(fileAccessType) {
25347
+ __classPrivateFieldSet(this, _GlobalFileAccessType_fileAccessType, fileAccessType, "f");
25348
+ }
25349
+ getFileAccessType() {
25350
+ return __classPrivateFieldGet(this, _GlobalFileAccessType_fileAccessType, "f");
25351
+ }
25352
+ }
25353
+ _GlobalFileAccessType_fileAccessType = new WeakMap();
25354
+ let instance;
25355
+ var GlobalFileAccessType$1 = {
25356
+ getInstance: () => {
25357
+ if (!instance) {
25358
+ instance = new GlobalFileAccessType();
25359
+ }
25360
+ return instance;
25361
+ },
25362
+ };
25363
+
25364
+ function setUploadedFileAccessType(accessType) {
25365
+ GlobalFileAccessType$1.getInstance().setFileAccessType(accessType);
25366
+ }
25367
+
25274
25368
  /**
25275
25369
  * ```js
25276
25370
  * import { onChannelMarkerFetched } from '@amityco/ts-sdk'
@@ -25801,10 +25895,12 @@ var index$l = /*#__PURE__*/Object.freeze({
25801
25895
  renewal: renewal,
25802
25896
  markerSync: markerSync,
25803
25897
  enableUnreadCount: enableUnreadCount,
25898
+ setUploadedFileAccessType: setUploadedFileAccessType,
25804
25899
  onConnectionError: onConnectionError,
25805
25900
  onClientDisconnected: onClientDisconnected,
25806
25901
  onClientBanned: onClientBanned,
25807
25902
  onSessionStateChange: onSessionStateChange,
25903
+ onNetworkActivities: onNetworkActivities,
25808
25904
  getTotalUnreadCount: getTotalUnreadCount,
25809
25905
  getUserUnread: getUserUnread,
25810
25906
  getMarkerSyncEvents: getMarkerSyncEvents,
@@ -27940,6 +28036,8 @@ const uploadFile = async (formData, onProgress) => {
27940
28036
  const files = formData.getAll('files');
27941
28037
  if (!files.length)
27942
28038
  throw new Error('The formData object must have a `files` key.');
28039
+ const accessType = GlobalFileAccessType$1.getInstance().getFileAccessType();
28040
+ formData.append('accessType', accessType);
27943
28041
  formData.append('preferredFilename', files[0].name);
27944
28042
  const headers = 'getHeaders' in formData
27945
28043
  ? formData.getHeaders()
@@ -28025,6 +28123,8 @@ const uploadVideo = async (formData, feedType, onProgress) => {
28025
28123
  const files = formData.getAll('files');
28026
28124
  if (!files.length)
28027
28125
  throw new Error('The formData object must have a `files` key.');
28126
+ const accessType = GlobalFileAccessType$1.getInstance().getFileAccessType();
28127
+ formData.append('accessType', accessType);
28028
28128
  formData.append('preferredFilename', files[0].name);
28029
28129
  if (feedType) {
28030
28130
  formData.append('feedType', feedType);
@@ -28074,6 +28174,8 @@ const uploadImage = async (formData, onProgress) => {
28074
28174
  const files = formData.getAll('files');
28075
28175
  if (!files.length)
28076
28176
  throw new Error('The formData object must have a `files` key.');
28177
+ const accessType = GlobalFileAccessType$1.getInstance().getFileAccessType();
28178
+ formData.append('accessType', accessType);
28077
28179
  formData.append('preferredFilename', files[0].name);
28078
28180
  const headers = 'getHeaders' in formData
28079
28181
  ? formData.getHeaders()
@@ -28117,6 +28219,8 @@ const createImage = async (formData, onProgress) => {
28117
28219
  const files = formData.getAll('files');
28118
28220
  if (!files.length)
28119
28221
  throw new Error('The formData object must have a `files` key.');
28222
+ const accessType = GlobalFileAccessType$1.getInstance().getFileAccessType();
28223
+ formData.append('accessType', accessType);
28120
28224
  formData.append('preferredFilename', files[0].name);
28121
28225
  const headers = 'getHeaders' in formData
28122
28226
  ? formData.getHeaders()
@@ -28160,6 +28264,8 @@ const createFile = async (formData, onProgress) => {
28160
28264
  const files = formData.getAll('files');
28161
28265
  if (!files.length)
28162
28266
  throw new Error('The formData object must have a `files` key.');
28267
+ const accessType = GlobalFileAccessType$1.getInstance().getFileAccessType();
28268
+ formData.append('accessType', accessType);
28163
28269
  formData.append('preferredFilename', files[0].name);
28164
28270
  const headers = 'getHeaders' in formData
28165
28271
  ? formData.getHeaders()
@@ -28203,6 +28309,8 @@ const createVideo = async (formData, feedType, onProgress) => {
28203
28309
  const files = formData.getAll('files');
28204
28310
  if (!files.length)
28205
28311
  throw new Error('The formData object must have a `files` key.');
28312
+ const accessType = GlobalFileAccessType$1.getInstance().getFileAccessType();
28313
+ formData.append('accessType', accessType);
28206
28314
  formData.append('preferredFilename', files[0].name);
28207
28315
  if (feedType) {
28208
28316
  formData.append('feedType', feedType);
@@ -28504,7 +28612,7 @@ getMessage$2.locally = (messageId) => {
28504
28612
  * @category Post API
28505
28613
  * @async
28506
28614
  */
28507
- const getPost$1 = async (postId) => {
28615
+ const getPost$2 = async (postId) => {
28508
28616
  const client = getActiveClient();
28509
28617
  client.log('post/getPost', postId);
28510
28618
  isInTombstone('post', postId);
@@ -28544,7 +28652,7 @@ const getPost$1 = async (postId) => {
28544
28652
  *
28545
28653
  * @category Post API
28546
28654
  */
28547
- getPost$1.locally = (postId) => {
28655
+ getPost$2.locally = (postId) => {
28548
28656
  const client = getActiveClient();
28549
28657
  client.log('post/getPost.locally', postId);
28550
28658
  if (!client.cache)
@@ -30585,9 +30693,40 @@ getMessages$1.locally = (messageIds) => {
30585
30693
  const getLocalId = () => `LOCAL_${uuid()}`;
30586
30694
  // FIXME: temp solution
30587
30695
  let uniqueId;
30588
- /* begin_public_function
30589
- id: message.create.text_message, message.create.image_message, message.create.file_message, message.create.video_message, message.create.audio_message, message.create.custom_message
30590
- */
30696
+ const createMessageOptimistic = (bundle) => {
30697
+ var _a, _b;
30698
+ const client = getActiveClient();
30699
+ if (!client.cache)
30700
+ return;
30701
+ /*
30702
+ * When creating messages optimistically a messageId needs to be added by the
30703
+ * client, created a new variable to allow backward compatibility of API
30704
+ *
30705
+ * Updated to handle client requirement to add messageId while uploading
30706
+ * a message with image.
30707
+ * Temporary!
30708
+ */
30709
+ uniqueId = bundle.referenceId || getLocalId();
30710
+ const bundleWithMessageId = Object.assign({ messageId: uniqueId, uniqueId }, bundle);
30711
+ client.log('message/createMessage.optimistically', bundleWithMessageId);
30712
+ const subChannel = pullFromCache(['subChannel', 'get', bundle.subChannelId]);
30713
+ if (subChannel) {
30714
+ upsertInCache(['subChannel', 'get', bundle.subChannelId], Object.assign(Object.assign({}, subChannel.data), { messageCount: subChannel.data.messageCount + 1 }));
30715
+ if (subChannel.data.channelId === subChannel.data.subChannelId) {
30716
+ const channel = pullFromCache(['channel', 'get', subChannel.data.channelId]);
30717
+ if (channel === null || channel === void 0 ? void 0 : channel.data) {
30718
+ upsertInCache(['channel', 'get', subChannel.data.channelId], Object.assign(Object.assign({}, channel.data), { messageCount: ((_a = channel.data.messageCount) !== null && _a !== void 0 ? _a : 0) + 1 }));
30719
+ }
30720
+ }
30721
+ }
30722
+ // as reused to update created and updated time, which should be the same
30723
+ const createdTime = new Date().toISOString();
30724
+ const message = Object.assign({ creatorId: client.userId, creatorPrivateId: getActiveUser()._id, channelSegment: ((_b = subChannel === null || subChannel === void 0 ? void 0 : subChannel.data.messageCount) !== null && _b !== void 0 ? _b : 0) + 1, childrenNumber: 0, createdAt: createdTime, updatedAt: createdTime, syncState: "syncing" /* Amity.SyncState.Syncing */, isDeleted: false }, bundleWithMessageId);
30725
+ const cachedAt = UNSYNCED_OBJECT_CACHED_AT_VALUE;
30726
+ pushToCache(['message', 'get', message.messageId], message, { cachedAt });
30727
+ fireEvent('local.message.created', { messages: [message] });
30728
+ return message;
30729
+ };
30591
30730
  /**
30592
30731
  * ```js
30593
30732
  * import { createMessage, createQuery, runQuery } from '@amityco/ts-sdk'
@@ -30613,75 +30752,31 @@ let uniqueId;
30613
30752
  const createMessage = async (bundle) => {
30614
30753
  const client = getActiveClient();
30615
30754
  client.log('message/createMessage', bundle);
30755
+ const optimisticData = createMessageOptimistic(bundle);
30616
30756
  const referenceId = bundle.referenceId || uniqueId || getLocalId();
30617
30757
  uniqueId = undefined;
30618
- const { data: payload } = await client.http.post('/api/v5/messages', Object.assign(Object.assign({}, convertParams(bundle)), { referenceId }));
30619
- const data = await prepareMessagePayload(payload);
30620
- const { messages } = data;
30621
- const cachedAt = client.cache && Date.now();
30622
- if (client.cache) {
30623
- dropFromCache(['message', 'get', referenceId]);
30624
- ingestInCache(data, { cachedAt });
30625
- }
30626
- fireEvent('local.message.created', { messages });
30627
- return {
30628
- data: LinkedObject.message(messages[0]),
30629
- cachedAt,
30630
- };
30631
- };
30632
- /**
30633
- * ```js
30634
- * import { createMessage } from '@amityco/ts-sdk'
30635
- *
30636
- * const created = createMessage.optimistically({
30637
- * channelId: 'foobar',
30638
- * data: { text: 'hello world' }
30639
- * })
30640
- * ```
30641
- *
30642
- * Creates an {@link Amity.Message} in cache
30643
- *
30644
- * @param bundle The data necessary to create a new {@link Amity.Message}
30645
- * @returns The newly created {@link Amity.Message}
30646
- *
30647
- * @category Message API
30648
- */
30649
- createMessage.optimistically = (_a) => {
30650
- var _b, _c;
30651
- var { referenceId } = _a, bundle = __rest(_a, ["referenceId"]);
30652
- const client = getActiveClient();
30653
- if (!client.cache)
30654
- return;
30655
- /*
30656
- * when creating messages optimistically a messageId needs to be added by the
30657
- * client, created a new variable so as to allow backward compatibility of API
30658
- *
30659
- * Updated to handle client requirement to add messageId while uploading
30660
- * message with image. Temporary!
30661
- */
30662
- uniqueId = referenceId || getLocalId();
30663
- const bundleWithMessageId = Object.assign({ messageId: uniqueId, uniqueId }, bundle);
30664
- client.log('message/createMessage.optimistically', bundleWithMessageId);
30665
- const subChannel = pullFromCache(['subChannel', 'get', bundle.subChannelId]);
30666
- if (subChannel) {
30667
- upsertInCache(['subChannel', 'get', bundle.subChannelId], Object.assign(Object.assign({}, subChannel.data), { messageCount: subChannel.data.messageCount + 1 }));
30668
- if (subChannel.data.channelId === subChannel.data.subChannelId) {
30669
- const channel = pullFromCache(['channel', 'get', subChannel.data.channelId]);
30670
- if (channel === null || channel === void 0 ? void 0 : channel.data) {
30671
- upsertInCache(['channel', 'get', subChannel.data.channelId], Object.assign(Object.assign({}, channel.data), { messageCount: ((_b = channel.data.messageCount) !== null && _b !== void 0 ? _b : 0) + 1 }));
30672
- }
30758
+ try {
30759
+ const { data: payload } = await client.http.post('/api/v5/messages', Object.assign(Object.assign({}, convertParams(bundle)), { referenceId }));
30760
+ const data = await prepareMessagePayload(payload);
30761
+ const { messages } = data;
30762
+ const cachedAt = client.cache && Date.now();
30763
+ if (client.cache) {
30764
+ ingestInCache(data, { cachedAt });
30673
30765
  }
30766
+ fireEvent('local.message.created', {
30767
+ messages: [Object.assign(Object.assign({}, messages[0]), { syncState: "synced" /* Amity.SyncState.Synced */ })],
30768
+ });
30769
+ return {
30770
+ data: LinkedObject.message(messages[0]),
30771
+ cachedAt,
30772
+ };
30773
+ }
30774
+ catch (e) {
30775
+ fireEvent('local.message.created', {
30776
+ messages: [Object.assign(Object.assign({}, optimisticData), { syncState: "error" /* Amity.SyncState.Error */ })],
30777
+ });
30778
+ throw e;
30674
30779
  }
30675
- // as reused to update created and updated time, which should be the same
30676
- const createdTime = new Date().toISOString();
30677
- const message = Object.assign({ creatorId: client.userId, creatorPrivateId: getActiveUser()._id, channelSegment: ((_c = subChannel === null || subChannel === void 0 ? void 0 : subChannel.data.messageCount) !== null && _c !== void 0 ? _c : 0) + 1, childrenNumber: 0, createdAt: createdTime, updatedAt: createdTime }, bundleWithMessageId);
30678
- const cachedAt = UNSYNCED_OBJECT_CACHED_AT_VALUE;
30679
- pushToCache(['message', 'get', message.messageId], message, { cachedAt });
30680
- fireEvent('local.message.created', { messages: [message] });
30681
- return {
30682
- cachedAt,
30683
- data: LinkedObject.message(message),
30684
- };
30685
30780
  };
30686
30781
  /* end_public_function */
30687
30782
 
@@ -31394,67 +31489,106 @@ const getMessage$1 = (messageId, callback) => {
31394
31489
  };
31395
31490
  /* end_public_function */
31396
31491
 
31397
- class PaginationController {
31492
+ class PaginationNoPageController {
31398
31493
  constructor(queryParams) {
31399
31494
  const { http } = getActiveClient();
31400
31495
  this.queryParams = queryParams;
31401
31496
  this.http = http;
31402
31497
  }
31403
- loadFirstPage() {
31404
- return this.onFetch("first" /* Amity.LiveCollectionPageDirection.FIRST */);
31498
+ async onFetch() {
31499
+ const queryResponse = await this.getRequest(this.queryParams);
31500
+ return queryResponse;
31405
31501
  }
31406
- loadNextPage() {
31407
- return this.onFetch("next" /* Amity.LiveCollectionPageDirection.NEXT */);
31502
+ }
31503
+
31504
+ class LiveCollectionController {
31505
+ constructor(paginationController, queryStreamId, cacheKey, callback) {
31506
+ this.paginationController = paginationController;
31507
+ this.queryStreamId = queryStreamId;
31508
+ this.cacheKey = cacheKey;
31509
+ this.callback = callback;
31408
31510
  }
31409
- loadPreviousPage() {
31410
- return this.onFetch("prev" /* Amity.LiveCollectionPageDirection.PREV */);
31511
+ async refresh() {
31512
+ try {
31513
+ let result;
31514
+ if (this.paginationController instanceof PaginationNoPageController) {
31515
+ result = await this.paginationController.onFetch();
31516
+ }
31517
+ else {
31518
+ result = await this.paginationController.loadFirstPage();
31519
+ }
31520
+ if (!result)
31521
+ return;
31522
+ await this.persistModel(result);
31523
+ this.persistQueryStream({
31524
+ response: result,
31525
+ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
31526
+ refresh: true,
31527
+ });
31528
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
31529
+ }
31530
+ catch (e) {
31531
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
31532
+ }
31411
31533
  }
31412
- async onFetch(direction = "first" /* Amity.LiveCollectionPageDirection.FIRST */) {
31413
- var _a, _b, _c, _d;
31414
- if (direction === 'prev' && !this.previousToken)
31415
- return;
31416
- if (direction === 'next' && !this.nextToken)
31417
- return;
31418
- let token;
31419
- if (direction === 'prev')
31420
- token = this.previousToken;
31421
- if (direction === 'next')
31422
- token = this.nextToken;
31423
- const queryResponse = await this.getRequest(this.queryParams, token);
31424
- if (direction === 'first') {
31425
- this.nextToken = (_a = queryResponse.paging) === null || _a === void 0 ? void 0 : _a.next;
31426
- this.previousToken = (_b = queryResponse.paging) === null || _b === void 0 ? void 0 : _b.previous;
31534
+ loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
31535
+ this.setup();
31536
+ this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
31537
+ if (initial) {
31538
+ this.refresh();
31539
+ }
31540
+ else if (direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */) {
31541
+ this.loadPrevPage();
31542
+ }
31543
+ else if (direction === "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
31544
+ this.loadNextPage();
31427
31545
  }
31428
- if (direction === 'prev')
31429
- this.previousToken = (_c = queryResponse.paging) === null || _c === void 0 ? void 0 : _c.previous;
31430
- if (direction === 'next')
31431
- this.nextToken = (_d = queryResponse.paging) === null || _d === void 0 ? void 0 : _d.next;
31432
- return queryResponse;
31433
31546
  }
31434
- getNextToken() {
31435
- return this.nextToken;
31547
+ async loadNextPage() {
31548
+ try {
31549
+ if (this.paginationController instanceof PaginationNoPageController)
31550
+ return;
31551
+ const result = await this.paginationController.loadNextPage();
31552
+ if (!result)
31553
+ return;
31554
+ await this.persistModel(result);
31555
+ this.persistQueryStream({
31556
+ response: result,
31557
+ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
31558
+ });
31559
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
31560
+ }
31561
+ catch (e) {
31562
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
31563
+ }
31436
31564
  }
31437
- getPrevToken() {
31438
- return this.previousToken;
31565
+ async loadPrevPage() {
31566
+ try {
31567
+ if (this.paginationController instanceof PaginationNoPageController)
31568
+ return;
31569
+ const result = await this.paginationController.loadPreviousPage();
31570
+ if (!result)
31571
+ return;
31572
+ await this.persistModel(result);
31573
+ this.persistQueryStream({
31574
+ response: result,
31575
+ direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */,
31576
+ });
31577
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
31578
+ }
31579
+ catch (e) {
31580
+ this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
31581
+ }
31439
31582
  }
31440
- }
31441
-
31442
- /* eslint-disable no-use-before-define */
31443
- /**
31444
- * TODO: handle cache receive cache option, and cache policy
31445
- * TODO: check if querybyIds is supported
31446
- */
31447
- class MessagePaginationController extends PaginationController {
31448
- async getRequest(queryParams, token) {
31449
- const processedQueryParams = convertQueryParams$1(queryParams);
31450
- const { data: queryResponse } = await this.http.get(`/api/v5/messages`, {
31451
- params: Object.assign(Object.assign({}, processedQueryParams), { options: token
31452
- ? {
31453
- token,
31454
- }
31455
- : Object.assign({}, processedQueryParams.options) }),
31456
- });
31457
- return queryResponse;
31583
+ shouldNotify(data) {
31584
+ const newData = data.map(convertGetterPropsToStatic).map(removeFunctionProperties);
31585
+ if (isEqual(this.snapshot, newData))
31586
+ return false;
31587
+ this.snapshot = newData;
31588
+ return true;
31589
+ }
31590
+ getCacheKey() {
31591
+ return this.cacheKey;
31458
31592
  }
31459
31593
  }
31460
31594
 
@@ -31502,6 +31636,7 @@ class MessageQueryStreamController extends QueryStreamController {
31502
31636
  var _a, _b, _c, _d, _e;
31503
31637
  if (action === 'onCreate') {
31504
31638
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
31639
+ const { referenceId } = payload;
31505
31640
  if (!collection)
31506
31641
  return;
31507
31642
  if (this.query.subChannelId !== (payload === null || payload === void 0 ? void 0 : payload.subChannelId) || !collection)
@@ -31531,10 +31666,10 @@ class MessageQueryStreamController extends QueryStreamController {
31531
31666
  return;
31532
31667
  if ((!this.query.sortBy || this.query.sortBy === 'segmentDesc') &&
31533
31668
  !this.paginationController.getPrevToken()) {
31534
- collection.data = [...new Set([payload.messageId, ...collection.data])];
31669
+ collection.data = [...new Set([referenceId !== null && referenceId !== void 0 ? referenceId : payload.messageId, ...collection.data])];
31535
31670
  }
31536
31671
  if (this.query.sortBy === 'segmentAsc' && !this.paginationController.getNextToken()) {
31537
- collection.data = [...new Set([...collection.data, payload.messageId])];
31672
+ collection.data = [...new Set([...collection.data, referenceId !== null && referenceId !== void 0 ? referenceId : payload.messageId])];
31538
31673
  }
31539
31674
  pushToCache(this.cacheKey, collection);
31540
31675
  }
@@ -31546,106 +31681,67 @@ class MessageQueryStreamController extends QueryStreamController {
31546
31681
  }
31547
31682
  }
31548
31683
 
31549
- class PaginationNoPageController {
31684
+ class PaginationController {
31550
31685
  constructor(queryParams) {
31551
31686
  const { http } = getActiveClient();
31552
31687
  this.queryParams = queryParams;
31553
31688
  this.http = http;
31554
31689
  }
31555
- async onFetch() {
31556
- const queryResponse = await this.getRequest(this.queryParams);
31557
- return queryResponse;
31558
- }
31559
- }
31560
-
31561
- class LiveCollectionController {
31562
- constructor(paginationController, queryStreamId, cacheKey, callback) {
31563
- this.paginationController = paginationController;
31564
- this.queryStreamId = queryStreamId;
31565
- this.cacheKey = cacheKey;
31566
- this.callback = callback;
31690
+ loadFirstPage() {
31691
+ return this.onFetch("first" /* Amity.LiveCollectionPageDirection.FIRST */);
31567
31692
  }
31568
- async refresh() {
31569
- try {
31570
- let result;
31571
- if (this.paginationController instanceof PaginationNoPageController) {
31572
- result = await this.paginationController.onFetch();
31573
- }
31574
- else {
31575
- result = await this.paginationController.loadFirstPage();
31576
- }
31577
- if (!result)
31578
- return;
31579
- await this.persistModel(result);
31580
- this.persistQueryStream({
31581
- response: result,
31582
- direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
31583
- refresh: true,
31584
- });
31585
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
31586
- }
31587
- catch (e) {
31588
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
31589
- }
31693
+ loadNextPage() {
31694
+ return this.onFetch("next" /* Amity.LiveCollectionPageDirection.NEXT */);
31590
31695
  }
31591
- loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
31592
- this.setup();
31593
- this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
31594
- if (initial) {
31595
- this.refresh();
31596
- }
31597
- else if (direction === "prev" /* Amity.LiveCollectionPageDirection.PREV */) {
31598
- this.loadPrevPage();
31599
- }
31600
- else if (direction === "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
31601
- this.loadNextPage();
31602
- }
31696
+ loadPreviousPage() {
31697
+ return this.onFetch("prev" /* Amity.LiveCollectionPageDirection.PREV */);
31603
31698
  }
31604
- async loadNextPage() {
31605
- try {
31606
- if (this.paginationController instanceof PaginationNoPageController)
31607
- return;
31608
- const result = await this.paginationController.loadNextPage();
31609
- if (!result)
31610
- return;
31611
- await this.persistModel(result);
31612
- this.persistQueryStream({
31613
- response: result,
31614
- direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */,
31615
- });
31616
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
31617
- }
31618
- catch (e) {
31619
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
31699
+ async onFetch(direction = "first" /* Amity.LiveCollectionPageDirection.FIRST */) {
31700
+ var _a, _b, _c, _d;
31701
+ if (direction === 'prev' && !this.previousToken)
31702
+ return;
31703
+ if (direction === 'next' && !this.nextToken)
31704
+ return;
31705
+ let token;
31706
+ if (direction === 'prev')
31707
+ token = this.previousToken;
31708
+ if (direction === 'next')
31709
+ token = this.nextToken;
31710
+ const queryResponse = await this.getRequest(this.queryParams, token);
31711
+ if (direction === 'first') {
31712
+ this.nextToken = (_a = queryResponse.paging) === null || _a === void 0 ? void 0 : _a.next;
31713
+ this.previousToken = (_b = queryResponse.paging) === null || _b === void 0 ? void 0 : _b.previous;
31620
31714
  }
31715
+ if (direction === 'prev')
31716
+ this.previousToken = (_c = queryResponse.paging) === null || _c === void 0 ? void 0 : _c.previous;
31717
+ if (direction === 'next')
31718
+ this.nextToken = (_d = queryResponse.paging) === null || _d === void 0 ? void 0 : _d.next;
31719
+ return queryResponse;
31621
31720
  }
31622
- async loadPrevPage() {
31623
- try {
31624
- if (this.paginationController instanceof PaginationNoPageController)
31625
- return;
31626
- const result = await this.paginationController.loadPreviousPage();
31627
- if (!result)
31628
- return;
31629
- await this.persistModel(result);
31630
- this.persistQueryStream({
31631
- response: result,
31632
- direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */,
31633
- });
31634
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false });
31635
- }
31636
- catch (e) {
31637
- this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
31638
- }
31721
+ getNextToken() {
31722
+ return this.nextToken;
31639
31723
  }
31640
- shouldNotify(data) {
31641
- const newData = data.map(convertGetterPropsToStatic).map(removeFunctionProperties);
31642
- if (isEqual(this.snapshot, newData))
31643
- return false;
31644
- this.snapshot = newData;
31645
- return true;
31724
+ getPrevToken() {
31725
+ return this.previousToken;
31646
31726
  }
31647
- getCacheKey() {
31648
- return this.cacheKey;
31727
+ }
31728
+
31729
+ /* eslint-disable no-use-before-define */
31730
+ /**
31731
+ * TODO: handle cache receive cache option, and cache policy
31732
+ * TODO: check if querybyIds is supported
31733
+ */
31734
+ class MessagePaginationController extends PaginationController {
31735
+ async getRequest(queryParams, token) {
31736
+ const processedQueryParams = convertQueryParams$1(queryParams);
31737
+ const { data: queryResponse } = await this.http.get(`/api/v5/messages`, {
31738
+ params: Object.assign(Object.assign({}, processedQueryParams), { options: token
31739
+ ? {
31740
+ token,
31741
+ }
31742
+ : Object.assign({}, processedQueryParams.options) }),
31743
+ });
31744
+ return queryResponse;
31649
31745
  }
31650
31746
  }
31651
31747
 
@@ -31660,25 +31756,10 @@ class MessageLiveCollectionController extends LiveCollectionController {
31660
31756
  this.callback = callback.bind(this);
31661
31757
  this.loadPage({ initial: true });
31662
31758
  }
31663
- setup() {
31664
- var _a;
31665
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
31666
- if (!collection) {
31667
- pushToCache(this.cacheKey, {
31668
- data: [],
31669
- query: this.query,
31670
- });
31671
- }
31672
- }
31673
- async persistModel(response) {
31674
- await this.queryStreamController.saveToMainDB(response);
31675
- }
31676
- persistQueryStream({ response, direction, refresh, }) {
31677
- this.queryStreamController.appendToQueryStream(response, direction, refresh);
31678
- }
31679
31759
  startSubscription() {
31680
31760
  return this.queryStreamController.subscribeRTE([
31681
31761
  { fn: onMessageCreatedMqtt, action: 'onCreate' },
31762
+ { fn: onMessageCreatedLocal, action: 'onCreate' },
31682
31763
  { fn: onMessageDeleted, action: 'onDelete' },
31683
31764
  { fn: onMessageUpdated, action: 'onUpdate' },
31684
31765
  { fn: onMessageFlagged, action: 'onFlagged' },
@@ -31755,6 +31836,22 @@ class MessageLiveCollectionController extends LiveCollectionController {
31755
31836
  });
31756
31837
  return messages;
31757
31838
  }
31839
+ setup() {
31840
+ var _a;
31841
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
31842
+ if (!collection) {
31843
+ pushToCache(this.cacheKey, {
31844
+ data: [],
31845
+ query: this.query,
31846
+ });
31847
+ }
31848
+ }
31849
+ async persistModel(response) {
31850
+ await this.queryStreamController.saveToMainDB(response);
31851
+ }
31852
+ persistQueryStream({ response, direction, refresh, }) {
31853
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
31854
+ }
31758
31855
  }
31759
31856
 
31760
31857
  /* eslint-disable no-use-before-define */
@@ -33955,7 +34052,7 @@ const convertCommunityUsersToUniqueObject = (communityUsers) => {
33955
34052
  });
33956
34053
  return result;
33957
34054
  };
33958
- const prepareCommunityPayload = (rawPayload) => {
34055
+ const convertCommunityPayload = (rawPayload) => {
33959
34056
  // Unpack community payload by mapping payload field to postSetting value.
33960
34057
  const communities = rawPayload.communities.map((_a) => {
33961
34058
  var { needApprovalOnPostCreation, onlyAdminCanPost } = _a, restCommunityPayload = __rest(_a, ["needApprovalOnPostCreation", "onlyAdminCanPost"]);
@@ -33979,6 +34076,11 @@ const prepareCommunityPayload = (rawPayload) => {
33979
34076
  const communityWithMembershipStatus = updateMembershipStatus(communities, communityUsers);
33980
34077
  return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers });
33981
34078
  };
34079
+ const prepareCommunityPayload = (rawPayload) => {
34080
+ const { communities, communityUsers } = convertCommunityPayload(rawPayload);
34081
+ return Object.assign(Object.assign({}, rawPayload), { communities,
34082
+ communityUsers });
34083
+ };
33982
34084
  const prepareCommunityRequest = (params) => {
33983
34085
  const { postSetting = undefined, storySetting } = params, restParam = __rest(params, ["postSetting", "storySetting"]);
33984
34086
  return Object.assign(Object.assign(Object.assign({}, restParam), (postSetting ? CommunityPostSettingMaps[postSetting] : undefined)), {
@@ -36711,7 +36813,7 @@ const editPost = async (postId, patch) => {
36711
36813
  const deletePost = async (postId, permanent = false) => {
36712
36814
  var _a;
36713
36815
  const client = getActiveClient();
36714
- const post = await getPost$1(postId);
36816
+ const post = await getPost$2(postId);
36715
36817
  await client.http.delete(`/api/v4/posts/${encodeURIComponent(postId)}`, {
36716
36818
  params: {
36717
36819
  postId,
@@ -37050,7 +37152,7 @@ const observePost = (postId, callback, policy = 'cache_then_server') => {
37050
37152
  };
37051
37153
  const disposers = [];
37052
37154
  disposers.push(onPostUpdated(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUpdate')), onPostDeleted(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onDelete')), onPostApproved(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onApproved')), onPostDeclined(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onDeclined')), onPostFlagged(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onFlagged')), onPostUnflagged(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUnflagged')), onPostReactionAdded(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onReactionAdded')), onPostReactionRemoved(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onReactionRemoved')));
37053
- runQuery(createQuery(getPost$1, postId), result => (result.data || result.error) &&
37155
+ runQuery(createQuery(getPost$2, postId), result => (result.data || result.error) &&
37054
37156
  router(Object.assign(Object.assign({}, result), { data: result.data && LinkedObject.post(result.data) }), 'onFetch'), queryOptions(policy));
37055
37157
  return () => {
37056
37158
  log(`observePosts(tmpid: ${timestamp}) > dispose`);
@@ -37165,7 +37267,7 @@ const createComment = async (bundle) => {
37165
37267
  if (client.cache)
37166
37268
  ingestInCache(data, { cachedAt });
37167
37269
  if (['post', 'content'].includes(bundle.referenceType)) {
37168
- const post = await getPost$1(bundle.referenceId);
37270
+ const post = await getPost$2(bundle.referenceId);
37169
37271
  fireEvent('local.post.updated', {
37170
37272
  posts: [post.data],
37171
37273
  categories: [],
@@ -37359,7 +37461,7 @@ const deleteComment = async (commentId, permanent = false) => {
37359
37461
  });
37360
37462
  }
37361
37463
  else {
37362
- const post = await getPost$1(comment.data.referenceId);
37464
+ const post = await getPost$2(comment.data.referenceId);
37363
37465
  fireEvent('local.post.updated', {
37364
37466
  posts: [post.data],
37365
37467
  categories: [],
@@ -37963,8 +38065,12 @@ var index$6 = /*#__PURE__*/Object.freeze({
37963
38065
  *
37964
38066
  * @category Post Live Object
37965
38067
  */
37966
- const getPost = (postId, callback) => {
37967
- return liveObject(postId, callback, 'postId', getPost$1, [
38068
+ const getPost$1 = (postId, callback) => {
38069
+ const responder = (snapshot) => {
38070
+ const { data } = snapshot;
38071
+ callback(Object.assign(Object.assign({}, snapshot), { data: data ? LinkedObject.post(snapshot.data) : data }));
38072
+ };
38073
+ return liveObject(postId, responder, 'postId', getPost$2, [
37968
38074
  onPostApproved,
37969
38075
  onPostDeclined,
37970
38076
  (callback) => {
@@ -38004,7 +38110,7 @@ const getPost = (postId, callback) => {
38004
38110
  convertEventPayload((callback) => {
38005
38111
  return onCommentCreated(async (comment) => {
38006
38112
  if (comment.referenceId === postId) {
38007
- await getPost$1(postId);
38113
+ await getPost$2(postId);
38008
38114
  callback(comment);
38009
38115
  }
38010
38116
  });
@@ -38012,7 +38118,7 @@ const getPost = (postId, callback) => {
38012
38118
  convertEventPayload((callback) => {
38013
38119
  return onCommentDeleted(async (comment) => {
38014
38120
  if (comment.referenceId === postId) {
38015
- await getPost$1(postId);
38121
+ await getPost$2(postId);
38016
38122
  callback(comment);
38017
38123
  }
38018
38124
  });
@@ -38021,61 +38127,272 @@ const getPost = (postId, callback) => {
38021
38127
  };
38022
38128
  /* end_public_function */
38023
38129
 
38024
- /**
38025
- * ```js
38026
- * import { queryPosts } from '@amityco/ts-sdk'
38027
- * const { data: posts, prevPage, nextPage } = await queryPosts({ targetId, targetType })
38028
- * ```
38029
- *
38030
- * Queries a paginable list of {@link Amity.Post} objects
38031
- *
38032
- * @param query The query parameters
38033
- * @returns posts
38034
- *
38035
- * @category Post API
38036
- * @async
38037
- */
38038
- const queryPosts = async (query) => {
38039
- const client = getActiveClient();
38040
- client.log('post/queryPosts', query);
38041
- const { page, limit = 10, includeDeleted } = query, params = __rest(query, ["page", "limit", "includeDeleted"]);
38042
- const { dataTypes, matchingOnlyParentPost } = params;
38043
- const options = (() => {
38044
- if (page)
38045
- return { token: page };
38046
- if (limit)
38047
- return { limit };
38048
- return undefined;
38049
- })();
38050
- // API-FIX: parameters should be querystring. (1)
38051
- // API-FIX: backend should answer Amity.Response (2)
38052
- // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.PostPayload>>>(
38053
- const { data } = await client.http.get(`/api/v4/posts`, {
38054
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted),
38055
- /*
38056
- * when creating post like image, file, video BE will create 2 posts
38057
- * 1. parent post to store text with dataType=text
38058
- * 2. child post to store dataTypes post data
38059
- *
38060
- * By default, BE queries only parent post
38061
- */
38062
- matchingOnlyParentPost: matchingOnlyParentPost !== null && matchingOnlyParentPost !== void 0 ? matchingOnlyParentPost : !(dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length), options }),
38130
+ class PostPaginationController extends PaginationController {
38131
+ async getRequest(queryParams, token) {
38132
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted, matchingOnlyParentPost } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted", "matchingOnlyParentPost"]);
38133
+ const { dataTypes } = params;
38134
+ const baseOptions = {
38135
+ type: params.sortBy || queryParams.limit ? 'pagination' : undefined,
38136
+ };
38137
+ const options = token ? Object.assign(Object.assign({}, baseOptions), { token }) : Object.assign(Object.assign({}, baseOptions), { limit });
38138
+ const { data: queryResponse } = await this.http.get(`/api/v4/posts`, {
38139
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted),
38140
+ /*
38141
+ * when creating post like image, file, video BE will create 2 posts
38142
+ * 1. parent post to store text with dataType=text
38143
+ * 2. child post to store dataTypes post data
38144
+ *
38145
+ * By default, BE queries only parent post
38146
+ */
38147
+ matchingOnlyParentPost: matchingOnlyParentPost !== null && matchingOnlyParentPost !== void 0 ? matchingOnlyParentPost : !(dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length), options }),
38148
+ });
38149
+ return queryResponse;
38150
+ }
38151
+ }
38152
+
38153
+ var EnumPostActions;
38154
+ (function (EnumPostActions) {
38155
+ EnumPostActions["OnPostCreated"] = "onPostCreated";
38156
+ EnumPostActions["OnPostUpdated"] = "onPostUpdated";
38157
+ EnumPostActions["OnPostDeleted"] = "onPostDeleted";
38158
+ EnumPostActions["OnPostFlagged"] = "onPostFlagged";
38159
+ EnumPostActions["OnPostUnflagged"] = "onPostUnflagged";
38160
+ EnumPostActions["OnPostReactionAdded"] = "onPostReactionAdded";
38161
+ EnumPostActions["OnPostReactionRemoved"] = "onPostReactionRemoved";
38162
+ EnumPostActions["OnPostApproved"] = "onPostApproved";
38163
+ EnumPostActions["OnPostDeclined"] = "onPostDeclined";
38164
+ })(EnumPostActions || (EnumPostActions = {}));
38165
+
38166
+ class PostQueryStreamController extends QueryStreamController {
38167
+ constructor(query, cacheKey, notifyChange, preparePayload) {
38168
+ super(query, cacheKey);
38169
+ this.notifyChange = notifyChange;
38170
+ this.preparePayload = preparePayload;
38171
+ }
38172
+ async saveToMainDB(response) {
38173
+ const processedPayload = await this.preparePayload(response);
38174
+ const client = getActiveClient();
38175
+ const cachedAt = client.cache && Date.now();
38176
+ if (client.cache) {
38177
+ ingestInCache(processedPayload, { cachedAt });
38178
+ }
38179
+ }
38180
+ appendToQueryStream(response, direction, refresh = false) {
38181
+ var _a, _b;
38182
+ if (refresh) {
38183
+ pushToCache(this.cacheKey, {
38184
+ data: response.posts.map(getResolver('post')),
38185
+ });
38186
+ }
38187
+ else {
38188
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38189
+ const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
38190
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...posts, ...response.posts.map(getResolver('post'))])] }));
38191
+ }
38192
+ }
38193
+ reactor(action) {
38194
+ return (post) => {
38195
+ var _a, _b;
38196
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38197
+ if (!collection)
38198
+ return;
38199
+ if (post.parentPostId && post.isDeleted) {
38200
+ const parentPost = (_b = pullFromCache([
38201
+ 'post',
38202
+ 'get',
38203
+ post.parentPostId,
38204
+ ])) === null || _b === void 0 ? void 0 : _b.data;
38205
+ if (!parentPost || (parentPost === null || parentPost === void 0 ? void 0 : parentPost.targetId) !== this.query.targetId)
38206
+ return;
38207
+ parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
38208
+ pushToCache(['post', 'get', parentPost.postId], parentPost);
38209
+ }
38210
+ else {
38211
+ if (this.query.targetId !== post.targetId)
38212
+ return;
38213
+ if (this.query.targetType !== post.targetType)
38214
+ return;
38215
+ }
38216
+ if (action === EnumPostActions.OnPostDeclined) {
38217
+ collection.data = collection.data.filter(postId => postId !== post.postId);
38218
+ }
38219
+ if (action === EnumPostActions.OnPostCreated || action === EnumPostActions.OnPostApproved) {
38220
+ collection.data = [...new Set([post.postId, ...collection.data])];
38221
+ }
38222
+ pushToCache(this.cacheKey, collection);
38223
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
38224
+ };
38225
+ }
38226
+ subscribeRTE(createSubscriber) {
38227
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
38228
+ }
38229
+ }
38230
+
38231
+ const preparePostPayload = (postPayload) => {
38232
+ const { posts } = postPayload;
38233
+ const { communities, communityUsers } = convertCommunityPayload({
38234
+ communities: postPayload.communities,
38235
+ communityUsers: postPayload.communityUsers,
38063
38236
  });
38064
- // API-FIX: backend should answer Amity.Response (2)
38065
- // const { paging, posts } = unwrapPayload(data)
38066
- // unpacking
38067
- const { paging } = data, payload = __rest(data, ["paging"]);
38068
- const paperedPayload = prepareMembershipPayload(payload, 'communityUsers');
38069
- const { posts } = payload;
38070
- const cachedAt = client.cache && Date.now();
38071
- if (client.cache) {
38072
- ingestInCache(paperedPayload, { cachedAt });
38073
- const cacheKey = ['post', 'query', Object.assign(Object.assign({}, params), { options })];
38074
- pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
38237
+ return Object.assign(Object.assign({}, postPayload), { posts,
38238
+ communities,
38239
+ communityUsers });
38240
+ };
38241
+
38242
+ const getPost = async (postId) => {
38243
+ const client = getActiveClient();
38244
+ client.log('post/getPost', postId);
38245
+ isInTombstone('post', postId);
38246
+ let payload;
38247
+ try {
38248
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
38249
+ const response = await client.http.get(`/api/v3/posts/${encodeURIComponent(postId)}`);
38250
+ payload = response.data;
38251
+ }
38252
+ catch (error) {
38253
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
38254
+ pushToTombstone('post', postId);
38255
+ }
38256
+ throw error;
38075
38257
  }
38076
- return { data: posts.map(LinkedObject.post), cachedAt, paging };
38258
+ const data = prepareMembershipPayload(payload, 'communityUsers');
38259
+ const cachedAt = client.cache && Date.now();
38260
+ if (client.cache)
38261
+ ingestInCache(data, { cachedAt });
38262
+ const { posts } = data;
38263
+ const result = posts.find(post => post.postId === postId);
38264
+ return {
38265
+ data: result,
38266
+ cachedAt,
38267
+ };
38268
+ };
38269
+ getPost.locally = (postId) => {
38270
+ const client = getActiveClient();
38271
+ client.log('post/getPost.locally', postId);
38272
+ if (!client.cache)
38273
+ return;
38274
+ const cached = pullFromCache(['post', 'get', postId]);
38275
+ if (!cached)
38276
+ return;
38277
+ return {
38278
+ data: cached.data,
38279
+ cachedAt: cached.cachedAt,
38280
+ };
38077
38281
  };
38078
38282
 
38283
+ class PostLiveCollectionController extends LiveCollectionController {
38284
+ constructor(query, callback) {
38285
+ const queryStreamId = hash(query);
38286
+ const cacheKey = ['posts', 'collection', queryStreamId];
38287
+ const paginationController = new PostPaginationController(query);
38288
+ super(paginationController, queryStreamId, cacheKey, callback);
38289
+ this.query = query;
38290
+ this.queryStreamController = new PostQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), preparePostPayload);
38291
+ this.callback = callback.bind(this);
38292
+ this.loadPage({ initial: true });
38293
+ }
38294
+ setup() {
38295
+ var _a;
38296
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38297
+ if (!collection) {
38298
+ pushToCache(this.cacheKey, {
38299
+ data: [],
38300
+ params: {},
38301
+ });
38302
+ }
38303
+ }
38304
+ async persistModel(queryPayload) {
38305
+ await this.queryStreamController.saveToMainDB(queryPayload);
38306
+ }
38307
+ persistQueryStream({ response, direction, refresh, }) {
38308
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
38309
+ }
38310
+ startSubscription() {
38311
+ return this.queryStreamController.subscribeRTE([
38312
+ { fn: onPostCreated, action: EnumPostActions.OnPostCreated },
38313
+ { fn: onPostUpdated, action: EnumPostActions.OnPostUpdated },
38314
+ { fn: onPostDeleted, action: EnumPostActions.OnPostDeleted },
38315
+ { fn: onPostFlagged, action: EnumPostActions.OnPostFlagged },
38316
+ { fn: onPostUnflagged, action: EnumPostActions.OnPostUnflagged },
38317
+ { fn: onPostApproved, action: EnumPostActions.OnPostApproved },
38318
+ { fn: onPostDeclined, action: EnumPostActions.OnPostDeclined },
38319
+ { fn: onPostReactionAdded, action: EnumPostActions.OnPostReactionAdded },
38320
+ { fn: onPostReactionRemoved, action: EnumPostActions.OnPostReactionRemoved },
38321
+ {
38322
+ fn: convertEventPayload((callback) => {
38323
+ return onCommentCreated(async (comment) => {
38324
+ var _a;
38325
+ const currentCollection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38326
+ if (!currentCollection || currentCollection.data.includes(comment.referenceId))
38327
+ return;
38328
+ await getPost(comment.referenceId);
38329
+ callback(comment);
38330
+ });
38331
+ }, 'referenceId', 'post'),
38332
+ action: EnumPostActions.OnPostUpdated,
38333
+ },
38334
+ {
38335
+ fn: convertEventPayload((callback) => {
38336
+ return onCommentDeleted(async (comment) => {
38337
+ var _a;
38338
+ const currentCollection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38339
+ if (!currentCollection || currentCollection.data.includes(comment.referenceId))
38340
+ return;
38341
+ await getPost(comment.referenceId);
38342
+ callback(comment);
38343
+ });
38344
+ }, 'referenceId', 'post'),
38345
+ action: EnumPostActions.OnPostUpdated,
38346
+ },
38347
+ ]);
38348
+ }
38349
+ notifyChange({ origin, loading, error }) {
38350
+ var _a, _b;
38351
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38352
+ if (!collection)
38353
+ return;
38354
+ const data = this.applyFilter((_b = collection.data
38355
+ .map(id => pullFromCache(['post', 'get', id]))
38356
+ .filter(isNonNullable)
38357
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.post);
38358
+ if (!this.shouldNotify(data) && origin === 'event')
38359
+ return;
38360
+ this.callback({
38361
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
38362
+ data,
38363
+ hasNextPage: !!this.paginationController.getNextToken(),
38364
+ loading,
38365
+ error,
38366
+ });
38367
+ }
38368
+ applyFilter(data) {
38369
+ var _a;
38370
+ let posts = data;
38371
+ if (!this.query.includeDeleted) {
38372
+ posts = filterByPropEquality(posts, 'isDeleted', false);
38373
+ }
38374
+ if (this.query.tags) {
38375
+ posts = posts.filter(p => { var _a; return (_a = p.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); }); });
38376
+ }
38377
+ if (this.query.targetType === 'community' && this.query.feedType) {
38378
+ posts = filterByFeedType(posts, this.query.feedType);
38379
+ }
38380
+ if ((_a = this.query.dataTypes) === null || _a === void 0 ? void 0 : _a.length) {
38381
+ posts = filterByPostDataTypes(posts, this.query.dataTypes);
38382
+ }
38383
+ switch (this.query.sortBy) {
38384
+ case 'firstCreated':
38385
+ posts = posts.sort(sortByFirstCreated);
38386
+ break;
38387
+ case 'lastCreated':
38388
+ default:
38389
+ posts = posts.sort(sortByLastCreated);
38390
+ break;
38391
+ }
38392
+ return posts;
38393
+ }
38394
+ }
38395
+
38079
38396
  /* begin_public_function
38080
38397
  id: post.query
38081
38398
  */
@@ -38107,121 +38424,9 @@ const getPosts = (params, callback, config) => {
38107
38424
  }
38108
38425
  const timestamp = Date.now();
38109
38426
  log(`getPosts(tmpid: ${timestamp}) > listen`);
38110
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
38111
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
38112
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
38113
- const disposers = [];
38114
- const cacheKey = [
38115
- 'post',
38116
- 'collection',
38117
- { targetId: params.targetId, targetType: params.targetType },
38118
- ];
38119
- const responder = (data) => {
38120
- var _a, _b, _c;
38121
- let posts = (_a = data.data
38122
- .map(postId => pullFromCache(['post', 'get', postId]))
38123
- .filter(Boolean)
38124
- .map(({ data }) => LinkedObject.post(data))) !== null && _a !== void 0 ? _a : [];
38125
- const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
38126
- posts = posts.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
38127
- if (!params.includeDeleted) {
38128
- posts = filterByPropEquality(posts, 'isDeleted', false);
38129
- }
38130
- if (params.tags) {
38131
- 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); }); });
38132
- }
38133
- if (params.targetType === 'community' && params.feedType) {
38134
- posts = filterByFeedType(posts, params.feedType);
38135
- }
38136
- if ((_b = params.dataTypes) === null || _b === void 0 ? void 0 : _b.length) {
38137
- posts = filterByPostDataTypes(posts, params.dataTypes);
38138
- }
38139
- callback({
38140
- onNextPage: onFetch,
38141
- data: posts,
38142
- hasNextPage: !!((_c = data.params) === null || _c === void 0 ? void 0 : _c.page),
38143
- loading: data.loading,
38144
- error: data.error,
38145
- });
38146
- };
38147
- const realtimeRouter = (action) => (post) => {
38148
- var _a, _b;
38149
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38150
- if (!collection)
38151
- return;
38152
- if (post.parentPostId && post.isDeleted) {
38153
- const parentPost = (_b = pullFromCache([
38154
- 'post',
38155
- 'get',
38156
- post.parentPostId,
38157
- ])) === null || _b === void 0 ? void 0 : _b.data;
38158
- if (!parentPost || (parentPost === null || parentPost === void 0 ? void 0 : parentPost.targetId) !== params.targetId)
38159
- return;
38160
- parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
38161
- pushToCache(['post', 'get', parentPost.postId], parentPost);
38162
- }
38163
- else {
38164
- if (params.targetId !== post.targetId)
38165
- return;
38166
- if (params.targetType !== post.targetType)
38167
- return;
38168
- }
38169
- /*
38170
- * This is not ideal, but currently this is the only way to update the
38171
- * collection on post declined
38172
- */
38173
- if (action === 'onDeclined') {
38174
- collection.data = collection.data.filter(postId => postId !== post.postId);
38175
- }
38176
- else {
38177
- collection.data = [...new Set([post.postId, ...collection.data])];
38178
- }
38179
- pushToCache(cacheKey, collection);
38180
- responder(collection);
38181
- };
38182
- const onFetch = (initial = false) => {
38183
- var _a, _b, _c;
38184
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38185
- const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
38186
- if (!initial && posts.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
38187
- return;
38188
- 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 }));
38189
- runQuery(query, ({ data: result, error, loading, paging }) => {
38190
- const data = {
38191
- loading,
38192
- error,
38193
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
38194
- data: posts,
38195
- };
38196
- if (result) {
38197
- data.data = initial
38198
- ? result.map(getResolver('post'))
38199
- : [...new Set([...posts, ...result.map(getResolver('post'))])];
38200
- }
38201
- pushToCache(cacheKey, data);
38202
- responder(data);
38203
- }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
38204
- };
38205
- 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) => {
38206
- return onCommentCreated(async (comment) => {
38207
- var _a;
38208
- const currentCollection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38209
- if (!currentCollection || currentCollection.data.includes(comment.referenceId))
38210
- return;
38211
- await getPost$1(comment.referenceId);
38212
- callback(comment);
38213
- });
38214
- }, 'referenceId', 'post')(realtimeRouter('onUpdate')), convertEventPayload((callback) => {
38215
- return onCommentDeleted(async (comment) => {
38216
- var _a;
38217
- const currentCollection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38218
- if (!currentCollection || currentCollection.data.includes(comment.referenceId))
38219
- return;
38220
- await getPost$1(comment.referenceId);
38221
- callback(comment);
38222
- });
38223
- }, 'referenceId', 'post')(realtimeRouter('onUpdate')));
38224
- onFetch(true);
38427
+ const postsLiveCollection = new PostLiveCollectionController(params, callback);
38428
+ const disposers = postsLiveCollection.startSubscription();
38429
+ const cacheKey = postsLiveCollection.getCacheKey();
38225
38430
  disposers.push(() => dropFromCache(cacheKey));
38226
38431
  return () => {
38227
38432
  log(`getPosts(tmpid: ${timestamp}) > dispose`);
@@ -38255,7 +38460,7 @@ var index$5 = /*#__PURE__*/Object.freeze({
38255
38460
  onPostReactionRemoved: onPostReactionRemoved,
38256
38461
  observePosts: observePosts,
38257
38462
  observePost: observePost,
38258
- getPost: getPost,
38463
+ getPost: getPost$1,
38259
38464
  getPosts: getPosts
38260
38465
  });
38261
38466
 
@@ -39150,7 +39355,7 @@ var index$3 = /*#__PURE__*/Object.freeze({
39150
39355
  getPoll: getPoll
39151
39356
  });
39152
39357
 
39153
- 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-----";
39358
+ 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-----";
39154
39359
  /*
39155
39360
  * The crypto algorithm used for importing key and signing string
39156
39361
  */
@@ -40597,20 +40802,27 @@ var index$1 = /*#__PURE__*/Object.freeze({
40597
40802
  getGlobalStoryTargets: getGlobalStoryTargets
40598
40803
  });
40599
40804
 
40600
- const convertToNetworkAds = (data) => {
40601
- const { ads, settings } = data;
40602
- return {
40603
- ads: ads.map(LinkedObject.ad),
40604
- settings,
40605
- };
40805
+ const convertToInternalAd = (ad) => {
40806
+ return Object.assign(Object.assign({}, ad), { endAt: ad.endAt ? ad.endAt : null });
40807
+ };
40808
+ const convertToInternalAdvertiser = (advertiser) => {
40809
+ return Object.assign({}, advertiser);
40606
40810
  };
40607
40811
  const getNetworkAds = async () => {
40608
40812
  const client = getActiveClient();
40609
40813
  const { data } = await client.http.get('/api/v1/ads/me');
40610
- const { settings } = data, rest = __rest(data, ["settings"]);
40611
- ingestInCache(rest);
40612
- pushToCache(['ad', 'setting'], settings);
40613
- return convertToNetworkAds(data);
40814
+ const internalAds = data.ads.map(convertToInternalAd);
40815
+ const internalAdvertisers = data.advertisers.map(convertToInternalAdvertiser);
40816
+ ingestInCache({
40817
+ ads: internalAds,
40818
+ advertisers: internalAdvertisers,
40819
+ files: data.files,
40820
+ });
40821
+ pushToCache(['ad', 'setting'], data.settings);
40822
+ return {
40823
+ ads: internalAds.map(LinkedObject.ad),
40824
+ settings: data.settings,
40825
+ };
40614
40826
  };
40615
40827
 
40616
40828
  var index = /*#__PURE__*/Object.freeze({
@@ -40640,4 +40852,4 @@ const createUserToken = async (apiKey, apiRegion, params) => {
40640
40852
  return { accessToken: data.accessToken };
40641
40853
  };
40642
40854
 
40643
- export { API_REGIONS, index as AdRepository, index$8 as CategoryRepository, index$c as ChannelRepository, index$l as Client, index$6 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$9 as CommunityRepository, ContentFeedType, DefaultCommunityPostSetting, index$7 as FeedRepository, index$i as FileRepository, FileType, index$2 as LiveStreamPlayer, MessageContentType, index$g as MessageRepository, index$3 as PollRepository, PostContentType, index$5 as PostRepository, index$h as ReactionRepository, index$1 as StoryRepository, index$4 as StreamRepository, index$f as SubChannelRepository, SubscriptionLevels, index$j as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, 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 };
40855
+ export { API_REGIONS, index as AdRepository, index$8 as CategoryRepository, index$c as ChannelRepository, index$l as Client, index$6 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$9 as CommunityRepository, ContentFeedType, DefaultCommunityPostSetting, index$7 as FeedRepository, FileAccessTypeEnum, index$i as FileRepository, FileType, index$2 as LiveStreamPlayer, MessageContentType, index$g as MessageRepository, index$3 as PollRepository, PostContentType, index$5 as PostRepository, index$h as ReactionRepository, index$1 as StoryRepository, index$4 as StreamRepository, index$f as SubChannelRepository, SubscriptionLevels, index$j as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, 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 };