@knocklabs/client 0.11.0-rc.0 → 0.11.1
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.
- package/CHANGELOG.md +32 -4
- package/dist/cjs/api.js +1 -1
- package/dist/cjs/api.js.map +1 -1
- package/dist/cjs/clients/feed/feed.js +1 -1
- package/dist/cjs/clients/feed/feed.js.map +1 -1
- package/dist/cjs/clients/feed/store.js +1 -1
- package/dist/cjs/clients/feed/store.js.map +1 -1
- package/dist/cjs/clients/ms-teams/index.js +2 -0
- package/dist/cjs/clients/ms-teams/index.js.map +1 -0
- package/dist/cjs/clients/slack/index.js +1 -1
- package/dist/cjs/clients/slack/index.js.map +1 -1
- package/dist/cjs/clients/users/index.js +1 -1
- package/dist/cjs/clients/users/index.js.map +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/knock.js +1 -5
- package/dist/cjs/knock.js.map +1 -1
- package/dist/esm/clients/feed/feed.mjs +45 -32
- package/dist/esm/clients/feed/feed.mjs.map +1 -1
- package/dist/esm/clients/ms-teams/index.mjs +54 -0
- package/dist/esm/clients/ms-teams/index.mjs.map +1 -0
- package/dist/esm/clients/slack/index.mjs +11 -11
- package/dist/esm/clients/slack/index.mjs.map +1 -1
- package/dist/esm/clients/users/index.mjs +20 -28
- package/dist/esm/clients/users/index.mjs.map +1 -1
- package/dist/esm/index.mjs +7 -11
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/knock.mjs +22 -26
- package/dist/esm/knock.mjs.map +1 -1
- package/dist/types/api.d.ts +0 -1
- package/dist/types/clients/feed/feed.d.ts +0 -1
- package/dist/types/clients/feed/feed.d.ts.map +1 -1
- package/dist/types/clients/feed/index.d.ts +0 -1
- package/dist/types/clients/feed/interfaces.d.ts +0 -1
- package/dist/types/clients/feed/store.d.ts +0 -1
- package/dist/types/clients/feed/types.d.ts +0 -1
- package/dist/types/clients/feed/utils.d.ts +0 -1
- package/dist/types/clients/messages/index.d.ts +0 -1
- package/dist/types/clients/messages/interfaces.d.ts +1 -2
- package/dist/types/clients/messages/interfaces.d.ts.map +1 -1
- package/dist/types/clients/ms-teams/index.d.ts +11 -0
- package/dist/types/clients/ms-teams/index.d.ts.map +1 -0
- package/dist/types/clients/objects/index.d.ts +0 -1
- package/dist/types/clients/preferences/index.d.ts +0 -1
- package/dist/types/clients/preferences/interfaces.d.ts +9 -7
- package/dist/types/clients/preferences/interfaces.d.ts.map +1 -1
- package/dist/types/clients/slack/index.d.ts +2 -2
- package/dist/types/clients/slack/index.d.ts.map +1 -1
- package/dist/types/clients/slack/interfaces.d.ts +0 -8
- package/dist/types/clients/slack/interfaces.d.ts.map +1 -1
- package/dist/types/clients/users/index.d.ts +1 -4
- package/dist/types/clients/users/index.d.ts.map +1 -1
- package/dist/types/clients/users/interfaces.d.ts +0 -7
- package/dist/types/clients/users/interfaces.d.ts.map +1 -1
- package/dist/types/index.d.ts +1 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/interfaces.d.ts +8 -1
- package/dist/types/interfaces.d.ts.map +1 -1
- package/dist/types/knock.d.ts +4 -3
- package/dist/types/knock.d.ts.map +1 -1
- package/package.json +15 -17
- package/src/clients/feed/feed.ts +25 -10
- package/src/clients/messages/interfaces.ts +9 -1
- package/src/clients/ms-teams/index.ts +60 -0
- package/src/clients/preferences/interfaces.ts +11 -6
- package/src/clients/slack/index.ts +6 -11
- package/src/clients/slack/interfaces.ts +0 -10
- package/src/clients/users/index.ts +1 -19
- package/src/clients/users/interfaces.ts +0 -8
- package/src/index.ts +1 -1
- package/src/interfaces.ts +10 -0
- package/src/knock.ts +5 -13
- package/dist/cjs/clients/in-app-messages/channel-client.js +0 -2
- package/dist/cjs/clients/in-app-messages/channel-client.js.map +0 -1
- package/dist/cjs/clients/in-app-messages/message-client.js +0 -2
- package/dist/cjs/clients/in-app-messages/message-client.js.map +0 -1
- package/dist/cjs/clients/in-app-messages/socket-manager.js +0 -2
- package/dist/cjs/clients/in-app-messages/socket-manager.js.map +0 -1
- package/dist/cjs/clients/in-app-messages/store.js +0 -2
- package/dist/cjs/clients/in-app-messages/store.js.map +0 -1
- package/dist/esm/clients/in-app-messages/channel-client.mjs +0 -80
- package/dist/esm/clients/in-app-messages/channel-client.mjs.map +0 -1
- package/dist/esm/clients/in-app-messages/message-client.mjs +0 -153
- package/dist/esm/clients/in-app-messages/message-client.mjs.map +0 -1
- package/dist/esm/clients/in-app-messages/socket-manager.mjs +0 -83
- package/dist/esm/clients/in-app-messages/socket-manager.mjs.map +0 -1
- package/dist/esm/clients/in-app-messages/store.mjs +0 -11
- package/dist/esm/clients/in-app-messages/store.mjs.map +0 -1
- package/dist/types/clients/in-app-messages/channel-client.d.ts +0 -23
- package/dist/types/clients/in-app-messages/channel-client.d.ts.map +0 -1
- package/dist/types/clients/in-app-messages/index.d.ts +0 -4
- package/dist/types/clients/in-app-messages/index.d.ts.map +0 -1
- package/dist/types/clients/in-app-messages/message-client.d.ts +0 -52
- package/dist/types/clients/in-app-messages/message-client.d.ts.map +0 -1
- package/dist/types/clients/in-app-messages/socket-manager.d.ts +0 -27
- package/dist/types/clients/in-app-messages/socket-manager.d.ts.map +0 -1
- package/dist/types/clients/in-app-messages/store.d.ts +0 -6
- package/dist/types/clients/in-app-messages/store.d.ts.map +0 -1
- package/dist/types/clients/in-app-messages/types.d.ts +0 -52
- package/dist/types/clients/in-app-messages/types.d.ts.map +0 -1
- package/src/clients/in-app-messages/channel-client.ts +0 -129
- package/src/clients/in-app-messages/index.ts +0 -3
- package/src/clients/in-app-messages/message-client.ts +0 -271
- package/src/clients/in-app-messages/socket-manager.ts +0 -187
- package/src/clients/in-app-messages/store.ts +0 -15
- package/src/clients/in-app-messages/types.ts +0 -79
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
var f = Object.defineProperty;
|
|
2
2
|
var p = (u, e, t) => e in u ? f(u, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : u[e] = t;
|
|
3
|
-
var
|
|
4
|
-
import
|
|
5
|
-
import { isRequestInFlight as
|
|
6
|
-
import
|
|
3
|
+
var c = (u, e, t) => p(u, typeof e != "symbol" ? e + "" : e, t);
|
|
4
|
+
import k from "eventemitter2";
|
|
5
|
+
import { isRequestInFlight as g, NetworkStatus as m } from "../../networkStatus.mjs";
|
|
6
|
+
import _ from "./store.mjs";
|
|
7
7
|
const S = {
|
|
8
8
|
archived: "exclude"
|
|
9
9
|
}, v = 2e3;
|
|
10
|
-
class
|
|
10
|
+
class U {
|
|
11
11
|
constructor(e, t, s) {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
12
|
+
c(this, "userFeedId");
|
|
13
|
+
c(this, "channel");
|
|
14
|
+
c(this, "broadcaster");
|
|
15
|
+
c(this, "defaultOptions");
|
|
16
|
+
c(this, "broadcastChannel");
|
|
17
|
+
c(this, "disconnectTimer", null);
|
|
18
|
+
c(this, "hasSubscribedToRealTimeUpdates", !1);
|
|
19
|
+
c(this, "visibilityChangeHandler", () => {
|
|
20
20
|
});
|
|
21
|
-
|
|
21
|
+
c(this, "visibilityChangeListenerConnected", !1);
|
|
22
22
|
// The raw store instance, used for binding in React and other environments
|
|
23
|
-
|
|
24
|
-
this.knock = e, this.feedId = t, this.feedId = t, this.userFeedId = this.buildUserFeedId(), this.store =
|
|
23
|
+
c(this, "store");
|
|
24
|
+
this.knock = e, this.feedId = t, this.feedId = t, this.userFeedId = this.buildUserFeedId(), this.store = _(), this.broadcaster = new k({ wildcard: !0, delimiter: "." }), this.defaultOptions = { ...S, ...s }, this.knock.log(`[Feed] Initialized a feed on channel ${t}`), this.initializeRealtimeConnection(), this.setupBroadcastChannel();
|
|
25
25
|
}
|
|
26
26
|
/**
|
|
27
27
|
* Used to reinitialize a current feed instance, which is useful when reauthenticating users
|
|
@@ -45,7 +45,12 @@ class I {
|
|
|
45
45
|
current ApiClient instance if the socket is not already connected.
|
|
46
46
|
*/
|
|
47
47
|
listenForUpdates() {
|
|
48
|
-
this.knock.log("[Feed] Connecting to real-time service"), this.hasSubscribedToRealTimeUpdates = !0
|
|
48
|
+
if (this.knock.log("[Feed] Connecting to real-time service"), this.hasSubscribedToRealTimeUpdates = !0, !this.knock.isAuthenticated()) {
|
|
49
|
+
this.knock.log(
|
|
50
|
+
"[Feed] User is not authenticated, skipping listening for updates"
|
|
51
|
+
);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
49
54
|
const e = this.knock.client().socket;
|
|
50
55
|
e && !e.isConnected() && e.connect(), this.channel && ["closed", "errored"].includes(this.channel.state) && this.channel.join();
|
|
51
56
|
}
|
|
@@ -150,14 +155,16 @@ class I {
|
|
|
150
155
|
if (s) {
|
|
151
156
|
const i = a.filter((l) => !l.seen_at).length, o = a.filter((l) => !l.read_at).length, r = {
|
|
152
157
|
...t.metadata,
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
158
|
+
// Ensure that the counts don't ever go below 0 on archiving where the client state
|
|
159
|
+
// gets out of sync with the server state
|
|
160
|
+
total_count: Math.max(0, t.metadata.total_count - a.length),
|
|
161
|
+
unseen_count: Math.max(0, t.metadata.unseen_count - i),
|
|
162
|
+
unread_count: Math.max(0, t.metadata.unread_count - o)
|
|
163
|
+
}, d = t.items.filter(
|
|
157
164
|
(l) => !n.includes(l.id)
|
|
158
165
|
);
|
|
159
166
|
t.setResult({
|
|
160
|
-
entries:
|
|
167
|
+
entries: d,
|
|
161
168
|
meta: r,
|
|
162
169
|
page_info: t.pageInfo
|
|
163
170
|
});
|
|
@@ -181,7 +188,7 @@ class I {
|
|
|
181
188
|
if (t.setItemAttrs(a, {
|
|
182
189
|
archived_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
183
190
|
}), this.defaultOptions.archived === "exclude") {
|
|
184
|
-
const o = e.filter((
|
|
191
|
+
const o = e.filter((d) => !a.includes(d.id)), r = {
|
|
185
192
|
...t.metadata,
|
|
186
193
|
total_count: o.length,
|
|
187
194
|
unread_count: 0
|
|
@@ -202,8 +209,14 @@ class I {
|
|
|
202
209
|
/* Fetches the feed content, appending it to the store */
|
|
203
210
|
async fetch(e = {}) {
|
|
204
211
|
const { networkStatus: t, ...s } = this.store.getState();
|
|
205
|
-
if (
|
|
212
|
+
if (!this.knock.isAuthenticated()) {
|
|
213
|
+
this.knock.log("[Feed] User is not authenticated, skipping fetch");
|
|
206
214
|
return;
|
|
215
|
+
}
|
|
216
|
+
if (g(t)) {
|
|
217
|
+
this.knock.log("[Feed] Request is in flight, skipping fetch");
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
207
220
|
s.setNetworkStatus(e.__loadingType ?? m.loading);
|
|
208
221
|
const a = {
|
|
209
222
|
...this.defaultOptions,
|
|
@@ -230,11 +243,11 @@ class I {
|
|
|
230
243
|
page_info: n.body.page_info
|
|
231
244
|
};
|
|
232
245
|
if (e.before) {
|
|
233
|
-
const
|
|
234
|
-
s.setResult(i,
|
|
246
|
+
const d = { shouldSetPage: !1, shouldAppend: !0 };
|
|
247
|
+
s.setResult(i, d);
|
|
235
248
|
} else if (e.after) {
|
|
236
|
-
const
|
|
237
|
-
s.setResult(i,
|
|
249
|
+
const d = { shouldSetPage: !0, shouldAppend: !0 };
|
|
250
|
+
s.setResult(i, d);
|
|
238
251
|
} else
|
|
239
252
|
s.setResult(i);
|
|
240
253
|
this.broadcast("messages.new", i);
|
|
@@ -269,7 +282,7 @@ class I {
|
|
|
269
282
|
optimisticallyPerformStatusUpdate(e, t, s, a) {
|
|
270
283
|
const n = this.store.getState(), i = Array.isArray(e) ? e : [e], o = i.map((r) => r.id);
|
|
271
284
|
if (a) {
|
|
272
|
-
const { metadata: r } = n,
|
|
285
|
+
const { metadata: r } = n, d = i.filter((h) => {
|
|
273
286
|
switch (t) {
|
|
274
287
|
case "seen":
|
|
275
288
|
return h.seen_at === null;
|
|
@@ -283,7 +296,7 @@ class I {
|
|
|
283
296
|
default:
|
|
284
297
|
return !0;
|
|
285
298
|
}
|
|
286
|
-
}), l = t.startsWith("un") ?
|
|
299
|
+
}), l = t.startsWith("un") ? d.length : -d.length;
|
|
287
300
|
n.setMetadata({
|
|
288
301
|
...r,
|
|
289
302
|
[a]: Math.max(0, r[a] + l)
|
|
@@ -348,7 +361,7 @@ class I {
|
|
|
348
361
|
e && (this.channel = e.channel(
|
|
349
362
|
`feeds:${this.userFeedId}`,
|
|
350
363
|
this.defaultOptions
|
|
351
|
-
), this.channel.on("new-message", (t) => this.onNewMessageReceived(t)), this.defaultOptions.auto_manage_socket_connection && this.setupAutoSocketManager(), this.hasSubscribedToRealTimeUpdates && (e.isConnected() || e.connect(), this.channel.join()));
|
|
364
|
+
), this.channel.on("new-message", (t) => this.onNewMessageReceived(t)), this.defaultOptions.auto_manage_socket_connection && this.setupAutoSocketManager(), this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated() && (e.isConnected() || e.connect(), this.channel.join()));
|
|
352
365
|
}
|
|
353
366
|
/**
|
|
354
367
|
* Listen for changes to document visibility and automatically disconnect
|
|
@@ -376,6 +389,6 @@ class I {
|
|
|
376
389
|
}
|
|
377
390
|
}
|
|
378
391
|
export {
|
|
379
|
-
|
|
392
|
+
U as default
|
|
380
393
|
};
|
|
381
394
|
//# sourceMappingURL=feed.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"feed.mjs","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { Channel } from \"phoenix\";\nimport { StoreApi } from \"zustand\";\n\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n} from \"./interfaces\";\nimport createStore from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n FeedStoreState,\n} from \"./types\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nclass Feed {\n private userFeedId: string;\n private channel?: Channel;\n private broadcaster: EventEmitter;\n private defaultOptions: FeedClientOptions;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: StoreApi<FeedStoreState>;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n ) {\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = { ...feedClientDefaults, ...options };\n\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize() {\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n if (this.channel) {\n this.channel.leave();\n this.channel.off(\"new-message\");\n }\n\n this.teardownAutoSocketManager();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n const maybeSocket = this.knock.client().socket;\n\n // Connect the socket only if we don't already have a connection\n if (maybeSocket && !maybeSocket.isConnected()) {\n maybeSocket.connect();\n }\n\n // Only join the channel if we're not already in a joining state\n if (this.channel && [\"closed\", \"errored\"].includes(this.channel.state)) {\n this.channel.join();\n }\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n\n const itemIds: string[] = normalizedItems.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = normalizedItems.filter((i) => !i.seen_at).length;\n const unreadCount = normalizedItems.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: state.metadata.total_count - normalizedItems.length,\n unseen_count: state.metadata.unseen_count - unseenCount,\n unread_count: state.metadata.unread_count - unreadCount,\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // Always include the default params, if they have been set\n const queryParams = {\n ...this.defaultOptions,\n ...options,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage() {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({\n metadata,\n }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n // Optimistically set the badge counts\n state.setMetadata(metadata);\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // Tnis is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n const { socket: maybeSocket } = this.knock.client();\n\n // In server environments we might not have a socket connection\n if (!maybeSocket) return;\n\n // Reinitialize channel connections incase the socket changed\n this.channel = maybeSocket.channel(\n `feeds:${this.userFeedId}`,\n this.defaultOptions,\n );\n\n this.channel.on(\"new-message\", (resp) => this.onNewMessageReceived(resp));\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setupAutoSocketManager();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates) {\n if (!maybeSocket.isConnected()) maybeSocket.connect();\n this.channel.join();\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setupAutoSocketManager() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private teardownAutoSocketManager() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n this.initializeRealtimeConnection();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","Feed","knock","feedId","options","__publicField","createStore","EventEmitter","maybeSocket","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","normalizedItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","itemsToUpdate","direction","status","payload","stringifiedPayload","e","resp","disconnectDelay","client","_a"],"mappings":";;;;;;AAgCA,MAAMA,IAA0D;AAAA,EAC9D,UAAU;AACZ,GAEMC,IAA2B;AAEjC,MAAMC,EAAK;AAAA,EAcT,YACWC,GACAC,GACTC,GACA;AAjBM,IAAAC,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA,yBAAwD;AACxD,IAAAA,EAAA,wCAA0C;AAC1C,IAAAA,EAAA,iCAAsC,MAAM;AAAA,IAAA;AAC5C,IAAAA,EAAA,2CAA6C;AAG9C;AAAA,IAAAA,EAAA;AAGI,SAAA,QAAAH,GACA,KAAA,SAAAC,GAGT,KAAK,SAASA,GACT,KAAA,aAAa,KAAK,mBACvB,KAAK,QAAQG,KACR,KAAA,cAAc,IAAIC,EAAa,EAAE,UAAU,IAAM,WAAW,KAAK,GACtE,KAAK,iBAAiB,EAAE,GAAGR,GAAoB,GAAGK,EAAQ,GAE1D,KAAK,MAAM,IAAI,wCAAwCD,CAAM,EAAE,GAG/D,KAAK,6BAA6B,GAElC,KAAK,sBAAsB;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA,EAKA,eAAe;AAER,SAAA,aAAa,KAAK,mBAGvB,KAAK,6BAA6B,GAGlC,KAAK,sBAAsB;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAW;AAC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vC,EAAY,YAAY,OAAe,QAAQ,GACpD,KAAK,QAAQ;EAEjB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,yBAAyB;AAC/B,IACE,OAAO,WAAa,OACpB,KAAK,sCAKP,KAAK,0BAA0B,KAAK,uBAAuB,KAAK,IAAI,GACpE,KAAK,oCAAoC,IAChC,SAAA,iBAAiB,oBAAoB,KAAK,uBAAuB;AAAA,EAC5E;AAAA,EAEQ,4BAA4B;AAC9B,IAAA,OAAO,WAAa,QAEf,SAAA;AAAA,MACP;AAAA,MACA,KAAK;AAAA,IAAA,GAEP,KAAK,oCAAoC;AAAA,EAC3C;AAAA,EAEQ,UACN+B,GAQAzB,GACA;AAEA,SAAK,YAAY,KAAK,SAASyB,CAAI,IAAI,EAAE,OAAAzB,GAAO,GAChD,KAAK,YAAY,KAAK,SAASyB,CAAI,IAAI,EAAE,OAAAzB,GAAO,GAEhD,KAAK,qBAAqB,SAASyB,CAAI,IAAI,EAAE,OAAAzB,GAAO;AAAA,EACtD;AAAA,EAEQ,yBAAyB;;AACzB,UAAAkC,IACJ,KAAK,eAAe,uCACpBhD,GAEIiD,IAAS,KAAK,MAAM,OAAO;AAE7B,IAAA,SAAS,oBAAoB,WAE1B,KAAA,kBAAkB,WAAW,MAAM;;AACtC,OAAAC,IAAAD,EAAO,WAAP,QAAAC,EAAe,cACf,KAAK,kBAAkB;AAAA,OACtBF,CAAe,IACT,SAAS,oBAAoB,cAGlC,KAAK,oBACP,aAAa,KAAK,eAAe,GACjC,KAAK,kBAAkB,QAIpBE,IAAAD,EAAO,WAAP,QAAAC,EAAe,iBAClB,KAAK,6BAA6B;AAAA,EAGxC;AACF;"}
|
|
1
|
+
{"version":3,"file":"feed.mjs","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { Channel } from \"phoenix\";\nimport { StoreApi } from \"zustand\";\n\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n} from \"./interfaces\";\nimport createStore from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n FeedStoreState,\n} from \"./types\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nclass Feed {\n private userFeedId: string;\n private channel?: Channel;\n private broadcaster: EventEmitter;\n private defaultOptions: FeedClientOptions;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: StoreApi<FeedStoreState>;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n ) {\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = { ...feedClientDefaults, ...options };\n\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize() {\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n if (this.channel) {\n this.channel.leave();\n this.channel.off(\"new-message\");\n }\n\n this.teardownAutoSocketManager();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\n \"[Feed] User is not authenticated, skipping listening for updates\",\n );\n return;\n }\n\n const maybeSocket = this.knock.client().socket;\n\n // Connect the socket only if we don't already have a connection\n if (maybeSocket && !maybeSocket.isConnected()) {\n maybeSocket.connect();\n }\n\n // Only join the channel if we're not already in a joining state\n if (this.channel && [\"closed\", \"errored\"].includes(this.channel.state)) {\n this.channel.join();\n }\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on archiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\"[Feed] User is not authenticated, skipping fetch\");\n return;\n }\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n this.knock.log(\"[Feed] Request is in flight, skipping fetch\");\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // Always include the default params, if they have been set\n const queryParams = {\n ...this.defaultOptions,\n ...options,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage() {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({\n metadata,\n }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n // Optimistically set the badge counts\n state.setMetadata(metadata);\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // Tnis is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n const { socket: maybeSocket } = this.knock.client();\n\n // In server environments we might not have a socket connection\n if (!maybeSocket) return;\n\n // Reinitialize channel connections incase the socket changed\n this.channel = maybeSocket.channel(\n `feeds:${this.userFeedId}`,\n this.defaultOptions,\n );\n\n this.channel.on(\"new-message\", (resp) => this.onNewMessageReceived(resp));\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setupAutoSocketManager();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {\n if (!maybeSocket.isConnected()) maybeSocket.connect();\n this.channel.join();\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setupAutoSocketManager() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private teardownAutoSocketManager() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n this.initializeRealtimeConnection();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","Feed","knock","feedId","options","__publicField","createStore","EventEmitter","maybeSocket","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","payload","stringifiedPayload","e","resp","disconnectDelay","client","_a"],"mappings":";;;;;;AAgCA,MAAMA,IAA0D;AAAA,EAC9D,UAAU;AACZ,GAEMC,IAA2B;AAEjC,MAAMC,EAAK;AAAA,EAcT,YACWC,GACAC,GACTC,GACA;AAjBM,IAAAC,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA,yBAAwD;AACxD,IAAAA,EAAA,wCAA0C;AAC1C,IAAAA,EAAA,iCAAsC,MAAM;AAAA,IAAA;AAC5C,IAAAA,EAAA,2CAA6C;AA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AAoC;AAAA,EAC3C;AAAA,EAEQ,UACN8B,GAQAxB,GACA;AAEA,SAAK,YAAY,KAAK,SAASwB,CAAI,IAAI,EAAE,OAAAxB,GAAO,GAChD,KAAK,YAAY,KAAK,SAASwB,CAAI,IAAI,EAAE,OAAAxB,GAAO,GAEhD,KAAK,qBAAqB,SAASwB,CAAI,IAAI,EAAE,OAAAxB,GAAO;AAAA,EACtD;AAAA,EAEQ,yBAAyB;;AACzB,UAAAkC,IACJ,KAAK,eAAe,uCACpBhD,GAEIiD,IAAS,KAAK,MAAM,OAAO;AAE7B,IAAA,SAAS,oBAAoB,WAE1B,KAAA,kBAAkB,WAAW,MAAM;;AACtC,OAAAC,IAAAD,EAAO,WAAP,QAAAC,EAAe,cACf,KAAK,kBAAkB;AAAA,OACtBF,CAAe,IACT,SAAS,oBAAoB,cAGlC,KAAK,oBACP,aAAa,KAAK,eAAe,GACjC,KAAK,kBAAkB,QAIpBE,IAAAD,EAAO,WAAP,QAAAC,EAAe,iBAClB,KAAK,6BAA6B;AAAA,EAGxC;AACF;"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
var c = Object.defineProperty;
|
|
2
|
+
var o = (s, t, e) => t in s ? c(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
|
|
3
|
+
var r = (s, t, e) => o(s, typeof t != "symbol" ? t + "" : t, e);
|
|
4
|
+
import { TENANT_OBJECT_COLLECTION as n } from "../objects/constants.mjs";
|
|
5
|
+
class l {
|
|
6
|
+
constructor(t) {
|
|
7
|
+
r(this, "instance");
|
|
8
|
+
this.instance = t;
|
|
9
|
+
}
|
|
10
|
+
async authCheck({ tenant: t, knockChannelId: e }) {
|
|
11
|
+
const a = await this.instance.client().makeRequest({
|
|
12
|
+
method: "GET",
|
|
13
|
+
url: `/v1/providers/ms-teams/${e}/auth_check`,
|
|
14
|
+
params: {
|
|
15
|
+
ms_teams_tenant_object: {
|
|
16
|
+
object_id: t,
|
|
17
|
+
collection: n
|
|
18
|
+
},
|
|
19
|
+
channel_id: e
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
return this.handleResponse(a);
|
|
23
|
+
}
|
|
24
|
+
async revokeAccessToken({
|
|
25
|
+
tenant: t,
|
|
26
|
+
knockChannelId: e
|
|
27
|
+
}) {
|
|
28
|
+
const a = await this.instance.client().makeRequest({
|
|
29
|
+
method: "PUT",
|
|
30
|
+
url: `/v1/providers/ms-teams/${e}/revoke_access`,
|
|
31
|
+
params: {
|
|
32
|
+
ms_teams_tenant_object: {
|
|
33
|
+
object_id: t,
|
|
34
|
+
collection: n
|
|
35
|
+
},
|
|
36
|
+
channel_id: e
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
return this.handleResponse(a);
|
|
40
|
+
}
|
|
41
|
+
handleResponse(t) {
|
|
42
|
+
var e, a;
|
|
43
|
+
if (t.statusCode === "error") {
|
|
44
|
+
if (((a = (e = t.error) == null ? void 0 : e.response) == null ? void 0 : a.status) < 500)
|
|
45
|
+
return t.error || t.body;
|
|
46
|
+
throw new Error(t.error || t.body);
|
|
47
|
+
}
|
|
48
|
+
return t.body;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export {
|
|
52
|
+
l as default
|
|
53
|
+
};
|
|
54
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../../../src/clients/ms-teams/index.ts"],"sourcesContent":["import { ApiResponse } from \"../../api\";\nimport { AuthCheckInput, RevokeAccessTokenInput } from \"../../interfaces\";\nimport Knock from \"../../knock\";\nimport { TENANT_OBJECT_COLLECTION } from \"../objects/constants\";\n\nclass MsTeamsClient {\n private instance: Knock;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n async authCheck({ tenant: tenantId, knockChannelId }: AuthCheckInput) {\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/providers/ms-teams/${knockChannelId}/auth_check`,\n params: {\n ms_teams_tenant_object: {\n object_id: tenantId,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n },\n });\n\n return this.handleResponse(result);\n }\n\n async revokeAccessToken({\n tenant: tenantId,\n knockChannelId,\n }: RevokeAccessTokenInput) {\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/providers/ms-teams/${knockChannelId}/revoke_access`,\n params: {\n ms_teams_tenant_object: {\n object_id: tenantId,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n },\n });\n\n return this.handleResponse(result);\n }\n\n private handleResponse(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n if (response.error?.response?.status < 500) {\n return response.error || response.body;\n }\n throw new Error(response.error || response.body);\n }\n\n return response.body;\n }\n}\n\nexport default MsTeamsClient;\n"],"names":["MsTeamsClient","instance","__publicField","tenantId","knockChannelId","result","TENANT_OBJECT_COLLECTION","response","_b","_a"],"mappings":";;;;AAKA,MAAMA,EAAc;AAAA,EAGlB,YAAYC,GAAiB;AAFrB,IAAAC,EAAA;AAGN,SAAK,WAAWD;AAAA,EAClB;AAAA,EAEA,MAAM,UAAU,EAAE,QAAQE,GAAU,gBAAAC,KAAkC;AACpE,UAAMC,IAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY;AAAA,MACtD,QAAQ;AAAA,MACR,KAAK,0BAA0BD,CAAc;AAAA,MAC7C,QAAQ;AAAA,QACN,wBAAwB;AAAA,UACtB,WAAWD;AAAA,UACX,YAAYG;AAAA,QACd;AAAA,QACA,YAAYF;AAAA,MACd;AAAA,IAAA,CACD;AAEM,WAAA,KAAK,eAAeC,CAAM;AAAA,EACnC;AAAA,EAEA,MAAM,kBAAkB;AAAA,IACtB,QAAQF;AAAA,IACR,gBAAAC;AAAA,EAAA,GACyB;AACzB,UAAMC,IAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY;AAAA,MACtD,QAAQ;AAAA,MACR,KAAK,0BAA0BD,CAAc;AAAA,MAC7C,QAAQ;AAAA,QACN,wBAAwB;AAAA,UACtB,WAAWD;AAAA,UACX,YAAYG;AAAA,QACd;AAAA,QACA,YAAYF;AAAA,MACd;AAAA,IAAA,CACD;AAEM,WAAA,KAAK,eAAeC,CAAM;AAAA,EACnC;AAAA,EAEQ,eAAeE,GAAuB;;AACxC,QAAAA,EAAS,eAAe,SAAS;AACnC,YAAIC,KAAAC,IAAAF,EAAS,UAAT,gBAAAE,EAAgB,aAAhB,gBAAAD,EAA0B,UAAS;AAC9B,eAAAD,EAAS,SAASA,EAAS;AAEpC,YAAM,IAAI,MAAMA,EAAS,SAASA,EAAS,IAAI;AAAA,IACjD;AAEA,WAAOA,EAAS;AAAA,EAClB;AACF;"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
var i = Object.defineProperty;
|
|
2
2
|
var l = (c, e, t) => e in c ? i(c, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : c[e] = t;
|
|
3
|
-
var
|
|
4
|
-
|
|
5
|
-
class
|
|
3
|
+
var n = (c, e, t) => l(c, typeof e != "symbol" ? e + "" : e, t);
|
|
4
|
+
import { TENANT_OBJECT_COLLECTION as a } from "../objects/constants.mjs";
|
|
5
|
+
class h {
|
|
6
6
|
constructor(e) {
|
|
7
|
-
|
|
7
|
+
n(this, "instance");
|
|
8
8
|
this.instance = e;
|
|
9
9
|
}
|
|
10
10
|
async authCheck({ tenant: e, knockChannelId: t }) {
|
|
@@ -22,7 +22,7 @@ class u {
|
|
|
22
22
|
return this.handleResponse(s);
|
|
23
23
|
}
|
|
24
24
|
async getChannels(e) {
|
|
25
|
-
const { knockChannelId: t, tenant: s } = e,
|
|
25
|
+
const { knockChannelId: t, tenant: s } = e, r = e.queryOptions || {}, o = await this.instance.client().makeRequest({
|
|
26
26
|
method: "GET",
|
|
27
27
|
url: `/v1/providers/slack/${t}/channels`,
|
|
28
28
|
params: {
|
|
@@ -32,11 +32,11 @@ class u {
|
|
|
32
32
|
},
|
|
33
33
|
channel_id: t,
|
|
34
34
|
query_options: {
|
|
35
|
-
cursor:
|
|
36
|
-
limit:
|
|
37
|
-
exclude_archived:
|
|
38
|
-
team_id:
|
|
39
|
-
types:
|
|
35
|
+
cursor: r.cursor,
|
|
36
|
+
limit: r.limit,
|
|
37
|
+
exclude_archived: r.excludeArchived,
|
|
38
|
+
team_id: r.teamId,
|
|
39
|
+
types: r.types
|
|
40
40
|
}
|
|
41
41
|
}
|
|
42
42
|
});
|
|
@@ -67,6 +67,6 @@ class u {
|
|
|
67
67
|
}
|
|
68
68
|
}
|
|
69
69
|
export {
|
|
70
|
-
|
|
70
|
+
h as default
|
|
71
71
|
};
|
|
72
72
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../../../src/clients/slack/index.ts"],"sourcesContent":["import { ApiResponse } from \"../../api\";\nimport Knock from \"../../knock\";\
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../../../src/clients/slack/index.ts"],"sourcesContent":["import { ApiResponse } from \"../../api\";\nimport { AuthCheckInput, RevokeAccessTokenInput } from \"../../interfaces\";\nimport Knock from \"../../knock\";\nimport { TENANT_OBJECT_COLLECTION } from \"../objects/constants\";\n\nimport { GetSlackChannelsInput, GetSlackChannelsResponse } from \"./interfaces\";\n\nclass SlackClient {\n private instance: Knock;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n async authCheck({ tenant, knockChannelId }: AuthCheckInput) {\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/providers/slack/${knockChannelId}/auth_check`,\n params: {\n access_token_object: {\n object_id: tenant,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n },\n });\n\n return this.handleResponse(result);\n }\n\n async getChannels(\n input: GetSlackChannelsInput,\n ): Promise<GetSlackChannelsResponse> {\n const { knockChannelId, tenant } = input;\n const queryOptions = input.queryOptions || {};\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/providers/slack/${knockChannelId}/channels`,\n params: {\n access_token_object: {\n object_id: tenant,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n query_options: {\n cursor: queryOptions.cursor,\n limit: queryOptions.limit,\n exclude_archived: queryOptions.excludeArchived,\n team_id: queryOptions.teamId,\n types: queryOptions.types,\n },\n },\n });\n\n return this.handleResponse(result);\n }\n\n async revokeAccessToken({ tenant, knockChannelId }: RevokeAccessTokenInput) {\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/providers/slack/${knockChannelId}/revoke_access`,\n params: {\n access_token_object: {\n object_id: tenant,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n },\n });\n\n return this.handleResponse(result);\n }\n\n private handleResponse(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n if (response.error?.response?.status < 500) {\n return response.error || response.body;\n }\n throw new Error(response.error || response.body);\n }\n\n return response.body;\n }\n}\n\nexport default SlackClient;\n"],"names":["SlackClient","instance","__publicField","tenant","knockChannelId","result","TENANT_OBJECT_COLLECTION","input","queryOptions","response","_b","_a"],"mappings":";;;;AAOA,MAAMA,EAAY;AAAA,EAGhB,YAAYC,GAAiB;AAFrB,IAAAC,EAAA;AAGN,SAAK,WAAWD;AAAA,EAClB;AAAA,EAEA,MAAM,UAAU,EAAE,QAAAE,GAAQ,gBAAAC,KAAkC;AAC1D,UAAMC,IAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY;AAAA,MACtD,QAAQ;AAAA,MACR,KAAK,uBAAuBD,CAAc;AAAA,MAC1C,QAAQ;AAAA,QACN,qBAAqB;AAAA,UACnB,WAAWD;AAAA,UACX,YAAYG;AAAA,QACd;AAAA,QACA,YAAYF;AAAA,MACd;AAAA,IAAA,CACD;AAEM,WAAA,KAAK,eAAeC,CAAM;AAAA,EACnC;AAAA,EAEA,MAAM,YACJE,GACmC;AAC7B,UAAA,EAAE,gBAAAH,GAAgB,QAAAD,EAAW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(s, e, t) => e in s ? i(s, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : s[e] = t;
|
|
3
|
+
var a = (s, e, t) => u(s, typeof e != "symbol" ? e + "" : e, t);
|
|
4
|
+
const r = "default";
|
|
5
5
|
class l {
|
|
6
6
|
constructor(e) {
|
|
7
|
-
|
|
7
|
+
a(this, "instance");
|
|
8
8
|
this.instance = e;
|
|
9
9
|
}
|
|
10
10
|
async get() {
|
|
@@ -15,12 +15,12 @@ class l {
|
|
|
15
15
|
return this.handleResponse(e);
|
|
16
16
|
}
|
|
17
17
|
async identify(e = {}) {
|
|
18
|
-
const
|
|
18
|
+
const t = await this.instance.client().makeRequest({
|
|
19
19
|
method: "PUT",
|
|
20
20
|
url: `/v1/users/${this.instance.userId}`,
|
|
21
21
|
params: e
|
|
22
22
|
});
|
|
23
|
-
return this.handleResponse(
|
|
23
|
+
return this.handleResponse(t);
|
|
24
24
|
}
|
|
25
25
|
async getAllPreferences() {
|
|
26
26
|
const e = await this.instance.client().makeRequest({
|
|
@@ -30,46 +30,38 @@ class l {
|
|
|
30
30
|
return this.handleResponse(e);
|
|
31
31
|
}
|
|
32
32
|
async getPreferences(e = {}) {
|
|
33
|
-
const
|
|
33
|
+
const t = e.preferenceSet || r, n = await this.instance.client().makeRequest({
|
|
34
34
|
method: "GET",
|
|
35
|
-
url: `/v1/users/${this.instance.userId}/preferences/${
|
|
35
|
+
url: `/v1/users/${this.instance.userId}/preferences/${t}`,
|
|
36
36
|
params: { tenant: e.tenant }
|
|
37
37
|
});
|
|
38
|
-
return this.handleResponse(
|
|
38
|
+
return this.handleResponse(n);
|
|
39
39
|
}
|
|
40
|
-
async setPreferences(e,
|
|
41
|
-
const
|
|
40
|
+
async setPreferences(e, t = {}) {
|
|
41
|
+
const n = t.preferenceSet || r, c = await this.instance.client().makeRequest({
|
|
42
42
|
method: "PUT",
|
|
43
|
-
url: `/v1/users/${this.instance.userId}/preferences/${
|
|
43
|
+
url: `/v1/users/${this.instance.userId}/preferences/${n}`,
|
|
44
44
|
data: e
|
|
45
45
|
});
|
|
46
|
-
return this.handleResponse(
|
|
46
|
+
return this.handleResponse(c);
|
|
47
47
|
}
|
|
48
48
|
async getChannelData(e) {
|
|
49
|
-
const
|
|
49
|
+
const t = await this.instance.client().makeRequest({
|
|
50
50
|
method: "GET",
|
|
51
51
|
url: `/v1/users/${this.instance.userId}/channel_data/${e.channelId}`
|
|
52
52
|
});
|
|
53
|
-
return this.handleResponse(
|
|
53
|
+
return this.handleResponse(t);
|
|
54
54
|
}
|
|
55
55
|
async setChannelData({
|
|
56
56
|
channelId: e,
|
|
57
|
-
channelData:
|
|
57
|
+
channelData: t
|
|
58
58
|
}) {
|
|
59
|
-
const
|
|
59
|
+
const n = await this.instance.client().makeRequest({
|
|
60
60
|
method: "PUT",
|
|
61
61
|
url: `/v1/users/${this.instance.userId}/channel_data/${e}`,
|
|
62
|
-
data: { data:
|
|
63
|
-
});
|
|
64
|
-
return this.handleResponse(t);
|
|
65
|
-
}
|
|
66
|
-
async getInAppMessages({ channelId: e, messageType: s, params: t }) {
|
|
67
|
-
const a = await this.instance.client().makeRequest({
|
|
68
|
-
method: "GET",
|
|
69
|
-
url: `/v1/users/${this.instance.userId}/in-app-messages/${e}/${s}`,
|
|
70
|
-
params: t
|
|
62
|
+
data: { data: t }
|
|
71
63
|
});
|
|
72
|
-
return this.handleResponse(
|
|
64
|
+
return this.handleResponse(n);
|
|
73
65
|
}
|
|
74
66
|
handleResponse(e) {
|
|
75
67
|
if (e.statusCode === "error")
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../../../src/clients/users/index.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\n\nimport { ApiResponse } from \"../../api\";\nimport { ChannelData, User } from \"../../interfaces\";\nimport Knock from \"../../knock\";\nimport {
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../../../src/clients/users/index.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\n\nimport { ApiResponse } from \"../../api\";\nimport { ChannelData, User } from \"../../interfaces\";\nimport Knock from \"../../knock\";\nimport {\n GetPreferencesOptions,\n PreferenceOptions,\n PreferenceSet,\n SetPreferencesProperties,\n} from \"../preferences/interfaces\";\n\nimport { GetChannelDataInput, SetChannelDataInput } from \"./interfaces\";\n\nconst DEFAULT_PREFERENCE_SET_ID = \"default\";\n\nclass UserClient {\n private instance: Knock;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n async get() {\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}`,\n });\n\n return this.handleResponse<User>(result);\n }\n\n async identify(props: GenericData = {}) {\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}`,\n params: props,\n });\n\n return this.handleResponse<User>(result);\n }\n\n async getAllPreferences() {\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/preferences`,\n });\n\n return this.handleResponse<PreferenceSet[]>(result);\n }\n\n async getPreferences(\n options: GetPreferencesOptions = {},\n ): Promise<PreferenceSet> {\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}`,\n params: { tenant: options.tenant },\n });\n\n return this.handleResponse<PreferenceSet>(result);\n }\n\n async setPreferences(\n preferenceSet: SetPreferencesProperties,\n options: PreferenceOptions = {},\n ): Promise<PreferenceSet> {\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}`,\n data: preferenceSet,\n });\n\n return this.handleResponse<PreferenceSet>(result);\n }\n\n async getChannelData<T = GenericData>(params: GetChannelDataInput) {\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/channel_data/${params.channelId}`,\n });\n\n return this.handleResponse<ChannelData<T>>(result);\n }\n\n async setChannelData<T = GenericData>({\n channelId,\n channelData,\n }: SetChannelDataInput) {\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/channel_data/${channelId}`,\n data: { data: channelData },\n });\n\n return this.handleResponse<ChannelData<T>>(result);\n }\n\n private handleResponse<T>(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n throw new Error(response.error || response.body);\n }\n\n return response.body as T;\n }\n}\n\nexport default UserClient;\n"],"names":["DEFAULT_PREFERENCE_SET_ID","UserClient","instance","__publicField","result","props","options","preferenceSetId","preferenceSet","params","channelId","channelData","response"],"mappings":";;;AAcA,MAAMA,IAA4B;AAElC,MAAMC,EAAW;AAAA,EAGf,YAAYC,GAAiB;AAFrB,IAAAC,EAAA;AAGN,SAAK,WAAWD;AAAA,EAClB;AAAA,EAEA,MAAM,MAAM;AACV,UAAME,IAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY;AAAA,MACtD,QAAQ;AAAA,MACR,KAAK,aAAa,KAAK,SAAS,MAAM;AAAA,IAAA,CACvC;AAEM,WAAA,KAAK,eAAqBA,CAAM;AAAA,EACzC;AAAA,EAEA,MAAM,SAASC,IAAqB,IAAI;AACtC,UAAMD,IAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY;AAAA,MACtD,QAAQ;AAAA,MACR,KAAK,aAAa,KAAK,SAAS,MAAM;AAAA,MACtC,QAAQC;AAAA,IAAA,CACT;AAEM,WAAA,KAAK,eAAqBD,CAAM;AAAA,EACzC;AAAA,EAEA,MAAM,oBAAoB;AACxB,UAAMA,IAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY;AAAA,MACtD,QAAQ;AAAA,MACR,KAAK,aAAa,KAAK,SAAS,MAAM;AAAA,IAAA,CACvC;AAEM,WAAA,KAAK,eAAgCA,CAAM;AAAA,EACpD;AAAA,EAEA,MAAM,eACJE,IA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