@knocklabs/client 0.14.10 → 0.15.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.
- package/CHANGELOG.md +16 -0
- package/dist/cjs/api.js +2 -0
- package/dist/cjs/api.js.map +1 -0
- package/dist/cjs/clients/feed/feed.js +2 -0
- package/dist/cjs/clients/feed/feed.js.map +1 -0
- package/dist/cjs/clients/feed/index.js +2 -0
- package/dist/cjs/clients/feed/index.js.map +1 -0
- package/dist/cjs/clients/feed/socket-manager.js +2 -0
- package/dist/cjs/clients/feed/socket-manager.js.map +1 -0
- package/dist/cjs/clients/feed/store.js +2 -0
- package/dist/cjs/clients/feed/store.js.map +1 -0
- package/dist/cjs/clients/feed/utils.js +2 -0
- package/dist/cjs/clients/feed/utils.js.map +1 -0
- package/dist/cjs/clients/guide/client.js +2 -0
- package/dist/cjs/clients/guide/client.js.map +1 -0
- package/dist/cjs/clients/messages/index.js +2 -0
- package/dist/cjs/clients/messages/index.js.map +1 -0
- 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/objects/constants.js +2 -0
- package/dist/cjs/clients/objects/constants.js.map +1 -0
- package/dist/cjs/clients/objects/index.js +2 -0
- package/dist/cjs/clients/objects/index.js.map +1 -0
- package/dist/cjs/clients/preferences/index.js +2 -0
- package/dist/cjs/clients/preferences/index.js.map +1 -0
- package/dist/cjs/clients/slack/index.js +2 -0
- package/dist/cjs/clients/slack/index.js.map +1 -0
- package/dist/cjs/clients/users/index.js +2 -0
- package/dist/cjs/clients/users/index.js.map +1 -0
- package/dist/cjs/helpers.js +2 -0
- package/dist/cjs/helpers.js.map +1 -0
- package/dist/cjs/index.js +2 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/knock.js +2 -0
- package/dist/cjs/knock.js.map +1 -0
- package/dist/cjs/networkStatus.js +2 -0
- package/dist/cjs/networkStatus.js.map +1 -0
- package/dist/esm/api.mjs +58 -0
- package/dist/esm/api.mjs.map +1 -0
- package/dist/esm/clients/feed/feed.mjs +422 -0
- package/dist/esm/clients/feed/feed.mjs.map +1 -0
- package/dist/esm/clients/feed/index.mjs +47 -0
- package/dist/esm/clients/feed/index.mjs.map +1 -0
- package/dist/esm/clients/feed/socket-manager.mjs +81 -0
- package/dist/esm/clients/feed/socket-manager.mjs.map +1 -0
- package/dist/esm/clients/feed/store.mjs +104 -0
- package/dist/esm/clients/feed/store.mjs.map +1 -0
- package/dist/esm/clients/feed/utils.mjs +35 -0
- package/dist/esm/clients/feed/utils.mjs.map +1 -0
- package/dist/esm/clients/guide/client.mjs +284 -0
- package/dist/esm/clients/guide/client.mjs.map +1 -0
- package/dist/esm/clients/messages/index.mjs +64 -0
- package/dist/esm/clients/messages/index.mjs.map +1 -0
- package/dist/esm/clients/ms-teams/index.mjs +91 -0
- package/dist/esm/clients/ms-teams/index.mjs.map +1 -0
- package/dist/esm/clients/objects/constants.mjs +5 -0
- package/dist/esm/clients/objects/constants.mjs.map +1 -0
- package/dist/esm/clients/objects/index.mjs +42 -0
- package/dist/esm/clients/objects/index.mjs.map +1 -0
- package/dist/esm/clients/preferences/index.mjs +128 -0
- package/dist/esm/clients/preferences/index.mjs.map +1 -0
- package/dist/esm/clients/slack/index.mjs +72 -0
- package/dist/esm/clients/slack/index.mjs.map +1 -0
- package/dist/esm/clients/users/index.mjs +99 -0
- package/dist/esm/clients/users/index.mjs.map +1 -0
- package/dist/esm/helpers.mjs +8 -0
- package/dist/esm/helpers.mjs.map +1 -0
- package/dist/esm/index.mjs +16 -0
- package/dist/esm/index.mjs.map +1 -0
- package/dist/esm/knock.mjs +108 -0
- package/dist/esm/knock.mjs.map +1 -0
- package/dist/esm/networkStatus.mjs +15 -0
- package/dist/esm/networkStatus.mjs.map +1 -0
- package/dist/types/api.d.ts +25 -0
- package/dist/types/api.d.ts.map +1 -0
- package/dist/types/clients/feed/feed.d.ts +75 -0
- package/dist/types/clients/feed/feed.d.ts.map +1 -0
- package/dist/types/clients/feed/index.d.ts +17 -0
- package/dist/types/clients/feed/index.d.ts.map +1 -0
- package/dist/types/clients/feed/interfaces.d.ts +99 -0
- package/dist/types/clients/feed/interfaces.d.ts.map +1 -0
- package/dist/types/clients/feed/socket-manager.d.ts +31 -0
- package/dist/types/clients/feed/socket-manager.d.ts.map +1 -0
- package/dist/types/clients/feed/store.d.ts +20 -0
- package/dist/types/clients/feed/store.d.ts.map +1 -0
- package/dist/types/clients/feed/types.d.ts +35 -0
- package/dist/types/clients/feed/types.d.ts.map +1 -0
- package/dist/types/clients/feed/utils.d.ts +20 -0
- package/dist/types/clients/feed/utils.d.ts.map +1 -0
- package/dist/types/clients/guide/client.d.ts +124 -0
- package/dist/types/clients/guide/client.d.ts.map +1 -0
- package/dist/types/clients/guide/index.d.ts +3 -0
- package/dist/types/clients/guide/index.d.ts.map +1 -0
- package/dist/types/clients/messages/index.d.ts +15 -0
- package/dist/types/clients/messages/index.d.ts.map +1 -0
- package/dist/types/clients/messages/interfaces.d.ts +46 -0
- package/dist/types/clients/messages/interfaces.d.ts.map +1 -0
- package/dist/types/clients/ms-teams/index.d.ts +14 -0
- package/dist/types/clients/ms-teams/index.d.ts.map +1 -0
- package/dist/types/clients/ms-teams/interfaces.d.ts +49 -0
- package/dist/types/clients/ms-teams/interfaces.d.ts.map +1 -0
- package/dist/types/clients/objects/constants.d.ts +2 -0
- package/dist/types/clients/objects/constants.d.ts.map +1 -0
- package/dist/types/clients/objects/index.d.ts +23 -0
- package/dist/types/clients/objects/index.d.ts.map +1 -0
- package/dist/types/clients/preferences/index.d.ts +46 -0
- package/dist/types/clients/preferences/index.d.ts.map +1 -0
- package/dist/types/clients/preferences/interfaces.d.ts +29 -0
- package/dist/types/clients/preferences/interfaces.d.ts.map +1 -0
- package/dist/types/clients/slack/index.d.ts +13 -0
- package/dist/types/clients/slack/index.d.ts.map +1 -0
- package/dist/types/clients/slack/interfaces.d.ts +29 -0
- package/dist/types/clients/slack/interfaces.d.ts.map +1 -0
- package/dist/types/clients/users/index.d.ts +22 -0
- package/dist/types/clients/users/index.d.ts.map +1 -0
- package/dist/types/clients/users/interfaces.d.ts +9 -0
- package/dist/types/clients/users/interfaces.d.ts.map +1 -0
- package/dist/types/helpers.d.ts +2 -0
- package/dist/types/helpers.d.ts.map +1 -0
- package/dist/types/index.d.ts +21 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/interfaces.d.ts +72 -0
- package/dist/types/interfaces.d.ts.map +1 -0
- package/dist/types/knock.d.ts +55 -0
- package/dist/types/knock.d.ts.map +1 -0
- package/dist/types/networkStatus.d.ts +8 -0
- package/dist/types/networkStatus.d.ts.map +1 -0
- package/package.json +2 -1
- package/src/interfaces.ts +6 -0
- package/src/knock.ts +52 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"networkStatus.js","sources":["../../src/networkStatus.ts"],"sourcesContent":["export enum NetworkStatus {\n // Performing a top level loading operation\n loading = \"loading\",\n\n // Performing a fetch more on some already loaded data\n fetchMore = \"fetchMore\",\n\n // No operation is currently in progress\n ready = \"ready\",\n\n // The last operation failed with an error\n error = \"error\",\n}\n\nexport function isRequestInFlight(networkStatus: NetworkStatus): boolean {\n return [NetworkStatus.loading, NetworkStatus.fetchMore].includes(\n networkStatus,\n );\n}\n"],"names":["NetworkStatus","isRequestInFlight","networkStatus"],"mappings":"gFAAY,IAAAA,GAAAA,IAEVA,EAAA,QAAU,UAGVA,EAAA,UAAY,YAGZA,EAAA,MAAQ,QAGRA,EAAA,MAAQ,QAXEA,IAAAA,GAAA,CAAA,CAAA,EAcL,SAASC,EAAkBC,EAAuC,CAChE,MAAA,CAAC,UAAuB,WAAA,EAAyB,SACtDA,CACF,CACF"}
|
package/dist/esm/api.mjs
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
var i = Object.defineProperty;
|
|
2
|
+
var a = (s, e, t) => e in s ? i(s, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : s[e] = t;
|
|
3
|
+
var r = (s, e, t) => a(s, typeof e != "symbol" ? e + "" : e, t);
|
|
4
|
+
import n from "axios";
|
|
5
|
+
import o from "axios-retry";
|
|
6
|
+
import { Socket as u } from "phoenix";
|
|
7
|
+
class y {
|
|
8
|
+
constructor(e) {
|
|
9
|
+
r(this, "host");
|
|
10
|
+
r(this, "apiKey");
|
|
11
|
+
r(this, "userToken");
|
|
12
|
+
r(this, "axiosClient");
|
|
13
|
+
r(this, "socket");
|
|
14
|
+
this.host = e.host, this.apiKey = e.apiKey, this.userToken = e.userToken || null, this.axiosClient = n.create({
|
|
15
|
+
baseURL: this.host,
|
|
16
|
+
headers: {
|
|
17
|
+
Accept: "application/json",
|
|
18
|
+
"Content-Type": "application/json",
|
|
19
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
20
|
+
"X-Knock-User-Token": this.userToken
|
|
21
|
+
}
|
|
22
|
+
}), typeof window < "u" && (this.socket = new u(`${this.host.replace("http", "ws")}/ws/v1`, {
|
|
23
|
+
params: {
|
|
24
|
+
user_token: this.userToken,
|
|
25
|
+
api_key: this.apiKey
|
|
26
|
+
}
|
|
27
|
+
})), o(this.axiosClient, {
|
|
28
|
+
retries: 3,
|
|
29
|
+
retryCondition: this.canRetryRequest,
|
|
30
|
+
retryDelay: o.exponentialDelay
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
async makeRequest(e) {
|
|
34
|
+
try {
|
|
35
|
+
const t = await this.axiosClient(e);
|
|
36
|
+
return {
|
|
37
|
+
statusCode: t.status < 300 ? "ok" : "error",
|
|
38
|
+
body: t.data,
|
|
39
|
+
error: void 0,
|
|
40
|
+
status: t.status
|
|
41
|
+
};
|
|
42
|
+
} catch (t) {
|
|
43
|
+
return console.error(t), {
|
|
44
|
+
statusCode: "error",
|
|
45
|
+
status: 500,
|
|
46
|
+
body: void 0,
|
|
47
|
+
error: t
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
canRetryRequest(e) {
|
|
52
|
+
return o.isNetworkError(e) ? !0 : e.response ? e.response.status >= 500 && e.response.status <= 599 || e.response.status === 429 : !1;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
export {
|
|
56
|
+
y as default
|
|
57
|
+
};
|
|
58
|
+
//# sourceMappingURL=api.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api.mjs","sources":["../../src/api.ts"],"sourcesContent":["import axios, { AxiosError, AxiosInstance, AxiosRequestConfig } from \"axios\";\nimport axiosRetry from \"axios-retry\";\nimport { Socket } from \"phoenix\";\n\ntype ApiClientOptions = {\n host: string;\n apiKey: string;\n userToken: string | undefined;\n};\n\nexport interface ApiResponse {\n // eslint-disable-next-line\n error?: any;\n // eslint-disable-next-line\n body?: any;\n statusCode: \"ok\" | \"error\";\n status: number;\n}\n\nclass ApiClient {\n private host: string;\n private apiKey: string;\n private userToken: string | null;\n private axiosClient: AxiosInstance;\n\n public socket: Socket | undefined;\n\n constructor(options: ApiClientOptions) {\n this.host = options.host;\n this.apiKey = options.apiKey;\n this.userToken = options.userToken || null;\n\n // Create a retryable axios client\n this.axiosClient = axios.create({\n baseURL: this.host,\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.apiKey}`,\n \"X-Knock-User-Token\": this.userToken,\n },\n });\n\n if (typeof window !== \"undefined\") {\n this.socket = new Socket(`${this.host.replace(\"http\", \"ws\")}/ws/v1`, {\n params: {\n user_token: this.userToken,\n api_key: this.apiKey,\n },\n });\n }\n\n axiosRetry(this.axiosClient, {\n retries: 3,\n retryCondition: this.canRetryRequest,\n retryDelay: axiosRetry.exponentialDelay,\n });\n }\n\n async makeRequest(req: AxiosRequestConfig): Promise<ApiResponse> {\n try {\n const result = await this.axiosClient(req);\n\n return {\n statusCode: result.status < 300 ? \"ok\" : \"error\",\n body: result.data,\n error: undefined,\n status: result.status,\n };\n\n // eslint:disable-next-line\n } catch (e: unknown) {\n console.error(e);\n\n return {\n statusCode: \"error\",\n status: 500,\n body: undefined,\n error: e,\n };\n }\n }\n\n private canRetryRequest(error: AxiosError) {\n // Retry Network Errors.\n if (axiosRetry.isNetworkError(error)) {\n return true;\n }\n\n if (!error.response) {\n // Cannot determine if the request can be retried\n return false;\n }\n\n // Retry Server Errors (5xx).\n if (error.response.status >= 500 && error.response.status <= 599) {\n return true;\n }\n\n // Retry if rate limited.\n if (error.response.status === 429) {\n return true;\n }\n\n return false;\n }\n}\n\nexport default ApiClient;\n"],"names":["ApiClient","options","__publicField","axios","Socket","axiosRetry","req","result","e","error"],"mappings":";;;;;;AAmBA,MAAMA,EAAU;AAAA,EAQd,YAAYC,GAA2B;AAP/B,IAAAC,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AAED,IAAAA,EAAA;AAGL,SAAK,OAAOD,EAAQ,MACpB,KAAK,SAASA,EAAQ,QACjB,KAAA,YAAYA,EAAQ,aAAa,MAGjC,KAAA,cAAcE,EAAM,OAAO;AAAA,MAC9B,SAAS,KAAK;AAAA,MACd,SAAS;AAAA,QACP,QAAQ;AAAA,QACR,gBAAgB;AAAA,QAChB,eAAe,UAAU,KAAK,MAAM;AAAA,QACpC,sBAAsB,KAAK;AAAA,MAAA;AAAA,IAC7B,CACD,GAEG,OAAO,SAAW,QACf,KAAA,SAAS,IAAIC,EAAO,GAAG,KAAK,KAAK,QAAQ,QAAQ,IAAI,CAAC,UAAU;AAAA,MACnE,QAAQ;AAAA,QACN,YAAY,KAAK;AAAA,QACjB,SAAS,KAAK;AAAA,MAAA;AAAA,IAChB,CACD,IAGHC,EAAW,KAAK,aAAa;AAAA,MAC3B,SAAS;AAAA,MACT,gBAAgB,KAAK;AAAA,MACrB,YAAYA,EAAW;AAAA,IAAA,CACxB;AAAA,EAAA;AAAA,EAGH,MAAM,YAAYC,GAA+C;AAC3D,QAAA;AACF,YAAMC,IAAS,MAAM,KAAK,YAAYD,CAAG;AAElC,aAAA;AAAA,QACL,YAAYC,EAAO,SAAS,MAAM,OAAO;AAAA,QACzC,MAAMA,EAAO;AAAA,QACb,OAAO;AAAA,QACP,QAAQA,EAAO;AAAA,MACjB;AAAA,aAGOC,GAAY;AACnB,qBAAQ,MAAMA,CAAC,GAER;AAAA,QACL,YAAY;AAAA,QACZ,QAAQ;AAAA,QACR,MAAM;AAAA,QACN,OAAOA;AAAA,MACT;AAAA,IAAA;AAAA,EACF;AAAA,EAGM,gBAAgBC,GAAmB;AAErC,WAAAJ,EAAW,eAAeI,CAAK,IAC1B,KAGJA,EAAM,WAMPA,EAAM,SAAS,UAAU,OAAOA,EAAM,SAAS,UAAU,OAKzDA,EAAM,SAAS,WAAW,MATrB;AAAA,EAaF;AAEX;"}
|
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
var p = Object.defineProperty;
|
|
2
|
+
var g = (u, e, t) => e in u ? p(u, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : u[e] = t;
|
|
3
|
+
var d = (u, e, t) => g(u, typeof e != "symbol" ? e + "" : e, t);
|
|
4
|
+
import k from "eventemitter2";
|
|
5
|
+
import { nanoid as _ } from "nanoid";
|
|
6
|
+
import { isValidUuid as v } from "../../helpers.mjs";
|
|
7
|
+
import { isRequestInFlight as S, NetworkStatus as m } from "../../networkStatus.mjs";
|
|
8
|
+
import { SocketEventType as y } from "./socket-manager.mjs";
|
|
9
|
+
import b from "./store.mjs";
|
|
10
|
+
import { mergeDateRangeParams as f, getFormattedTriggerData as I } from "./utils.mjs";
|
|
11
|
+
const U = {
|
|
12
|
+
archived: "exclude"
|
|
13
|
+
}, C = 2e3, w = "client_";
|
|
14
|
+
class P {
|
|
15
|
+
constructor(e, t, s, a) {
|
|
16
|
+
d(this, "defaultOptions");
|
|
17
|
+
d(this, "referenceId");
|
|
18
|
+
d(this, "unsubscribeFromSocketEvents");
|
|
19
|
+
d(this, "socketManager");
|
|
20
|
+
d(this, "userFeedId");
|
|
21
|
+
d(this, "broadcaster");
|
|
22
|
+
d(this, "broadcastChannel");
|
|
23
|
+
d(this, "disconnectTimer", null);
|
|
24
|
+
d(this, "hasSubscribedToRealTimeUpdates", !1);
|
|
25
|
+
d(this, "visibilityChangeHandler", () => {
|
|
26
|
+
});
|
|
27
|
+
d(this, "visibilityChangeListenerConnected", !1);
|
|
28
|
+
// The raw store instance, used for binding in React and other environments
|
|
29
|
+
d(this, "store");
|
|
30
|
+
this.knock = e, this.feedId = t, (!t || !v(t)) && this.knock.log(
|
|
31
|
+
"[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.",
|
|
32
|
+
!0
|
|
33
|
+
), this.feedId = t, this.userFeedId = this.buildUserFeedId(), this.referenceId = w + _(), this.socketManager = a, this.store = b(), this.broadcaster = new k({ wildcard: !0, delimiter: "." }), this.defaultOptions = {
|
|
34
|
+
...U,
|
|
35
|
+
...f(s)
|
|
36
|
+
}, this.knock.log(`[Feed] Initialized a feed on channel ${t}`), this.initializeRealtimeConnection(), this.setupBroadcastChannel();
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Used to reinitialize a current feed instance, which is useful when reauthenticating users
|
|
40
|
+
*/
|
|
41
|
+
reinitialize(e) {
|
|
42
|
+
this.socketManager = e, this.userFeedId = this.buildUserFeedId(), this.initializeRealtimeConnection(), this.setupBroadcastChannel();
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Cleans up a feed instance by destroying the store and disconnecting
|
|
46
|
+
* an open socket connection.
|
|
47
|
+
*/
|
|
48
|
+
teardown() {
|
|
49
|
+
var e;
|
|
50
|
+
this.knock.log("[Feed] Tearing down feed instance"), (e = this.socketManager) == null || e.leave(this), this.tearDownVisibilityListeners(), this.disconnectTimer && (clearTimeout(this.disconnectTimer), this.disconnectTimer = null), this.broadcastChannel && this.broadcastChannel.close();
|
|
51
|
+
}
|
|
52
|
+
/** Tears down an instance and removes it entirely from the feed manager */
|
|
53
|
+
dispose() {
|
|
54
|
+
this.knock.log("[Feed] Disposing of feed instance"), this.teardown(), this.broadcaster.removeAllListeners(), this.knock.feeds.removeInstance(this);
|
|
55
|
+
}
|
|
56
|
+
/*
|
|
57
|
+
Initializes a real-time connection to Knock, connecting the websocket for the
|
|
58
|
+
current ApiClient instance if the socket is not already connected.
|
|
59
|
+
*/
|
|
60
|
+
listenForUpdates() {
|
|
61
|
+
var e;
|
|
62
|
+
if (this.knock.log("[Feed] Connecting to real-time service"), this.hasSubscribedToRealTimeUpdates = !0, !this.knock.isAuthenticated()) {
|
|
63
|
+
this.knock.log(
|
|
64
|
+
"[Feed] User is not authenticated, skipping listening for updates"
|
|
65
|
+
);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
this.unsubscribeFromSocketEvents = (e = this.socketManager) == null ? void 0 : e.join(this);
|
|
69
|
+
}
|
|
70
|
+
/* Binds a handler to be invoked when event occurs */
|
|
71
|
+
on(e, t) {
|
|
72
|
+
this.broadcaster.on(e, t);
|
|
73
|
+
}
|
|
74
|
+
off(e, t) {
|
|
75
|
+
this.broadcaster.off(e, t);
|
|
76
|
+
}
|
|
77
|
+
getState() {
|
|
78
|
+
return this.store.getState();
|
|
79
|
+
}
|
|
80
|
+
async markAsSeen(e) {
|
|
81
|
+
const t = (/* @__PURE__ */ new Date()).toISOString();
|
|
82
|
+
return this.optimisticallyPerformStatusUpdate(
|
|
83
|
+
e,
|
|
84
|
+
"seen",
|
|
85
|
+
{ seen_at: t },
|
|
86
|
+
"unseen_count"
|
|
87
|
+
), this.makeStatusUpdate(e, "seen");
|
|
88
|
+
}
|
|
89
|
+
async markAllAsSeen() {
|
|
90
|
+
const { metadata: e, items: t, ...s } = this.store.getState();
|
|
91
|
+
if (this.defaultOptions.status === "unseen")
|
|
92
|
+
s.resetStore({
|
|
93
|
+
...e,
|
|
94
|
+
total_count: 0,
|
|
95
|
+
unseen_count: 0
|
|
96
|
+
});
|
|
97
|
+
else {
|
|
98
|
+
s.setMetadata({ ...e, unseen_count: 0 });
|
|
99
|
+
const i = { seen_at: (/* @__PURE__ */ new Date()).toISOString() }, n = t.map((o) => o.id);
|
|
100
|
+
s.setItemAttrs(n, i);
|
|
101
|
+
}
|
|
102
|
+
const r = await this.makeBulkStatusUpdate("seen");
|
|
103
|
+
return this.emitEvent("all_seen", t), r;
|
|
104
|
+
}
|
|
105
|
+
async markAsUnseen(e) {
|
|
106
|
+
return this.optimisticallyPerformStatusUpdate(
|
|
107
|
+
e,
|
|
108
|
+
"unseen",
|
|
109
|
+
{ seen_at: null },
|
|
110
|
+
"unseen_count"
|
|
111
|
+
), this.makeStatusUpdate(e, "unseen");
|
|
112
|
+
}
|
|
113
|
+
async markAsRead(e) {
|
|
114
|
+
const t = (/* @__PURE__ */ new Date()).toISOString();
|
|
115
|
+
return this.optimisticallyPerformStatusUpdate(
|
|
116
|
+
e,
|
|
117
|
+
"read",
|
|
118
|
+
{ read_at: t },
|
|
119
|
+
"unread_count"
|
|
120
|
+
), this.makeStatusUpdate(e, "read");
|
|
121
|
+
}
|
|
122
|
+
async markAllAsRead() {
|
|
123
|
+
const { metadata: e, items: t, ...s } = this.store.getState();
|
|
124
|
+
if (this.defaultOptions.status === "unread")
|
|
125
|
+
s.resetStore({
|
|
126
|
+
...e,
|
|
127
|
+
total_count: 0,
|
|
128
|
+
unread_count: 0
|
|
129
|
+
});
|
|
130
|
+
else {
|
|
131
|
+
s.setMetadata({ ...e, unread_count: 0 });
|
|
132
|
+
const i = { read_at: (/* @__PURE__ */ new Date()).toISOString() }, n = t.map((o) => o.id);
|
|
133
|
+
s.setItemAttrs(n, i);
|
|
134
|
+
}
|
|
135
|
+
const r = await this.makeBulkStatusUpdate("read");
|
|
136
|
+
return this.emitEvent("all_read", t), r;
|
|
137
|
+
}
|
|
138
|
+
async markAsUnread(e) {
|
|
139
|
+
return this.optimisticallyPerformStatusUpdate(
|
|
140
|
+
e,
|
|
141
|
+
"unread",
|
|
142
|
+
{ read_at: null },
|
|
143
|
+
"unread_count"
|
|
144
|
+
), this.makeStatusUpdate(e, "unread");
|
|
145
|
+
}
|
|
146
|
+
async markAsInteracted(e, t) {
|
|
147
|
+
const s = (/* @__PURE__ */ new Date()).toISOString();
|
|
148
|
+
return this.optimisticallyPerformStatusUpdate(
|
|
149
|
+
e,
|
|
150
|
+
"interacted",
|
|
151
|
+
{
|
|
152
|
+
read_at: s,
|
|
153
|
+
interacted_at: s
|
|
154
|
+
},
|
|
155
|
+
"unread_count"
|
|
156
|
+
), this.makeStatusUpdate(e, "interacted", t);
|
|
157
|
+
}
|
|
158
|
+
/*
|
|
159
|
+
Marking one or more items as archived should:
|
|
160
|
+
|
|
161
|
+
- Decrement the badge count for any unread / unseen items
|
|
162
|
+
- Remove the item from the feed list when the `archived` flag is "exclude" (default)
|
|
163
|
+
|
|
164
|
+
TODO: how do we handle rollbacks?
|
|
165
|
+
*/
|
|
166
|
+
async markAsArchived(e) {
|
|
167
|
+
const t = this.store.getState(), s = this.defaultOptions.archived === "exclude", a = Array.isArray(e) ? e : [e], r = a.map((i) => i.id);
|
|
168
|
+
if (s) {
|
|
169
|
+
const i = a.filter((c) => !c.seen_at).length, n = a.filter((c) => !c.read_at).length, o = {
|
|
170
|
+
...t.metadata,
|
|
171
|
+
// Ensure that the counts don't ever go below 0 on archiving where the client state
|
|
172
|
+
// gets out of sync with the server state
|
|
173
|
+
total_count: Math.max(0, t.metadata.total_count - a.length),
|
|
174
|
+
unseen_count: Math.max(0, t.metadata.unseen_count - i),
|
|
175
|
+
unread_count: Math.max(0, t.metadata.unread_count - n)
|
|
176
|
+
}, l = t.items.filter(
|
|
177
|
+
(c) => !r.includes(c.id)
|
|
178
|
+
);
|
|
179
|
+
t.setResult({
|
|
180
|
+
entries: l,
|
|
181
|
+
meta: o,
|
|
182
|
+
page_info: t.pageInfo
|
|
183
|
+
});
|
|
184
|
+
} else
|
|
185
|
+
t.setItemAttrs(r, { archived_at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
186
|
+
return this.makeStatusUpdate(e, "archived");
|
|
187
|
+
}
|
|
188
|
+
async markAllAsArchived() {
|
|
189
|
+
const { items: e, ...t } = this.store.getState();
|
|
190
|
+
if (this.defaultOptions.archived === "exclude")
|
|
191
|
+
t.resetStore();
|
|
192
|
+
else {
|
|
193
|
+
const r = e.map((i) => i.id);
|
|
194
|
+
t.setItemAttrs(r, { archived_at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
195
|
+
}
|
|
196
|
+
const a = await this.makeBulkStatusUpdate("archive");
|
|
197
|
+
return this.emitEvent("all_archived", e), a;
|
|
198
|
+
}
|
|
199
|
+
async markAllReadAsArchived() {
|
|
200
|
+
const { items: e, ...t } = this.store.getState(), a = e.filter((n) => n.read_at === null).map((n) => n.id);
|
|
201
|
+
if (t.setItemAttrs(a, {
|
|
202
|
+
archived_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
203
|
+
}), this.defaultOptions.archived === "exclude") {
|
|
204
|
+
const n = e.filter((l) => !a.includes(l.id)), o = {
|
|
205
|
+
...t.metadata,
|
|
206
|
+
total_count: n.length,
|
|
207
|
+
unread_count: 0
|
|
208
|
+
};
|
|
209
|
+
t.setResult({
|
|
210
|
+
entries: n,
|
|
211
|
+
meta: o,
|
|
212
|
+
page_info: t.pageInfo
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
return await this.makeBulkStatusUpdate("archive");
|
|
216
|
+
}
|
|
217
|
+
async markAsUnarchived(e) {
|
|
218
|
+
return this.optimisticallyPerformStatusUpdate(e, "unarchived", {
|
|
219
|
+
archived_at: null
|
|
220
|
+
}), this.makeStatusUpdate(e, "unarchived");
|
|
221
|
+
}
|
|
222
|
+
/* Fetches the feed content, appending it to the store */
|
|
223
|
+
async fetch(e = {}) {
|
|
224
|
+
const { networkStatus: t, ...s } = this.store.getState();
|
|
225
|
+
if (!this.knock.isAuthenticated()) {
|
|
226
|
+
this.knock.log("[Feed] User is not authenticated, skipping fetch");
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (S(t)) {
|
|
230
|
+
this.knock.log("[Feed] Request is in flight, skipping fetch");
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
s.setNetworkStatus(e.__loadingType ?? m.loading);
|
|
234
|
+
const a = I({
|
|
235
|
+
...this.defaultOptions,
|
|
236
|
+
...e
|
|
237
|
+
}), r = {
|
|
238
|
+
...this.defaultOptions,
|
|
239
|
+
...f(e),
|
|
240
|
+
trigger_data: a,
|
|
241
|
+
// Unset options that should not be sent to the API
|
|
242
|
+
__loadingType: void 0,
|
|
243
|
+
__fetchSource: void 0,
|
|
244
|
+
__experimentalCrossBrowserUpdates: void 0,
|
|
245
|
+
auto_manage_socket_connection: void 0,
|
|
246
|
+
auto_manage_socket_connection_delay: void 0
|
|
247
|
+
}, i = await this.knock.client().makeRequest({
|
|
248
|
+
method: "GET",
|
|
249
|
+
url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,
|
|
250
|
+
params: r
|
|
251
|
+
});
|
|
252
|
+
if (i.statusCode === "error" || !i.body)
|
|
253
|
+
return s.setNetworkStatus(m.error), {
|
|
254
|
+
status: i.statusCode,
|
|
255
|
+
data: i.error || i.body
|
|
256
|
+
};
|
|
257
|
+
const n = {
|
|
258
|
+
entries: i.body.entries,
|
|
259
|
+
meta: i.body.meta,
|
|
260
|
+
page_info: i.body.page_info
|
|
261
|
+
};
|
|
262
|
+
if (e.before) {
|
|
263
|
+
const c = { shouldSetPage: !1, shouldAppend: !0 };
|
|
264
|
+
s.setResult(n, c);
|
|
265
|
+
} else if (e.after) {
|
|
266
|
+
const c = { shouldSetPage: !0, shouldAppend: !0 };
|
|
267
|
+
s.setResult(n, c);
|
|
268
|
+
} else
|
|
269
|
+
s.setResult(n);
|
|
270
|
+
this.broadcast("messages.new", n);
|
|
271
|
+
const o = e.__fetchSource === "socket" ? "items.received.realtime" : "items.received.page", l = {
|
|
272
|
+
items: n.entries,
|
|
273
|
+
metadata: n.meta,
|
|
274
|
+
event: o
|
|
275
|
+
};
|
|
276
|
+
return this.broadcast(l.event, l), { data: n, status: i.statusCode };
|
|
277
|
+
}
|
|
278
|
+
async fetchNextPage(e = {}) {
|
|
279
|
+
const { pageInfo: t } = this.store.getState();
|
|
280
|
+
t.after && this.fetch({
|
|
281
|
+
...e,
|
|
282
|
+
after: t.after,
|
|
283
|
+
__loadingType: m.fetchMore
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
get socketChannelTopic() {
|
|
287
|
+
return `feeds:${this.userFeedId}`;
|
|
288
|
+
}
|
|
289
|
+
broadcast(e, t) {
|
|
290
|
+
this.broadcaster.emit(e, t);
|
|
291
|
+
}
|
|
292
|
+
// Invoked when a new real-time message comes in from the socket
|
|
293
|
+
async onNewMessageReceived({ data: e }) {
|
|
294
|
+
var i;
|
|
295
|
+
this.knock.log("[Feed] Received new real-time message");
|
|
296
|
+
const { items: t, ...s } = this.store.getState(), a = t[0], r = (i = e[this.referenceId]) == null ? void 0 : i.metadata;
|
|
297
|
+
r && s.setMetadata(r), this.fetch({ before: a == null ? void 0 : a.__cursor, __fetchSource: "socket" });
|
|
298
|
+
}
|
|
299
|
+
buildUserFeedId() {
|
|
300
|
+
return `${this.feedId}:${this.knock.userId}`;
|
|
301
|
+
}
|
|
302
|
+
optimisticallyPerformStatusUpdate(e, t, s, a) {
|
|
303
|
+
const r = this.store.getState(), i = Array.isArray(e) ? e : [e], n = i.map((o) => o.id);
|
|
304
|
+
if (a) {
|
|
305
|
+
const { metadata: o } = r, l = i.filter((h) => {
|
|
306
|
+
switch (t) {
|
|
307
|
+
case "seen":
|
|
308
|
+
return h.seen_at === null;
|
|
309
|
+
case "unseen":
|
|
310
|
+
return h.seen_at !== null;
|
|
311
|
+
case "read":
|
|
312
|
+
case "interacted":
|
|
313
|
+
return h.read_at === null;
|
|
314
|
+
case "unread":
|
|
315
|
+
return h.read_at !== null;
|
|
316
|
+
default:
|
|
317
|
+
return !0;
|
|
318
|
+
}
|
|
319
|
+
}), c = t.startsWith("un") ? l.length : -l.length;
|
|
320
|
+
r.setMetadata({
|
|
321
|
+
...o,
|
|
322
|
+
[a]: Math.max(0, o[a] + c)
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
r.setItemAttrs(n, s);
|
|
326
|
+
}
|
|
327
|
+
async makeStatusUpdate(e, t, s) {
|
|
328
|
+
const a = Array.isArray(e) ? e : [e], r = a.map((n) => n.id), i = await this.knock.messages.batchUpdateStatuses(
|
|
329
|
+
r,
|
|
330
|
+
t,
|
|
331
|
+
{ metadata: s }
|
|
332
|
+
);
|
|
333
|
+
return this.emitEvent(t, a), i;
|
|
334
|
+
}
|
|
335
|
+
async makeBulkStatusUpdate(e) {
|
|
336
|
+
const t = {
|
|
337
|
+
user_ids: [this.knock.userId],
|
|
338
|
+
engagement_status: this.defaultOptions.status !== "all" ? this.defaultOptions.status : void 0,
|
|
339
|
+
archived: this.defaultOptions.archived,
|
|
340
|
+
has_tenant: this.defaultOptions.has_tenant,
|
|
341
|
+
tenants: this.defaultOptions.tenant ? [this.defaultOptions.tenant] : void 0
|
|
342
|
+
};
|
|
343
|
+
return await this.knock.messages.bulkUpdateAllStatusesInChannel({
|
|
344
|
+
channelId: this.feedId,
|
|
345
|
+
status: e,
|
|
346
|
+
options: t
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
setupBroadcastChannel() {
|
|
350
|
+
this.broadcastChannel = typeof self < "u" && "BroadcastChannel" in self ? new BroadcastChannel(`knock:feed:${this.userFeedId}`) : null, this.broadcastChannel && this.defaultOptions.__experimentalCrossBrowserUpdates === !0 && (this.broadcastChannel.onmessage = (e) => {
|
|
351
|
+
switch (e.data.type) {
|
|
352
|
+
case "items:archived":
|
|
353
|
+
case "items:unarchived":
|
|
354
|
+
case "items:seen":
|
|
355
|
+
case "items:unseen":
|
|
356
|
+
case "items:read":
|
|
357
|
+
case "items:unread":
|
|
358
|
+
case "items:all_read":
|
|
359
|
+
case "items:all_seen":
|
|
360
|
+
case "items:all_archived":
|
|
361
|
+
return this.fetch();
|
|
362
|
+
default:
|
|
363
|
+
return null;
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
broadcastOverChannel(e, t) {
|
|
368
|
+
if (this.broadcastChannel)
|
|
369
|
+
try {
|
|
370
|
+
const s = JSON.parse(JSON.stringify(t));
|
|
371
|
+
this.broadcastChannel.postMessage({
|
|
372
|
+
type: e,
|
|
373
|
+
payload: s
|
|
374
|
+
});
|
|
375
|
+
} catch (s) {
|
|
376
|
+
console.warn(`Could not broadcast ${e}, got error: ${s}`);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
initializeRealtimeConnection() {
|
|
380
|
+
var e;
|
|
381
|
+
this.socketManager && (this.defaultOptions.auto_manage_socket_connection && this.setUpVisibilityListeners(), this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated() && (this.unsubscribeFromSocketEvents = (e = this.socketManager) == null ? void 0 : e.join(this)));
|
|
382
|
+
}
|
|
383
|
+
async handleSocketEvent(e) {
|
|
384
|
+
switch (e.event) {
|
|
385
|
+
case y.NewMessage:
|
|
386
|
+
this.onNewMessageReceived(e);
|
|
387
|
+
return;
|
|
388
|
+
default: {
|
|
389
|
+
e.event;
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Listen for changes to document visibility and automatically disconnect
|
|
396
|
+
* or reconnect the socket after a delay
|
|
397
|
+
*/
|
|
398
|
+
setUpVisibilityListeners() {
|
|
399
|
+
typeof document > "u" || this.visibilityChangeListenerConnected || (this.visibilityChangeHandler = this.handleVisibilityChange.bind(this), this.visibilityChangeListenerConnected = !0, document.addEventListener("visibilitychange", this.visibilityChangeHandler));
|
|
400
|
+
}
|
|
401
|
+
tearDownVisibilityListeners() {
|
|
402
|
+
typeof document > "u" || (document.removeEventListener(
|
|
403
|
+
"visibilitychange",
|
|
404
|
+
this.visibilityChangeHandler
|
|
405
|
+
), this.visibilityChangeListenerConnected = !1);
|
|
406
|
+
}
|
|
407
|
+
emitEvent(e, t) {
|
|
408
|
+
this.broadcaster.emit(`items.${e}`, { items: t }), this.broadcaster.emit(`items:${e}`, { items: t }), this.broadcastOverChannel(`items:${e}`, { items: t });
|
|
409
|
+
}
|
|
410
|
+
handleVisibilityChange() {
|
|
411
|
+
var s, a;
|
|
412
|
+
const e = this.defaultOptions.auto_manage_socket_connection_delay ?? C, t = this.knock.client();
|
|
413
|
+
document.visibilityState === "hidden" ? this.disconnectTimer = setTimeout(() => {
|
|
414
|
+
var r;
|
|
415
|
+
(r = t.socket) == null || r.disconnect(), this.disconnectTimer = null;
|
|
416
|
+
}, e) : document.visibilityState === "visible" && (this.disconnectTimer && (clearTimeout(this.disconnectTimer), this.disconnectTimer = null), (s = t.socket) != null && s.isConnected() || (a = t.socket) == null || a.connect());
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
export {
|
|
420
|
+
P as default
|
|
421
|
+
};
|
|
422
|
+
//# sourceMappingURL=feed.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"feed.mjs","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { nanoid } from \"nanoid\";\n\nimport { isValidUuid } from \"../../helpers\";\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 FetchFeedOptionsForRequest,\n} from \"./interfaces\";\nimport {\n FeedSocketManager,\n SocketEventPayload,\n SocketEventType,\n} from \"./socket-manager\";\nimport createStore, { FeedStore } from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n} from \"./types\";\nimport { getFormattedTriggerData, mergeDateRangeParams } from \"./utils\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nconst CLIENT_REF_ID_PREFIX = \"client_\";\n\nclass Feed {\n public readonly defaultOptions: FeedClientOptions;\n public readonly referenceId: string;\n public unsubscribeFromSocketEvents: (() => void) | undefined = undefined;\n private socketManager: FeedSocketManager | undefined;\n private userFeedId: string;\n private broadcaster: EventEmitter;\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: FeedStore;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n socketManager: FeedSocketManager | undefined,\n ) {\n if (!feedId || !isValidUuid(feedId)) {\n this.knock.log(\n \"[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.\",\n true,\n );\n }\n\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.referenceId = CLIENT_REF_ID_PREFIX + nanoid();\n this.socketManager = socketManager;\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = {\n ...feedClientDefaults,\n ...mergeDateRangeParams(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(socketManager?: FeedSocketManager) {\n this.socketManager = socketManager;\n\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 this.socketManager?.leave(this);\n\n this.tearDownVisibilityListeners();\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 this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\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 // trigger_data should be a JSON string for the API\n // this function will format the trigger data if it's an object\n // https://docs.knock.app/reference#get-feed\n const formattedTriggerData = getFormattedTriggerData({\n ...this.defaultOptions,\n ...options,\n });\n\n // Always include the default params, if they have been set\n const queryParams: FetchFeedOptionsForRequest = {\n ...this.defaultOptions,\n ...mergeDateRangeParams(options),\n trigger_data: formattedTriggerData,\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(options: FetchFeedOptions = {}) {\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 ...options,\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n get socketChannelTopic(): string {\n return `feeds:${this.userFeedId}`;\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({ data }: 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\n // Optimistically set the badge counts\n const metadata = data[this.referenceId]?.metadata;\n if (metadata) {\n state.setMetadata(metadata);\n }\n\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 // This 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 // In server environments we might not have a socket connection\n if (!this.socketManager) return;\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setUpVisibilityListeners();\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 this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n }\n\n async handleSocketEvent(payload: SocketEventPayload) {\n switch (payload.event) {\n case SocketEventType.NewMessage:\n this.onNewMessageReceived(payload);\n return;\n default: {\n const _exhaustiveCheck: never = payload.event;\n return;\n }\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 setUpVisibilityListeners() {\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 tearDownVisibilityListeners() {\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 client.socket?.connect();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","CLIENT_REF_ID_PREFIX","Feed","knock","feedId","options","socketManager","__publicField","isValidUuid","nanoid","createStore","EventEmitter","mergeDateRangeParams","_a","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","formattedTriggerData","getFormattedTriggerData","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","payload","stringifiedPayload","e","SocketEventType","disconnectDelay","client","_b"],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,MAAM,OAAO;AAE7B,IAAA,SAAS,oBAAoB,WAE1B,KAAA,kBAAkB,WAAW,MAAM;;AACtC,OAAA3C,IAAA2C,EAAO,WAAP,QAAA3C,EAAe,cACf,KAAK,kBAAkB;AAAA,OACtB0C,CAAe,IACT,SAAS,oBAAoB,cAGlC,KAAK,oBACP,aAAa,KAAK,eAAe,GACjC,KAAK,kBAAkB,QAIpB1C,IAAA2C,EAAO,WAAP,QAAA3C,EAAe,kBAClB4C,IAAAD,EAAO,WAAP,QAAAC,EAAe;AAAA,EAEnB;AAEJ;"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
var i = Object.defineProperty;
|
|
2
|
+
var c = (n, e, t) => e in n ? i(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
|
|
3
|
+
var s = (n, e, t) => c(n, typeof e != "symbol" ? e + "" : e, t);
|
|
4
|
+
import o from "./feed.mjs";
|
|
5
|
+
import { FeedSocketManager as r } from "./socket-manager.mjs";
|
|
6
|
+
class k {
|
|
7
|
+
constructor(e) {
|
|
8
|
+
s(this, "instance");
|
|
9
|
+
s(this, "feedInstances", []);
|
|
10
|
+
s(this, "socketManager");
|
|
11
|
+
this.instance = e;
|
|
12
|
+
}
|
|
13
|
+
initialize(e, t = {}) {
|
|
14
|
+
this.initSocketManager();
|
|
15
|
+
const a = new o(
|
|
16
|
+
this.instance,
|
|
17
|
+
e,
|
|
18
|
+
t,
|
|
19
|
+
this.socketManager
|
|
20
|
+
);
|
|
21
|
+
return this.feedInstances.push(a), a;
|
|
22
|
+
}
|
|
23
|
+
removeInstance(e) {
|
|
24
|
+
this.feedInstances = this.feedInstances.filter((t) => t !== e);
|
|
25
|
+
}
|
|
26
|
+
teardownInstances() {
|
|
27
|
+
for (const e of this.feedInstances)
|
|
28
|
+
e.teardown();
|
|
29
|
+
}
|
|
30
|
+
reinitializeInstances() {
|
|
31
|
+
var e;
|
|
32
|
+
for (const t of this.feedInstances)
|
|
33
|
+
(e = this.socketManager) == null || e.leave(t);
|
|
34
|
+
this.socketManager = void 0, this.initSocketManager();
|
|
35
|
+
for (const t of this.feedInstances)
|
|
36
|
+
t.reinitialize(this.socketManager);
|
|
37
|
+
}
|
|
38
|
+
initSocketManager() {
|
|
39
|
+
const e = this.instance.client().socket;
|
|
40
|
+
e && !this.socketManager && (this.socketManager = new r(e));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export {
|
|
44
|
+
o as Feed,
|
|
45
|
+
k as default
|
|
46
|
+
};
|
|
47
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../../../src/clients/feed/index.ts"],"sourcesContent":["import Knock from \"../../knock\";\n\nimport Feed from \"./feed\";\nimport { FeedClientOptions } from \"./interfaces\";\nimport { FeedSocketManager } from \"./socket-manager\";\n\nclass FeedClient {\n private instance: Knock;\n private feedInstances: Feed[] = [];\n private socketManager: FeedSocketManager | undefined;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n initialize(feedChannelId: string, options: FeedClientOptions = {}) {\n this.initSocketManager();\n\n const feedInstance = new Feed(\n this.instance,\n feedChannelId,\n options,\n this.socketManager,\n );\n this.feedInstances.push(feedInstance);\n return feedInstance;\n }\n\n removeInstance(feed: Feed) {\n this.feedInstances = this.feedInstances.filter((f) => f !== feed);\n }\n\n teardownInstances() {\n for (const feed of this.feedInstances) {\n feed.teardown();\n }\n }\n\n reinitializeInstances() {\n for (const feed of this.feedInstances) {\n this.socketManager?.leave(feed);\n }\n\n // The API client has a new socket once it's reinitialized,\n // so we need to set up a new socket manager\n this.socketManager = undefined;\n this.initSocketManager();\n\n for (const feed of this.feedInstances) {\n feed.reinitialize(this.socketManager);\n }\n }\n\n private initSocketManager() {\n const socket = this.instance.client().socket;\n if (socket && !this.socketManager) {\n this.socketManager = new FeedSocketManager(socket);\n }\n }\n}\n\nexport { Feed };\nexport default FeedClient;\n"],"names":["FeedClient","instance","__publicField","feedChannelId","options","feedInstance","Feed","feed","f","_a","socket","FeedSocketManager"],"mappings":";;;;;AAMA,MAAMA,EAAW;AAAA,EAKf,YAAYC,GAAiB;AAJrB,IAAAC,EAAA;AACA,IAAAA,EAAA,uBAAwB,CAAC;AACzB,IAAAA,EAAA;AAGN,SAAK,WAAWD;AAAA,EAAA;AAAA,EAGlB,WAAWE,GAAuBC,IAA6B,IAAI;AACjE,SAAK,kBAAkB;AAEvB,UAAMC,IAAe,IAAIC;AAAA,MACvB,KAAK;AAAA,MACLH;AAAA,MACAC;AAAA,MACA,KAAK;AAAA,IACP;AACK,gBAAA,cAAc,KAAKC,CAAY,GAC7BA;AAAA,EAAA;AAAA,EAGT,eAAeE,GAAY;AACzB,SAAK,gBAAgB,KAAK,cAAc,OAAO,CAACC,MAAMA,MAAMD,CAAI;AAAA,EAAA;AAAA,EAGlE,oBAAoB;AACP,eAAAA,KAAQ,KAAK;AACtB,MAAAA,EAAK,SAAS;AAAA,EAChB;AAAA,EAGF,wBAAwB;;AACX,eAAAA,KAAQ,KAAK;AACjB,OAAAE,IAAA,KAAA,kBAAA,QAAAA,EAAe,MAAMF;AAK5B,SAAK,gBAAgB,QACrB,KAAK,kBAAkB;AAEZ,eAAAA,KAAQ,KAAK;AACjB,MAAAA,EAAA,aAAa,KAAK,aAAa;AAAA,EACtC;AAAA,EAGM,oBAAoB;AAC1B,UAAMG,IAAS,KAAK,SAAS,OAAS,EAAA;AAClC,IAAAA,KAAU,CAAC,KAAK,kBACb,KAAA,gBAAgB,IAAIC,EAAkBD,CAAM;AAAA,EACnD;AAEJ;"}
|