@knocklabs/client 0.21.1 → 0.21.3
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 +20 -0
- 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/guide/client.js +1 -1
- package/dist/cjs/clients/guide/client.js.map +1 -1
- package/dist/cjs/clients/guide/helpers.js +1 -1
- package/dist/cjs/clients/guide/helpers.js.map +1 -1
- package/dist/cjs/clients/guide/types.js +2 -0
- package/dist/cjs/clients/guide/types.js.map +1 -0
- package/dist/cjs/helpers.js +1 -1
- package/dist/cjs/helpers.js.map +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/knock.js +2 -2
- package/dist/cjs/knock.js.map +1 -1
- package/dist/cjs/pageVisibility.js +2 -0
- package/dist/cjs/pageVisibility.js.map +1 -0
- package/dist/esm/api.mjs +27 -12
- package/dist/esm/api.mjs.map +1 -1
- package/dist/esm/clients/feed/feed.mjs +60 -87
- package/dist/esm/clients/feed/feed.mjs.map +1 -1
- package/dist/esm/clients/guide/client.mjs +346 -268
- package/dist/esm/clients/guide/client.mjs.map +1 -1
- package/dist/esm/clients/guide/helpers.mjs +50 -57
- package/dist/esm/clients/guide/helpers.mjs.map +1 -1
- package/dist/esm/clients/guide/types.mjs +13 -0
- package/dist/esm/clients/guide/types.mjs.map +1 -0
- package/dist/esm/helpers.mjs +19 -4
- package/dist/esm/helpers.mjs.map +1 -1
- package/dist/esm/index.mjs +14 -12
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/knock.mjs +31 -29
- package/dist/esm/knock.mjs.map +1 -1
- package/dist/esm/pageVisibility.mjs +31 -0
- package/dist/esm/pageVisibility.mjs.map +1 -0
- package/dist/types/api.d.ts +4 -0
- package/dist/types/api.d.ts.map +1 -1
- package/dist/types/clients/feed/feed.d.ts +1 -11
- package/dist/types/clients/feed/feed.d.ts.map +1 -1
- package/dist/types/clients/feed/interfaces.d.ts +0 -4
- package/dist/types/clients/feed/interfaces.d.ts.map +1 -1
- package/dist/types/clients/feed/utils.d.ts +0 -2
- package/dist/types/clients/feed/utils.d.ts.map +1 -1
- package/dist/types/clients/guide/client.d.ts +4 -1
- package/dist/types/clients/guide/client.d.ts.map +1 -1
- package/dist/types/clients/guide/helpers.d.ts +1 -7
- package/dist/types/clients/guide/helpers.d.ts.map +1 -1
- package/dist/types/clients/guide/index.d.ts +2 -1
- package/dist/types/clients/guide/index.d.ts.map +1 -1
- package/dist/types/clients/guide/types.d.ts +24 -0
- package/dist/types/clients/guide/types.d.ts.map +1 -1
- package/dist/types/helpers.d.ts +19 -0
- package/dist/types/helpers.d.ts.map +1 -1
- package/dist/types/interfaces.d.ts +2 -0
- package/dist/types/interfaces.d.ts.map +1 -1
- package/dist/types/knock.d.ts +1 -0
- package/dist/types/knock.d.ts.map +1 -1
- package/dist/types/pageVisibility.d.ts +22 -0
- package/dist/types/pageVisibility.d.ts.map +1 -0
- package/package.json +1 -1
- package/src/api.ts +30 -0
- package/src/clients/feed/feed.ts +0 -73
- package/src/clients/feed/interfaces.ts +0 -7
- package/src/clients/guide/client.ts +182 -35
- package/src/clients/guide/helpers.ts +4 -12
- package/src/clients/guide/index.ts +3 -0
- package/src/clients/guide/types.ts +37 -0
- package/src/helpers.ts +39 -0
- package/src/interfaces.ts +2 -0
- package/src/knock.ts +4 -3
- package/src/pageVisibility.ts +70 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.21.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 1ed4f75: [Guides] Add additional debug settings to guide client, and improvements to the guide toolbar V2
|
|
8
|
+
|
|
9
|
+
- Add `focusedGuideKeys` debug setting to pin a target guide during preview
|
|
10
|
+
- Add `ignoreDisplayInterval` debug setting to ignore throttling during preview
|
|
11
|
+
- Add `skipEngagementTracking` debug setting to skip sending engagement updates to the API during preview
|
|
12
|
+
- Add control UIs to the guide toolbar V2 for the newly added debug settings
|
|
13
|
+
- Add a drag handle to the guide toolbar for drag and drop
|
|
14
|
+
|
|
15
|
+
## 0.21.2
|
|
16
|
+
|
|
17
|
+
### Patch Changes
|
|
18
|
+
|
|
19
|
+
- cb7148b: Add exponential backoff with jitter to Phoenix socket reconnection to prevent thundering herd on outages
|
|
20
|
+
- 04a8f16: Disconnects socket after an initial delay when page visibility is hidden and removes the `auto_manage_socket_connection` and `auto_manage_socket_connection_delay` flags from `FeedClientOptions`.
|
|
21
|
+
- b7b3708: [guides] add guide toolbar v2 poc
|
|
22
|
+
|
|
3
23
|
## 0.21.1
|
|
4
24
|
|
|
5
25
|
### Patch Changes
|
package/dist/cjs/api.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var o=Object.defineProperty;var u=(s,e,t)=>e in s?o(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var i=(s,e,t)=>u(s,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const l=require("axios"),c=require("axios-retry"),h=require("phoenix"),a=require("./helpers.js"),d=require("./pageVisibility.js"),n=s=>s&&typeof s=="object"&&"default"in s?s:{default:s},y=n(l),r=n(c);class f{constructor(e){i(this,"host");i(this,"apiKey");i(this,"userToken");i(this,"branch");i(this,"axiosClient");i(this,"socket");i(this,"pageVisibility");this.host=e.host,this.apiKey=e.apiKey,this.userToken=e.userToken||null,this.branch=e.branch||null,this.axiosClient=y.default.create({baseURL:this.host,headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-Knock-User-Token":this.userToken,"X-Knock-Client":this.getKnockClientHeader(),"X-Knock-Branch":this.branch}}),typeof window<"u"&&(this.socket=new h.Socket(`${this.host.replace("http","ws")}/ws/v1`,{params:{user_token:this.userToken,api_key:this.apiKey,branch_slug:this.branch},reconnectAfterMs:t=>a.exponentialBackoffFullJitter(t,{baseDelayMs:1e3,maxDelayMs:3e4}),rejoinAfterMs:t=>a.exponentialBackoffFullJitter(t,{baseDelayMs:1e3,maxDelayMs:6e4})}),e.disconnectOnPageHidden!==!1&&(this.pageVisibility=new d.PageVisibilityManager(this.socket))),r.default(this.axiosClient,{retries:3,retryCondition:this.canRetryRequest,retryDelay:r.default.exponentialDelay})}async makeRequest(e){try{const t=await this.axiosClient(e);return{statusCode:t.status<300?"ok":"error",body:t.data,error:void 0,status:t.status}}catch(t){return console.error(t),{statusCode:"error",status:500,body:void 0,error:t}}}teardown(){var e,t;(e=this.pageVisibility)==null||e.teardown(),(t=this.socket)!=null&&t.isConnected()&&this.socket.disconnect()}canRetryRequest(e){return r.default.isNetworkError(e)?!0:e.response?e.response.status>=500&&e.response.status<=599||e.response.status===429:!1}getKnockClientHeader(){return"Knock/ClientJS 0.21.3"}}exports.default=f;
|
|
2
2
|
//# sourceMappingURL=api.js.map
|
package/dist/cjs/api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.js","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 branch?: string;\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 branch: 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 this.branch = options.branch || 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 \"X-Knock-Client\": this.getKnockClientHeader(),\n \"X-Knock-Branch\": this.branch,\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 branch_slug: this.branch,\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 private getKnockClientHeader() {\n // Note: we're following format used in our Stainless SDKs:\n // https://github.com/knocklabs/knock-node/blob/main/src/client.ts#L335\n // If we add the env var to turbo.json, it caches it so the version\n // never actually updates.\n // eslint-disable-next-line turbo/no-undeclared-env-vars\n return `Knock/ClientJS ${process.env.CLIENT_PACKAGE_VERSION}`;\n }\n}\n\nexport default ApiClient;\n"],"names":["ApiClient","options","__publicField","axios","Socket","axiosRetry","req","result","e","error"],"mappings":"
|
|
1
|
+
{"version":3,"file":"api.js","sources":["../../src/api.ts"],"sourcesContent":["import axios, { AxiosError, AxiosInstance, AxiosRequestConfig } from \"axios\";\nimport axiosRetry from \"axios-retry\";\nimport { Socket } from \"phoenix\";\n\nimport { exponentialBackoffFullJitter } from \"./helpers\";\nimport { PageVisibilityManager } from \"./pageVisibility\";\n\ntype ApiClientOptions = {\n host: string;\n apiKey: string;\n userToken: string | undefined;\n branch?: string;\n /** Automatically disconnect the socket when the page is hidden and reconnect when visible. Defaults to `true`. */\n disconnectOnPageHidden?: boolean;\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 branch: string | null;\n private axiosClient: AxiosInstance;\n\n public socket: Socket | undefined;\n private pageVisibility: PageVisibilityManager | undefined;\n\n constructor(options: ApiClientOptions) {\n this.host = options.host;\n this.apiKey = options.apiKey;\n this.userToken = options.userToken || null;\n this.branch = options.branch || 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 \"X-Knock-Client\": this.getKnockClientHeader(),\n \"X-Knock-Branch\": this.branch,\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 branch_slug: this.branch,\n },\n reconnectAfterMs: (tries: number) => {\n return exponentialBackoffFullJitter(tries, {\n baseDelayMs: 1000,\n maxDelayMs: 30_000,\n });\n },\n rejoinAfterMs: (tries: number) => {\n return exponentialBackoffFullJitter(tries, {\n baseDelayMs: 1000,\n maxDelayMs: 60_000,\n });\n },\n });\n\n if (options.disconnectOnPageHidden !== false) {\n this.pageVisibility = new PageVisibilityManager(this.socket);\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 teardown() {\n this.pageVisibility?.teardown();\n\n if (this.socket?.isConnected()) {\n this.socket.disconnect();\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 private getKnockClientHeader() {\n // Note: we're following format used in our Stainless SDKs:\n // https://github.com/knocklabs/knock-node/blob/main/src/client.ts#L335\n // If we add the env var to turbo.json, it caches it so the version\n // never actually updates.\n // eslint-disable-next-line turbo/no-undeclared-env-vars\n return `Knock/ClientJS ${process.env.CLIENT_PACKAGE_VERSION}`;\n }\n}\n\nexport default ApiClient;\n"],"names":["ApiClient","options","__publicField","axios","Socket","tries","exponentialBackoffFullJitter","PageVisibilityManager","axiosRetry","req","result","e","_a","_b","error"],"mappings":"wdAyBA,MAAMA,CAAU,CAUd,YAAYC,EAA2B,CAT/BC,EAAA,aACAA,EAAA,eACAA,EAAA,kBACAA,EAAA,eACAA,EAAA,oBAEDA,EAAA,eACCA,EAAA,uBAGN,KAAK,KAAOD,EAAQ,KACpB,KAAK,OAASA,EAAQ,OACjB,KAAA,UAAYA,EAAQ,WAAa,KAC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EAC1B,GAGJA,EAAM,SAMPA,EAAM,SAAS,QAAU,KAAOA,EAAM,SAAS,QAAU,KAKzDA,EAAM,SAAS,SAAW,IATrB,EAaF,CAGD,sBAAuB,CAMtB,MAAA,uBAAoD,CAE/D"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var p=Object.defineProperty;var g=(u,e,t)=>e in u?p(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var c=(u,e,t)=>g(u,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("eventemitter2"),_=require("nanoid"),v=require("../../helpers.js"),m=require("../../networkStatus.js"),S=require("./socket-manager.js"),y=require("./store.js"),f=require("./utils.js"),b=u=>u&&typeof u=="object"&&"default"in u?u:{default:u},I=b(k),w={archived:"exclude",mode:"compact"},C=2e3,U="client_";class A{constructor(e,t,s,n){c(this,"defaultOptions");c(this,"referenceId");c(this,"unsubscribeFromSocketEvents");c(this,"socketManager");c(this,"userFeedId");c(this,"broadcaster");c(this,"broadcastChannel");c(this,"disconnectTimer",null);c(this,"hasSubscribedToRealTimeUpdates",!1);c(this,"visibilityChangeHandler",()=>{});c(this,"visibilityChangeListenerConnected",!1);c(this,"store");this.knock=e,this.feedId=t,(!t||!v.isValidUuid(t))&&this.knock.log("[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.",!0),this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.referenceId=U+_.nanoid(),this.socketManager=n,this.store=y.default(),this.broadcaster=new I.default({wildcard:!0,delimiter:"."}),this.defaultOptions={...w,...f.mergeDateRangeParams(s)},this.knock.log(`[Feed] Initialized a feed on channel ${t}`),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}reinitialize(e){this.socketManager=e,this.userFeedId=this.buildUserFeedId(),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}teardown(){var e;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()}dispose(){this.knock.log("[Feed] Disposing of feed instance"),this.teardown(),this.broadcaster.removeAllListeners(),this.knock.feeds.removeInstance(this)}listenForUpdates(){var e;if(this.knock.log("[Feed] Connecting to real-time service"),this.hasSubscribedToRealTimeUpdates=!0,!this.knock.isAuthenticated()){this.knock.log("[Feed] User is not authenticated, skipping listening for updates");return}this.unsubscribeFromSocketEvents=(e=this.socketManager)==null?void 0:e.join(this)}on(e,t){this.broadcaster.on(e,t)}off(e,t){this.broadcaster.off(e,t)}getState(){return this.store.getState()}async markAsSeen(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"seen",{seen_at:t},"unseen_count"),this.makeStatusUpdate(e,"seen")}async markAllAsSeen(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unseen")s.resetStore({...e,total_count:0,unseen_count:0});else{s.setMetadata({...e,unseen_count:0});const a={seen_at:new Date().toISOString()},i=t.map(d=>d.id);s.setItemAttrs(i,a)}const o=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",t),o}async markAsUnseen(e){return this.optimisticallyPerformStatusUpdate(e,"unseen",{seen_at:null},"unseen_count"),this.makeStatusUpdate(e,"unseen")}async markAsRead(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"read",{read_at:t},"unread_count"),this.makeStatusUpdate(e,"read")}async markAllAsRead(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unread")s.resetStore({...e,total_count:0,unread_count:0});else{s.setMetadata({...e,unread_count:0});const a={read_at:new Date().toISOString()},i=t.map(d=>d.id);s.setItemAttrs(i,a)}const o=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",t),o}async markAsUnread(e){return this.optimisticallyPerformStatusUpdate(e,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(e,"unread")}async markAsInteracted(e,t){const s=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"interacted",{read_at:s,interacted_at:s},"unread_count"),this.makeStatusUpdate(e,"interacted",t)}async markAsArchived(e){const t=this.store.getState(),s=this.defaultOptions.archived==="exclude",n=Array.isArray(e)?e:[e],o=n.map(a=>a.id);if(s){const a=n.filter(r=>!r.seen_at).length,i=n.filter(r=>!r.read_at).length,d={...t.metadata,total_count:Math.max(0,t.metadata.total_count-n.length),unseen_count:Math.max(0,t.metadata.unseen_count-a),unread_count:Math.max(0,t.metadata.unread_count-i)},l=t.items.filter(r=>!o.includes(r.id));t.setResult({entries:l,meta:d,page_info:t.pageInfo})}else t.setItemAttrs(o,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(e,"archived")}async markAllAsArchived(){const{items:e,...t}=this.store.getState();if(this.defaultOptions.archived==="exclude")t.resetStore();else{const o=e.map(a=>a.id);t.setItemAttrs(o,{archived_at:new Date().toISOString()})}const n=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",e),n}async markAllReadAsArchived(){const{items:e,...t}=this.store.getState(),n=e.filter(i=>i.read_at===null).map(i=>i.id);if(t.setItemAttrs(n,{archived_at:new Date().toISOString()}),this.defaultOptions.archived==="exclude"){const i=e.filter(l=>!n.includes(l.id)),d={...t.metadata,total_count:i.length,unread_count:0};t.setResult({entries:i,meta:d,page_info:t.pageInfo})}return await this.makeBulkStatusUpdate("archive")}async markAsUnarchived(e){const t=this.store.getState(),s=Array.isArray(e)?e:[e],n=s.map(a=>a.id);if(this.defaultOptions.archived==="only"){const a=s.filter(r=>!r.seen_at).length,i=s.filter(r=>!r.read_at).length,d={...t.metadata,total_count:Math.max(0,t.metadata.total_count-s.length),unseen_count:Math.max(0,t.metadata.unseen_count-a),unread_count:Math.max(0,t.metadata.unread_count-i)},l=t.items.filter(r=>!n.includes(r.id));t.setResult({entries:l,meta:d,page_info:t.pageInfo})}else this.optimisticallyPerformStatusUpdate(e,"unarchived",{archived_at:null});return this.makeStatusUpdate(e,"unarchived")}async fetch(e={}){const{networkStatus:t,...s}=this.store.getState();if(!this.knock.isAuthenticated()){this.knock.log("[Feed] User is not authenticated, skipping fetch");return}if(m.isRequestInFlight(t)){this.knock.log("[Feed] Request is in flight, skipping fetch");return}s.setNetworkStatus(e.__loadingType??m.NetworkStatus.loading);const n=f.getFormattedTriggerData({...this.defaultOptions,...e}),o={...this.defaultOptions,...f.mergeDateRangeParams(e),trigger_data:n,__loadingType:void 0,__fetchSource:void 0,__experimentalCrossBrowserUpdates:void 0,auto_manage_socket_connection:void 0,auto_manage_socket_connection_delay:void 0},a=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:o});if(a.statusCode==="error"||!a.body)return s.setNetworkStatus(m.NetworkStatus.error),{status:a.statusCode,data:a.error||a.body};const i={entries:a.body.entries,meta:a.body.meta,page_info:a.body.page_info};if(e.before){const r={shouldSetPage:!1,shouldAppend:!0};s.setResult(i,r)}else if(e.after){const r={shouldSetPage:!0,shouldAppend:!0};s.setResult(i,r)}else s.setResult(i);this.broadcast("messages.new",i);const d=e.__fetchSource==="socket"?"items.received.realtime":"items.received.page",l={items:i.entries,metadata:i.meta,event:d};return this.broadcast(l.event,l),{data:i,status:a.statusCode}}async fetchNextPage(e={}){const{pageInfo:t}=this.store.getState();t.after&&this.fetch({...e,after:t.after,__loadingType:m.NetworkStatus.fetchMore})}get socketChannelTopic(){return`feeds:${this.userFeedId}`}broadcast(e,t){this.broadcaster.emit(e,t)}async onNewMessageReceived({data:e}){var a;this.knock.log("[Feed] Received new real-time message");const{items:t,...s}=this.store.getState(),n=t[0],o=(a=e[this.referenceId])==null?void 0:a.metadata;o&&s.setMetadata(o),this.fetch({before:n==null?void 0:n.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,s,n){const o=this.store.getState(),a=Array.isArray(e)?e:[e],i=a.map(d=>d.id);if(n){const{metadata:d}=o,l=a.filter(h=>{switch(t){case"seen":return h.seen_at===null;case"unseen":return h.seen_at!==null;case"read":case"interacted":return h.read_at===null;case"unread":return h.read_at!==null;default:return!0}}),r=t.startsWith("un")?l.length:-l.length;o.setMetadata({...d,[n]:Math.max(0,d[n]+r)})}o.setItemAttrs(i,s)}async makeStatusUpdate(e,t,s){const n=Array.isArray(e)?e:[e],o=n.map(i=>i.id),a=await this.knock.messages.batchUpdateStatuses(o,t,{metadata:s});return this.emitEvent(t,n),a}async makeBulkStatusUpdate(e){const t={user_ids:[this.knock.userId],engagement_status:this.defaultOptions.status!=="all"?this.defaultOptions.status:void 0,archived:this.defaultOptions.archived,has_tenant:this.defaultOptions.has_tenant,tenants:this.defaultOptions.tenant?[this.defaultOptions.tenant]:void 0};return await this.knock.messages.bulkUpdateAllStatusesInChannel({channelId:this.feedId,status:e,options:t})}setupBroadcastChannel(){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=>{switch(e.data.type){case"items:archived":case"items:unarchived":case"items:seen":case"items:unseen":case"items:read":case"items:unread":case"items:all_read":case"items:all_seen":case"items:all_archived":return this.fetch();default:return null}})}broadcastOverChannel(e,t){if(this.broadcastChannel)try{const s=JSON.parse(JSON.stringify(t));this.broadcastChannel.postMessage({type:e,payload:s})}catch(s){console.warn(`Could not broadcast ${e}, got error: ${s}`)}}initializeRealtimeConnection(){var e;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)))}async handleSocketEvent(e){switch(e.event){case S.SocketEventType.NewMessage:this.onNewMessageReceived(e);return;default:{e.event;return}}}setUpVisibilityListeners(){typeof document>"u"||this.visibilityChangeListenerConnected||(this.visibilityChangeHandler=this.handleVisibilityChange.bind(this),this.visibilityChangeListenerConnected=!0,document.addEventListener("visibilitychange",this.visibilityChangeHandler))}tearDownVisibilityListeners(){typeof document>"u"||(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeListenerConnected=!1)}emitEvent(e,t){this.broadcaster.emit(`items.${e}`,{items:t}),this.broadcaster.emit(`items:${e}`,{items:t}),this.broadcastOverChannel(`items:${e}`,{items:t})}handleVisibilityChange(){var s,n;const e=this.defaultOptions.auto_manage_socket_connection_delay??C,t=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var o;(o=t.socket)==null||o.disconnect(),this.disconnectTimer=null},e):document.visibilityState==="visible"&&(this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),(s=t.socket)!=null&&s.isConnected()||(n=t.socket)==null||n.connect())}}exports.default=A;
|
|
1
|
+
"use strict";var p=Object.defineProperty;var g=(c,t,e)=>t in c?p(c,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):c[t]=e;var l=(c,t,e)=>g(c,typeof t!="symbol"?t+"":t,e);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("eventemitter2"),_=require("nanoid"),S=require("../../helpers.js"),m=require("../../networkStatus.js"),v=require("./socket-manager.js"),y=require("./store.js"),f=require("./utils.js"),b=c=>c&&typeof c=="object"&&"default"in c?c:{default:c},I=b(k),w={archived:"exclude",mode:"compact"},U="client_";class A{constructor(t,e,s,n){l(this,"defaultOptions");l(this,"referenceId");l(this,"unsubscribeFromSocketEvents");l(this,"socketManager");l(this,"userFeedId");l(this,"broadcaster");l(this,"broadcastChannel");l(this,"hasSubscribedToRealTimeUpdates",!1);l(this,"store");this.knock=t,this.feedId=e,(!e||!S.isValidUuid(e))&&this.knock.log("[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.",!0),this.feedId=e,this.userFeedId=this.buildUserFeedId(),this.referenceId=U+_.nanoid(),this.socketManager=n,this.store=y.default(),this.broadcaster=new I.default({wildcard:!0,delimiter:"."}),this.defaultOptions={...w,...f.mergeDateRangeParams(s)},this.knock.log(`[Feed] Initialized a feed on channel ${e}`),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}reinitialize(t){this.socketManager=t,this.userFeedId=this.buildUserFeedId(),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}teardown(){var t;this.knock.log("[Feed] Tearing down feed instance"),(t=this.socketManager)==null||t.leave(this),this.broadcastChannel&&this.broadcastChannel.close()}dispose(){this.knock.log("[Feed] Disposing of feed instance"),this.teardown(),this.broadcaster.removeAllListeners(),this.knock.feeds.removeInstance(this)}listenForUpdates(){var t;if(this.knock.log("[Feed] Connecting to real-time service"),this.hasSubscribedToRealTimeUpdates=!0,!this.knock.isAuthenticated()){this.knock.log("[Feed] User is not authenticated, skipping listening for updates");return}this.unsubscribeFromSocketEvents=(t=this.socketManager)==null?void 0:t.join(this)}on(t,e){this.broadcaster.on(t,e)}off(t,e){this.broadcaster.off(t,e)}getState(){return this.store.getState()}async markAsSeen(t){const e=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(t,"seen",{seen_at:e},"unseen_count"),this.makeStatusUpdate(t,"seen")}async markAllAsSeen(){const{metadata:t,items:e,...s}=this.store.getState();if(this.defaultOptions.status==="unseen")s.resetStore({...t,total_count:0,unseen_count:0});else{s.setMetadata({...t,unseen_count:0});const a={seen_at:new Date().toISOString()},i=e.map(d=>d.id);s.setItemAttrs(i,a)}const r=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",e),r}async markAsUnseen(t){return this.optimisticallyPerformStatusUpdate(t,"unseen",{seen_at:null},"unseen_count"),this.makeStatusUpdate(t,"unseen")}async markAsRead(t){const e=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(t,"read",{read_at:e},"unread_count"),this.makeStatusUpdate(t,"read")}async markAllAsRead(){const{metadata:t,items:e,...s}=this.store.getState();if(this.defaultOptions.status==="unread")s.resetStore({...t,total_count:0,unread_count:0});else{s.setMetadata({...t,unread_count:0});const a={read_at:new Date().toISOString()},i=e.map(d=>d.id);s.setItemAttrs(i,a)}const r=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",e),r}async markAsUnread(t){return this.optimisticallyPerformStatusUpdate(t,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(t,"unread")}async markAsInteracted(t,e){const s=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(t,"interacted",{read_at:s,interacted_at:s},"unread_count"),this.makeStatusUpdate(t,"interacted",e)}async markAsArchived(t){const e=this.store.getState(),s=this.defaultOptions.archived==="exclude",n=Array.isArray(t)?t:[t],r=n.map(a=>a.id);if(s){const a=n.filter(o=>!o.seen_at).length,i=n.filter(o=>!o.read_at).length,d={...e.metadata,total_count:Math.max(0,e.metadata.total_count-n.length),unseen_count:Math.max(0,e.metadata.unseen_count-a),unread_count:Math.max(0,e.metadata.unread_count-i)},u=e.items.filter(o=>!r.includes(o.id));e.setResult({entries:u,meta:d,page_info:e.pageInfo})}else e.setItemAttrs(r,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(t,"archived")}async markAllAsArchived(){const{items:t,...e}=this.store.getState();if(this.defaultOptions.archived==="exclude")e.resetStore();else{const r=t.map(a=>a.id);e.setItemAttrs(r,{archived_at:new Date().toISOString()})}const n=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",t),n}async markAllReadAsArchived(){const{items:t,...e}=this.store.getState(),n=t.filter(i=>i.read_at===null).map(i=>i.id);if(e.setItemAttrs(n,{archived_at:new Date().toISOString()}),this.defaultOptions.archived==="exclude"){const i=t.filter(u=>!n.includes(u.id)),d={...e.metadata,total_count:i.length,unread_count:0};e.setResult({entries:i,meta:d,page_info:e.pageInfo})}return await this.makeBulkStatusUpdate("archive")}async markAsUnarchived(t){const e=this.store.getState(),s=Array.isArray(t)?t:[t],n=s.map(a=>a.id);if(this.defaultOptions.archived==="only"){const a=s.filter(o=>!o.seen_at).length,i=s.filter(o=>!o.read_at).length,d={...e.metadata,total_count:Math.max(0,e.metadata.total_count-s.length),unseen_count:Math.max(0,e.metadata.unseen_count-a),unread_count:Math.max(0,e.metadata.unread_count-i)},u=e.items.filter(o=>!n.includes(o.id));e.setResult({entries:u,meta:d,page_info:e.pageInfo})}else this.optimisticallyPerformStatusUpdate(t,"unarchived",{archived_at:null});return this.makeStatusUpdate(t,"unarchived")}async fetch(t={}){const{networkStatus:e,...s}=this.store.getState();if(!this.knock.isAuthenticated()){this.knock.log("[Feed] User is not authenticated, skipping fetch");return}if(m.isRequestInFlight(e)){this.knock.log("[Feed] Request is in flight, skipping fetch");return}s.setNetworkStatus(t.__loadingType??m.NetworkStatus.loading);const n=f.getFormattedTriggerData({...this.defaultOptions,...t}),r={...this.defaultOptions,...f.mergeDateRangeParams(t),trigger_data:n,__loadingType:void 0,__fetchSource:void 0,__experimentalCrossBrowserUpdates:void 0},a=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:r});if(a.statusCode==="error"||!a.body)return s.setNetworkStatus(m.NetworkStatus.error),{status:a.statusCode,data:a.error||a.body};const i={entries:a.body.entries,meta:a.body.meta,page_info:a.body.page_info};if(t.before){const o={shouldSetPage:!1,shouldAppend:!0};s.setResult(i,o)}else if(t.after){const o={shouldSetPage:!0,shouldAppend:!0};s.setResult(i,o)}else s.setResult(i);this.broadcast("messages.new",i);const d=t.__fetchSource==="socket"?"items.received.realtime":"items.received.page",u={items:i.entries,metadata:i.meta,event:d};return this.broadcast(u.event,u),{data:i,status:a.statusCode}}async fetchNextPage(t={}){const{pageInfo:e}=this.store.getState();e.after&&this.fetch({...t,after:e.after,__loadingType:m.NetworkStatus.fetchMore})}get socketChannelTopic(){return`feeds:${this.userFeedId}`}broadcast(t,e){this.broadcaster.emit(t,e)}async onNewMessageReceived({data:t}){var a;this.knock.log("[Feed] Received new real-time message");const{items:e,...s}=this.store.getState(),n=e[0],r=(a=t[this.referenceId])==null?void 0:a.metadata;r&&s.setMetadata(r),this.fetch({before:n==null?void 0:n.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(t,e,s,n){const r=this.store.getState(),a=Array.isArray(t)?t:[t],i=a.map(d=>d.id);if(n){const{metadata:d}=r,u=a.filter(h=>{switch(e){case"seen":return h.seen_at===null;case"unseen":return h.seen_at!==null;case"read":case"interacted":return h.read_at===null;case"unread":return h.read_at!==null;default:return!0}}),o=e.startsWith("un")?u.length:-u.length;r.setMetadata({...d,[n]:Math.max(0,d[n]+o)})}r.setItemAttrs(i,s)}async makeStatusUpdate(t,e,s){const n=Array.isArray(t)?t:[t],r=n.map(i=>i.id),a=await this.knock.messages.batchUpdateStatuses(r,e,{metadata:s});return this.emitEvent(e,n),a}async makeBulkStatusUpdate(t){const e={user_ids:[this.knock.userId],engagement_status:this.defaultOptions.status!=="all"?this.defaultOptions.status:void 0,archived:this.defaultOptions.archived,has_tenant:this.defaultOptions.has_tenant,tenants:this.defaultOptions.tenant?[this.defaultOptions.tenant]:void 0};return await this.knock.messages.bulkUpdateAllStatusesInChannel({channelId:this.feedId,status:t,options:e})}setupBroadcastChannel(){this.broadcastChannel=typeof self<"u"&&"BroadcastChannel"in self?new BroadcastChannel(`knock:feed:${this.userFeedId}`):null,this.broadcastChannel&&this.defaultOptions.__experimentalCrossBrowserUpdates===!0&&(this.broadcastChannel.onmessage=t=>{switch(t.data.type){case"items:archived":case"items:unarchived":case"items:seen":case"items:unseen":case"items:read":case"items:unread":case"items:all_read":case"items:all_seen":case"items:all_archived":return this.fetch();default:return null}})}broadcastOverChannel(t,e){if(this.broadcastChannel)try{const s=JSON.parse(JSON.stringify(e));this.broadcastChannel.postMessage({type:t,payload:s})}catch(s){console.warn(`Could not broadcast ${t}, got error: ${s}`)}}initializeRealtimeConnection(){var t;this.socketManager&&this.hasSubscribedToRealTimeUpdates&&this.knock.isAuthenticated()&&(this.unsubscribeFromSocketEvents=(t=this.socketManager)==null?void 0:t.join(this))}async handleSocketEvent(t){switch(t.event){case v.SocketEventType.NewMessage:this.onNewMessageReceived(t);return;default:{t.event;return}}}emitEvent(t,e){this.broadcaster.emit(`items.${t}`,{items:e}),this.broadcaster.emit(`items:${t}`,{items:e}),this.broadcastOverChannel(`items:${t}`,{items:e})}}exports.default=A;
|
|
2
2
|
//# sourceMappingURL=feed.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"feed.js","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\" | \"mode\"> = {\n archived: \"exclude\",\n mode: \"compact\",\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 const state = this.store.getState();\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"only\";\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 unarchiving 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 unarchived 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 this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\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"],"mappings":"uhBAsCMA,EAAmE,CACvE,SAAU,UACV,KAAM,SACR,EAEMC,EAA2B,IAE3BC,EAAuB,UAE7B,MAAMC,CAAK,CAgBT,YACWC,EACAC,EACTC,EACAC,EACA,CApBcC,EAAA,uBACAA,EAAA,oBACTA,EAAA,oCACCA,EAAA,sBACAA,EAAA,mBACAA,EAAA,oBACAA,EAAA,yBACAA,EAAA,uBAAwD,MACxDA,EAAA,sCAA0C,IAC1CA,EAAA,+BAAsC,IAAM,CAAC,GAC7CA,EAAA,yCAA6C,IAG9CA,EAAA,cAGI,KAAA,MAAAJ,EACA,KAAA,OAAAC,GAIL,CAACA,GAAU,CAACI,EAAA,YAAYJ,CAAM,IAChC,KAAK,MAAM,IACT,8NACA,EACF,EAGF,KAAK,OAASA,EACT,KAAA,WAAa,KAAK,gBAAgB,EAClC,KAAA,YAAcH,EAAuBQ,SAAO,EACjD,KAAK,cAAgBH,EACrB,KAAK,MAAQI,UAAY,EACpB,KAAA,YAAc,IAAIC,UAAa,CAAE,SAAU,GAAM,UAAW,IAAK,EACtE,KAAK,eAAiB,CACpB,GAAGZ,EACH,GAAGa,uBAAqBP,CAAO,CACjC,EACA,KAAK,MAAM,IAAI,wCAAwCD,CAAM,EAAE,EAG/D,KAAK,6BAA6B,EAElC,KAAK,sBAAsB,CAAA,CAM7B,aAAaE,EAAmC,CAC9C,KAAK,cAAgBA,EAGhB,KAAA,WAAa,K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AiB,mBAAoB,KAAK,uBAAuB,EAAA,CAGpE,6BAA8B,CAChC,OAAO,SAAa,MAEf,SAAA,oBACP,mBACA,KAAK,uBACP,EACA,KAAK,kCAAoC,GAAA,CAGnC,UACNN,EAQA1B,EACA,CAEA,KAAK,YAAY,KAAK,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,EAChD,KAAK,YAAY,KAAK,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,EAEhD,KAAK,qBAAqB,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,CAAA,CAG9C,wBAAyB,SACzB,MAAAoC,EACJ,KAAK,eAAe,qCACpBvD,EAEIwD,EAAS,KAAK,MAAM,OAAO,EAE7B,SAAS,kBAAoB,SAE1B,KAAA,gBAAkB,WAAW,IAAM,QACtC3C,EAAA2C,EAAO,SAAP,MAAA3C,EAAe,aACf,KAAK,gBAAkB,MACtB0C,CAAe,EACT,SAAS,kBAAoB,YAGlC,KAAK,kBACP,aAAa,KAAK,eAAe,EACjC,KAAK,gBAAkB,OAIpB1C,EAAA2C,EAAO,SAAP,MAAA3C,EAAe,gBAClB4C,EAAAD,EAAO,SAAP,MAAAC,EAAe,UAEnB,CAEJ"}
|
|
1
|
+
{"version":3,"file":"feed.js","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\" | \"mode\"> = {\n archived: \"exclude\",\n mode: \"compact\",\n};\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 hasSubscribedToRealTimeUpdates: 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 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 const state = this.store.getState();\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"only\";\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 unarchiving 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 unarchived 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 this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\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 };\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 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 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\nexport default Feed;\n"],"names":["feedClientDefaults","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","e","payload","stringifiedPayload","SocketEventType"],"mappings":"uhBAsCMA,EAAmE,CACvE,SAAU,UACV,KAAM,SACR,EAEMC,EAAuB,UAE7B,MAAMC,CAAK,CAaT,YACWC,EACAC,EACTC,EACAC,EACA,CAjBcC,EAAA,uBACAA,EAAA,oBACTA,EAAA,oCACCA,EAAA,sBACAA,EAAA,mBACAA,EAAA,oBACAA,EAAA,yBACAA,EAAA,sCAA0C,IAG3CA,EAAA,cAGI,KAAA,MAAAJ,EACA,KAAA,OAAAC,GAIL,CAACA,GAAU,CAACI,EAAA,YAAYJ,CAAM,IAChC,KAAK,MAAM,IACT,8NACA,EACF,EAGF,KAAK,OAASA,EACT,KAAA,WAAa,KAAK,gBAAgB,EAClC,KAAA,YAAcH,EAAuBQ,SAAO,EACjD,KAAK,cAAgBH,EACrB,KAAK,MAAQI,UAAY,EACpB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CAGM,UACNP,EAQA1B,EACA,CAEA,KAAK,YAAY,KAAK,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,EAChD,KAAK,YAAY,KAAK,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,EAEhD,KAAK,qBAAqB,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,CAAA,CAExD"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var b=Object.defineProperty;var _=(u,e,t)=>e in u?b(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var d=(u,e,t)=>_(u,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("@tanstack/store"),C=require("urlpattern-polyfill"),c=require("./helpers.js"),E=50,w=30*1e3,R=3,g={GUIDE_KEY:"knock_guide_key",PREVIEW_SESSION_ID:"knock_preview_session_id"},G="knock_guide_debug",k=()=>{if(typeof window<"u")return window},m=u=>`/v1/users/${u}/guides`,S=()=>{const u=k();if(!u||!u.location)return{forcedGuideKey:null,previewSessionId:null};const e=new URLSearchParams(u.location.search),t=e.get(g.GUIDE_KEY),s=e.get(g.PREVIEW_SESSION_ID);if(t||s){if(u.localStorage)try{const r={forcedGuideKey:t,previewSessionId:s};u.localStorage.setItem(G,JSON.stringify(r))}catch{}return{forcedGuideKey:t,previewSessionId:s}}let i=null,n=null;if(u.localStorage)try{const r=u.localStorage.getItem(G);if(r){const o=P(r);i=o.forcedGuideKey,n=o.previewSessionId}}catch{}return{forcedGuideKey:i,previewSessionId:n}},P=u=>{try{const e=JSON.parse(u);return{forcedGuideKey:(e==null?void 0:e.forcedGuideKey)??null,previewSessionId:(e==null?void 0:e.previewSessionId)??null}}catch{return{forcedGuideKey:null,previewSessionId:null}}},y=(u,e={})=>{const t=new c.SelectionResult,s=c.findDefaultGroup(u.guideGroups);if(!s)return t;const i=s.display_sequence,n=u.location;for(const[r,o]of i.entries()){const a=u.previewGuides[o]||u.guides[o];!a||!D(a,e,{location:n,ineligibleGuides:u.ineligibleGuides,debug:u.debug})||t.set(r,a)}return t.metadata={guideGroup:s},t},D=(u,e,{location:t,ineligibleGuides:s={},debug:i={}})=>e.type&&e.type!==u.type||e.key&&e.key!==u.key?!1:i.forcedGuideKey?i.forcedGuideKey===u.key:s[u.key]||!u.active||u.steps.every(r=>!!r.message.archived_at)?!1:v(u,t),v=(u,e)=>{const t=e?c.newUrl(e):void 0,s=u.activation_url_rules||[],i=u.activation_url_patterns||[];if(t&&s.length>0){if(!c.predicateUrlRules(t,s))return!1}else if(t&&i.length>0&&!c.predicateUrlPatterns(t,i))return!1;return!0};class A{constructor(e,t,s={},i={}){d(this,"store");d(this,"socket");d(this,"socketChannel");d(this,"socketChannelTopic");d(this,"socketEventTypes",["guide.added","guide.updated","guide.removed","guide_group.added","guide_group.updated","guide.live_preview_updated"]);d(this,"subscribeRetryCount",0);d(this,"pushStateFn");d(this,"replaceStateFn");d(this,"stage");d(this,"counterIntervalId");d(this,"handleLocationChange",()=>{this.knock.log("[Guide] .handleLocationChange");const e=k();if(!(e!=null&&e.location))return;const t=e.location.href;if(this.store.state.location===t)return;if(this.knock.log(`[Guide] Detected a location change: ${t}`),!this.options.trackDebugParams){this.setLocation(t);return}const s=this.store.state.debug||{},i=S();this.setLocation(t,{debug:i}),this.checkDebugStateChanged(s,i)&&(this.knock.log("[Guide] Debug state changed, refetching guides and resubscribing to the websocket channel"),this.fetch(),this.subscribe())});var f;this.knock=e,this.channelId=t,this.targetParams=s,this.options=i;const{trackLocationFromWindow:n=!0,trackDebugParams:r=!1,throttleCheckInterval:o=w}=i,a=k(),h=n?(f=a==null?void 0:a.location)==null?void 0:f.href:void 0,l=r?S():void 0;this.store=new I.Store({guideGroups:[],guideGroupDisplayLogs:{},guides:{},ineligibleGuides:{},previewGuides:{},queries:{},location:h,counter:0,debug:l});const{socket:p}=this.knock.client();this.socket=p,this.socketChannelTopic=`guides:${t}`,n&&this.listenForLocationChangesFromWindow(),o&&this.startCounterInterval(o),this.knock.log("[Guide] Initialized a guide client")}incrementCounter(){this.knock.log("[Guide] Incrementing the counter"),this.store.setState(e=>({...e,counter:e.counter+1}))}startCounterInterval(e){this.counterIntervalId=setInterval(()=>{this.knock.log("[Guide] Counter interval tick"),!(this.stage&&this.stage.status!=="closed")&&this.incrementCounter()},e)}clearCounterInterval(){this.counterIntervalId&&(clearInterval(this.counterIntervalId),this.counterIntervalId=void 0)}cleanup(){this.unsubscribe(),this.removeLocationChangeEventListeners(),this.clearGroupStage(),this.clearCounterInterval()}async fetch(e){this.knock.log("[Guide] .fetch"),this.knock.failIfNotAuthenticated();const t=this.buildQueryParams(e==null?void 0:e.filters),s=this.formatQueryKey(t),i=this.store.state.queries[s];if(i)return i;this.store.setState(r=>({...r,queries:{...r.queries,[s]:{status:"loading"}}}));let n;try{this.knock.log("[Guide] Fetching all eligible guides");const r=await this.knock.user.getGuides(this.channelId,t);n={status:"ok"};const{entries:o,guide_groups:a,guide_group_display_logs:h,ineligible_guides:l}=r;this.knock.log("[Guide] Loading fetched guides"),this.store.setState(p=>({...p,guideGroups:(a==null?void 0:a.length)>0?a:[c.mockDefaultGroup(o)],guideGroupDisplayLogs:h||{},guides:c.byKey(o.map(f=>this.localCopy(f))),ineligibleGuides:c.byKey(l||[]),queries:{...p.queries,[s]:n}}))}catch(r){n={status:"error",error:r},this.store.setState(o=>({...o,queries:{...o.queries,[s]:n}}))}return n}subscribe(){if(!this.socket)return;this.knock.failIfNotAuthenticated(),this.knock.log("[Guide] Subscribing to real time updates"),this.socket.isConnected()||this.socket.connect(),this.socketChannel&&this.unsubscribe();const e=this.store.state.debug,t={...this.targetParams,user_id:this.knock.userId,force_all_guides:e!=null&&e.forcedGuideKey||e!=null&&e.debugging?!0:void 0,preview_session_id:(e==null?void 0:e.previewSessionId)||void 0},s=this.socket.channel(this.socketChannelTopic,t);for(const i of this.socketEventTypes)s.on(i,n=>this.handleSocketEvent(n));["closed","errored"].includes(s.state)&&(this.subscribeRetryCount=0,s.join().receive("ok",()=>{this.knock.log("[Guide] Successfully joined channel")}).receive("error",i=>{this.knock.log(`[Guide] Failed to join channel: ${JSON.stringify(i)}`),this.handleChannelJoinError()}).receive("timeout",()=>{this.knock.log("[Guide] Channel join timed out"),this.handleChannelJoinError()})),this.socketChannel=s}handleChannelJoinError(){if(this.subscribeRetryCount>=R){this.knock.log(`[Guide] Channel join max retry limit reached: ${this.subscribeRetryCount}`),this.unsubscribe();return}this.subscribeRetryCount++}unsubscribe(){if(this.socketChannel){this.knock.log("[Guide] Unsubscribing from real time updates");for(const e of this.socketEventTypes)this.socketChannel.off(e);this.socketChannel.leave(),this.socketChannel=void 0}}handleSocketEvent(e){const{event:t,data:s}=e;switch(t){case"guide.added":return this.addOrReplaceGuide(e);case"guide.updated":return s.eligible?this.addOrReplaceGuide(e):this.removeGuide(e);case"guide.removed":return this.removeGuide(e);case"guide_group.added":case"guide_group.updated":return this.addOrReplaceGuideGroup(e);case"guide.live_preview_updated":return this.updatePreviewGuide(e);default:return}}setLocation(e,t={}){this.knock.log(`[Guide] .setLocation (loc=${e})`),this.clearGroupStage(),this.knock.log("[Guide] Updating the tracked location"),this.store.setState(s=>{var n;const i=(n=t==null?void 0:t.debug)!=null&&n.previewSessionId?s.previewGuides:{};return{...s,...t,previewGuides:i,location:e}})}exitDebugMode(){this.knock.log("[Guide] Exiting debug mode");const e=k();if(e!=null&&e.localStorage)try{e.localStorage.removeItem(G)}catch{}if(this.store.setState(t=>({...t,debug:{forcedGuideKey:null,previewSessionId:null},previewGuides:{}})),e!=null&&e.location){const t=new URL(e.location.href);(t.searchParams.has(g.GUIDE_KEY)||t.searchParams.has(g.PREVIEW_SESSION_ID))&&(t.searchParams.delete(g.GUIDE_KEY),t.searchParams.delete(g.PREVIEW_SESSION_ID),e.location.href=t.toString())}}setDebug(e){var s;this.knock.log("[Guide] .setDebug()");const t=!((s=this.store.state.debug)!=null&&s.debugging);this.store.setState(i=>({...i,debug:{...e,debugging:!0}})),t&&(this.knock.log("[Guide] Start debugging, refetching guides and resubscribing to the websocket channel"),this.fetch(),this.subscribe())}unsetDebug(){var t;this.knock.log("[Guide] .unsetDebug()");const e=(t=this.store.state.debug)==null?void 0:t.debugging;this.store.setState(s=>({...s,debug:void 0})),e&&(this.knock.log("[Guide] Stop debugging, refetching guides and resubscribing to the websocket channel"),this.fetch(),this.subscribe())}selectGuides(e,t={},s={}){if(this.knock.log(`[Guide] .selectGuides (filters: ${c.formatFilters(t)}; state: ${c.formatState(e)})`),!this.selectGuide(e,t,s))return[];const n=[...y(e,t).values()];if(!s.includeThrottled&&c.checkStateIfThrottled(e)){const r=n.filter(a=>a.bypass_global_group_limit),o=n.length-r.length;return this.knock.log(`[Guide] Throttling ${o} guides from selection, and returning ${r.length} guides`),r}return this.knock.log(`[Guide] Returning ${n.length} guides from selection`),n}selectGuide(e,t={},s={}){if(this.knock.log(`[Guide] .selectGuide (filters: ${c.formatFilters(t)}; state: ${c.formatState(e)})`),Object.keys(e.guides).length===0&&Object.keys(e.previewGuides).length===0){this.knock.log("[Guide] Exiting selection (no guides)");return}const i=y(e,t);if(i.size===0){this.knock.log("[Guide] Selection found zero result");return}const[n,r]=[...i][0];if(this.knock.log(`[Guide] Selection found: \`${r.key}\` (total: ${i.size})`),r.bypass_global_group_limit)return this.knock.log(`[Guide] Returning the unthrottled guide: ${r.key}`),r;if(!s.includeThrottled&&c.checkStateIfThrottled(e)){this.knock.log(`[Guide] Throttling the selected guide: ${r.key}`);return}switch(this.stage||(this.stage=this.openGroupStage()),this.stage.status){case"open":{this.knock.log(`[Guide] Adding to the group stage: ${r.key}`),this.stage.ordered[n]=r.key;return}case"patch":{this.knock.log(`[Guide] Patching the group stage: ${r.key}`),this.stage.ordered[n]=r.key;const o=this.stage.resolved===r.key?r:void 0;return this.knock.log(`[Guide] Returning \`${o==null?void 0:o.key}\` (stage: ${c.formatGroupStage(this.stage)})`),o}case"closed":{const o=this.stage.resolved===r.key?r:void 0;return this.knock.log(`[Guide] Returning \`${o==null?void 0:o.key}\` (stage: ${c.formatGroupStage(this.stage)})`),o}}}openGroupStage(){this.knock.log("[Guide] Opening a new group stage");const{orderResolutionDuration:e=E}=this.options,t=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.stage={status:"open",ordered:[],timeoutId:t},this.stage}closePendingGroupStage(){if(this.knock.log("[Guide] .closePendingGroupStage"),!this.stage||this.stage.status==="closed")return;this.ensureClearTimeout();const e=this.stage.ordered.find(t=>t!==void 0);return this.knock.log(`[Guide] Closing the current group stage: resolved=${e}`),this.stage={...this.stage,status:"closed",resolved:e,timeoutId:null},this.stage}patchClosedGroupStage(){var s;if(this.knock.log("[Guide] .patchClosedGroupStage"),((s=this.stage)==null?void 0:s.status)!=="closed")return;const{orderResolutionDuration:e=0}=this.options,t=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.ensureClearTimeout(),this.knock.log("[Guide] Patching the current group stage"),this.stage={...this.stage,status:"patch",ordered:[],timeoutId:t},this.stage}clearGroupStage(){this.knock.log("[Guide] .clearGroupStage"),this.stage&&(this.knock.log("[Guide] Clearing the current group stage"),this.ensureClearTimeout(),this.stage=void 0)}ensureClearTimeout(){var e;(e=this.stage)!=null&&e.timeoutId&&clearTimeout(this.stage.timeoutId)}_selectGuide(e,t={},s={}){return this.openGroupStage(),this.selectGuide(e,t,s),this.closePendingGroupStage(),this.selectGuide(e,t,s)}_selectGuides(e,t={},s={}){return this.openGroupStage(),this.selectGuides(e,t,s),this.closePendingGroupStage(),this.selectGuides(e,t,s)}async markAsSeen(e,t){if(t.message.seen_at)return;this.knock.log(`[Guide] Marking as seen (Guide key: ${e.key}, Step ref:${t.ref})`);const s=this.setStepMessageAttrs(e.key,t.ref,{seen_at:new Date().toISOString()});if(!s)return;const i={...this.buildEngagementEventBaseParams(e,s),content:s.content,data:this.targetParams.data};return this.knock.user.markGuideStepAs("seen",i),s}async markAsInteracted(e,t,s){this.knock.log(`[Guide] Marking as interacted (Guide key: ${e.key}; Step ref:${t.ref})`);const i=new Date().toISOString(),n=this.setStepMessageAttrs(e.key,t.ref,{read_at:i,interacted_at:i});if(!n)return;const r={...this.buildEngagementEventBaseParams(e,n),metadata:s};return this.knock.user.markGuideStepAs("interacted",r),n}async markAsArchived(e,t){if(t.message.archived_at)return;this.knock.log(`[Guide] Marking as archived (Guide key: ${e.key}, Step ref:${t.ref})`);const s=this.setStepMessageAttrs(e.key,t.ref,{archived_at:new Date().toISOString()});if(!s)return;const i=this.buildEngagementEventBaseParams(e,s);return this.knock.user.markGuideStepAs("archived",{...i,unthrottled:e.bypass_global_group_limit}),s}localCopy(e){const t=this,s={...e,getStep(){var i;return((i=t.store.state.debug)==null?void 0:i.forcedGuideKey)===this.key?this.steps[0]:this.steps.find(n=>!n.message.archived_at)}};return s.getStep=s.getStep.bind(s),s.steps=e.steps.map(({message:i,...n})=>{const r={...n,message:{...i},markAsSeen(){return t.markAsSeen(s,this)},markAsInteracted({metadata:o}={}){return t.markAsInteracted(s,this,o)},markAsArchived(){return t.markAsArchived(s,this)}};return r.markAsSeen=r.markAsSeen.bind(r),r.markAsInteracted=r.markAsInteracted.bind(r),r.markAsArchived=r.markAsArchived.bind(r),r}),s.activation_url_patterns=e.activation_url_patterns.map(i=>({...i,pattern:new C.URLPattern({pathname:i.pathname??void 0,search:i.search??void 0})})),s}buildQueryParams(e={}){const t={...this.targetParams,...e},s=this.store.state.debug;(s!=null&&s.forcedGuideKey||s!=null&&s.debugging)&&(t.force_all_guides=!0);let i=Object.fromEntries(Object.entries(t).filter(([n,r])=>r!=null));return i=i.data?{...i,data:JSON.stringify(i.data)}:i,i}formatQueryKey(e){const s=Object.keys(e).sort().map(n=>`${encodeURIComponent(n)}=${encodeURIComponent(e[n])}`).join("&"),i=m(this.knock.userId);return s?`${i}?${s}`:i}setStepMessageAttrs(e,t,s){let i;return s.archived_at&&this.clearGroupStage(),this.store.setState(n=>{let r=n.guides[e];if(!r)return n;const o=r.steps.map(l=>(l.ref!==t||(l.message={...l.message,...s},i=l),l));r=i?{...r,steps:o}:r;const a={...n.guides,[r.key]:r},h=s.archived_at&&!r.bypass_global_group_limit?{...n.guideGroupDisplayLogs,[c.DEFAULT_GROUP_KEY]:s.archived_at}:n.guideGroupDisplayLogs;return{...n,guides:a,guideGroupDisplayLogs:h}}),i}buildEngagementEventBaseParams(e,t){return{channel_id:e.channel_id,guide_key:e.key,guide_id:e.id,guide_step_ref:t.ref,tenant:this.targetParams.tenant}}addOrReplaceGuide({data:e}){this.patchClosedGroupStage();const t=this.localCopy(e.guide);this.store.setState(s=>{const i={...s.guides,[t.key]:t};return{...s,guides:i}})}removeGuide({data:e}){this.patchClosedGroupStage(),this.store.setState(t=>{const{[e.guide.key]:s,...i}=t.guides;return{...t,guides:i}})}addOrReplaceGuideGroup({data:e}){this.patchClosedGroupStage(),this.store.setState(t=>{const s=[e.guide_group],i=e.guide_group.display_sequence_unthrottled||[],n=e.guide_group.display_sequence_throttled||[];let r=t.guides;return r=i.reduce((o,a)=>{if(!o[a])return o;const h={...o[a],bypass_global_group_limit:!0};return{...o,[a]:h}},r),r=n.reduce((o,a)=>{if(!o[a])return o;const h={...o[a],bypass_global_group_limit:!1};return{...o,[a]:h}},r),{...t,guides:r,guideGroups:s}})}updatePreviewGuide({data:e}){const t=this.localCopy(e.guide);this.store.setState(s=>{const i={...s.previewGuides,[t.key]:t};return{...s,previewGuides:i}})}checkDebugStateChanged(e,t){return!!e.forcedGuideKey!=!!t.forcedGuideKey||e.previewSessionId!==t.previewSessionId}listenForLocationChangesFromWindow(){const e=k();if(e!=null&&e.history&&(e!=null&&e.addEventListener)){e.addEventListener("popstate",this.handleLocationChange),e.addEventListener("hashchange",this.handleLocationChange);const t=e.history.pushState,s=e.history.replaceState;e.history.pushState=new Proxy(t,{apply:(i,n,r)=>{Reflect.apply(i,n,r),setTimeout(()=>{this.handleLocationChange()},0)}}),e.history.replaceState=new Proxy(s,{apply:(i,n,r)=>{Reflect.apply(i,n,r),setTimeout(()=>{this.handleLocationChange()},0)}}),this.pushStateFn=t,this.replaceStateFn=s}else this.knock.log("[Guide] Unable to access the `window.history` object to detect location changes")}removeLocationChangeEventListeners(){const e=k();!(e!=null&&e.history)||!(e!=null&&e.removeEventListener)||(e.removeEventListener("popstate",this.handleLocationChange),e.removeEventListener("hashchange",this.handleLocationChange),this.pushStateFn&&(e.history.pushState=this.pushStateFn,this.pushStateFn=void 0),this.replaceStateFn&&(e.history.replaceState=this.replaceStateFn,this.replaceStateFn=void 0))}}exports.DEBUG_QUERY_PARAMS=g;exports.KnockGuideClient=A;exports.checkActivatable=v;exports.guidesApiRootPath=m;
|
|
1
|
+
"use strict";var I=Object.defineProperty;var E=(u,e,s)=>e in u?I(u,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):u[e]=s;var h=(u,e,s)=>E(u,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("@tanstack/store"),R=require("urlpattern-polyfill"),l=require("./helpers.js"),A=require("./types.js"),w=50,P=30*1e3,D=3,f={GUIDE_KEY:"knock_guide_key",PREVIEW_SESSION_ID:"knock_preview_session_id"},G="knock_guide_debug",y=()=>{if(typeof window<"u")return window},v=u=>`/v1/users/${u}/guides`,m=()=>{const u=y();if(!u||!u.location)return{forcedGuideKey:null,previewSessionId:null};const e=new URLSearchParams(u.location.search),s=e.get(f.GUIDE_KEY),t=e.get(f.PREVIEW_SESSION_ID);if(s||t){if(u.localStorage)try{const r={forcedGuideKey:s,previewSessionId:t};u.localStorage.setItem(G,JSON.stringify(r))}catch{}return{forcedGuideKey:s,previewSessionId:t}}let i=null,n=null;if(u.localStorage)try{const r=u.localStorage.getItem(G);if(r){const a=K(r);i=a.forcedGuideKey,n=a.previewSessionId}}catch{}return{forcedGuideKey:i,previewSessionId:n}},K=u=>{try{const e=JSON.parse(u);return{forcedGuideKey:(e==null?void 0:e.forcedGuideKey)??null,previewSessionId:(e==null?void 0:e.previewSessionId)??null}}catch{return{forcedGuideKey:null,previewSessionId:null}}},b=(u,e,s)=>{const t=new A.SelectionResult,i=l.findDefaultGroup(u.guideGroups);if(!i)return t;const n=i.display_sequence,r=u.location;for(const[a,o]of n.entries()){const c=u.previewGuides[o]||u.guides[o];!c||!L(c,e,{location:r,ineligibleGuides:u.ineligibleGuides,debug:u.debug})||t.set(a,c)}return t.metadata={guideGroup:i,filters:e,...s},t},L=(u,e,{location:s,ineligibleGuides:t={},debug:i={}})=>e.type&&e.type!==u.type||e.key&&e.key!==u.key?!1:i.focusedGuideKeys&&Object.keys(i.focusedGuideKeys).length>0?!!i.focusedGuideKeys[u.key]:i.forcedGuideKey?i.forcedGuideKey===u.key:t[u.key]||!u.active||u.steps.every(r=>!!r.message.archived_at)?!1:_(u,s),_=(u,e)=>{const s=e?l.newUrl(e):void 0,t=u.activation_url_rules||[],i=u.activation_url_patterns||[];if(s&&t.length>0){if(!l.predicateUrlRules(s,t))return!1}else if(s&&i.length>0&&!l.predicateUrlPatterns(s,i))return!1;return!0};class T{constructor(e,s,t={},i={}){h(this,"store");h(this,"socket");h(this,"socketChannel");h(this,"socketChannelTopic");h(this,"socketEventTypes",["guide.added","guide.updated","guide.removed","guide_group.added","guide_group.updated","guide.live_preview_updated"]);h(this,"subscribeRetryCount",0);h(this,"pushStateFn");h(this,"replaceStateFn");h(this,"stage");h(this,"counterIntervalId");h(this,"handleLocationChange",()=>{this.knock.log("[Guide] .handleLocationChange");const e=y();if(!(e!=null&&e.location))return;const s=e.location.href;if(this.store.state.location===s)return;if(this.knock.log(`[Guide] Detected a location change: ${s}`),!this.options.trackDebugParams){this.setLocation(s);return}const t=this.store.state.debug||{},i=m();this.setLocation(s,{debug:i}),this.checkDebugStateChanged(t,i)&&(this.knock.log("[Guide] Debug state changed, refetching guides and resubscribing to the websocket channel"),this.fetch(),this.subscribe())});var k;this.knock=e,this.channelId=s,this.targetParams=t,this.options=i;const{trackLocationFromWindow:n=!0,trackDebugParams:r=!1,throttleCheckInterval:a=P}=i,o=y(),c=n?(k=o==null?void 0:o.location)==null?void 0:k.href:void 0,d=r?m():void 0;this.store=new C.Store({guideGroups:[],guideGroupDisplayLogs:{},guides:{},ineligibleGuides:{},previewGuides:{},queries:{},location:c,counter:0,debug:d});const{socket:g}=this.knock.client();this.socket=g,this.socketChannelTopic=`guides:${s}`,n&&this.listenForLocationChangesFromWindow(),a&&this.startCounterInterval(a),this.knock.log("[Guide] Initialized a guide client")}incrementCounter(){this.knock.log("[Guide] Incrementing the counter"),this.store.setState(e=>({...e,counter:e.counter+1}))}startCounterInterval(e){this.counterIntervalId=setInterval(()=>{this.knock.log("[Guide] Counter interval tick"),!(this.stage&&this.stage.status!=="closed")&&this.incrementCounter()},e)}clearCounterInterval(){this.counterIntervalId&&(clearInterval(this.counterIntervalId),this.counterIntervalId=void 0)}cleanup(){this.unsubscribe(),this.removeLocationChangeEventListeners(),this.clearGroupStage(),this.clearCounterInterval()}async fetch(e){this.knock.log("[Guide] .fetch"),this.knock.failIfNotAuthenticated();const s=this.buildQueryParams(e==null?void 0:e.filters),t=this.formatQueryKey(s),i=this.store.state.queries[t];if(i)return i;this.store.setState(r=>({...r,queries:{...r.queries,[t]:{status:"loading"}}}));let n;try{this.knock.log("[Guide] Fetching all eligible guides");const r=await this.knock.user.getGuides(this.channelId,s);n={status:"ok"};const{entries:a,guide_groups:o,guide_group_display_logs:c,ineligible_guides:d}=r;this.knock.log("[Guide] Loading fetched guides"),this.store.setState(g=>({...g,guideGroups:(o==null?void 0:o.length)>0?o:[l.mockDefaultGroup(a)],guideGroupDisplayLogs:c||{},guides:l.byKey(a.map(k=>this.localCopy(k))),ineligibleGuides:l.byKey(d||[]),queries:{...g.queries,[t]:n}}))}catch(r){n={status:"error",error:r},this.store.setState(a=>({...a,queries:{...a.queries,[t]:n}}))}return n}subscribe(){if(!this.socket)return;this.knock.failIfNotAuthenticated(),this.knock.log("[Guide] Subscribing to real time updates"),this.socket.isConnected()||this.socket.connect(),this.socketChannel&&this.unsubscribe();const e=this.store.state.debug,s={...this.targetParams,user_id:this.knock.userId,force_all_guides:e!=null&&e.forcedGuideKey||e!=null&&e.debugging?!0:void 0,preview_session_id:(e==null?void 0:e.previewSessionId)||void 0},t=this.socket.channel(this.socketChannelTopic,s);for(const i of this.socketEventTypes)t.on(i,n=>this.handleSocketEvent(n));["closed","errored"].includes(t.state)&&(this.subscribeRetryCount=0,t.join().receive("ok",()=>{this.knock.log("[Guide] Successfully joined channel")}).receive("error",i=>{this.knock.log(`[Guide] Failed to join channel: ${JSON.stringify(i)}`),this.handleChannelJoinError()}).receive("timeout",()=>{this.knock.log("[Guide] Channel join timed out"),this.handleChannelJoinError()})),this.socketChannel=t}handleChannelJoinError(){if(this.subscribeRetryCount>=D){this.knock.log(`[Guide] Channel join max retry limit reached: ${this.subscribeRetryCount}`),this.unsubscribe();return}this.subscribeRetryCount++}unsubscribe(){if(this.socketChannel){this.knock.log("[Guide] Unsubscribing from real time updates");for(const e of this.socketEventTypes)this.socketChannel.off(e);this.socketChannel.leave(),this.socketChannel=void 0}}handleSocketEvent(e){const{event:s,data:t}=e;switch(s){case"guide.added":return this.addOrReplaceGuide(e);case"guide.updated":return t.eligible?this.addOrReplaceGuide(e):this.removeGuide(e);case"guide.removed":return this.removeGuide(e);case"guide_group.added":case"guide_group.updated":return this.addOrReplaceGuideGroup(e);case"guide.live_preview_updated":return this.updatePreviewGuide(e);default:return}}setLocation(e,s={}){this.knock.log(`[Guide] .setLocation (loc=${e})`),this.clearGroupStage(),this.knock.log("[Guide] Updating the tracked location"),this.store.setState(t=>{var n;const i=(n=s==null?void 0:s.debug)!=null&&n.previewSessionId?t.previewGuides:{};return{...t,...s,previewGuides:i,location:e}})}exitDebugMode(){this.knock.log("[Guide] Exiting debug mode");const e=y();if(e!=null&&e.localStorage)try{e.localStorage.removeItem(G)}catch{}if(this.store.setState(s=>({...s,debug:{forcedGuideKey:null,previewSessionId:null,focusedGuideKeys:{}},previewGuides:{}})),e!=null&&e.location){const s=new URL(e.location.href);(s.searchParams.has(f.GUIDE_KEY)||s.searchParams.has(f.PREVIEW_SESSION_ID))&&(s.searchParams.delete(f.GUIDE_KEY),s.searchParams.delete(f.PREVIEW_SESSION_ID),e.location.href=s.toString())}}setDebug(e){var t;this.knock.log("[Guide] .setDebug()");const s=!((t=this.store.state.debug)!=null&&t.debugging);this.store.setState(i=>({...i,debug:{skipEngagementTracking:!0,ignoreDisplayInterval:!0,focusedGuideKeys:{},...e,debugging:!0}})),s&&(this.knock.log("[Guide] Start debugging, refetching guides and resubscribing to the websocket channel"),this.fetch(),this.subscribe())}unsetDebug(){var s;this.knock.log("[Guide] .unsetDebug()");const e=(s=this.store.state.debug)==null?void 0:s.debugging;this.store.setState(t=>({...t,debug:void 0})),e&&(this.knock.log("[Guide] Stop debugging, refetching guides and resubscribing to the websocket channel"),this.fetch(),this.subscribe())}selectGuides(e,s={},t={}){var c;this.knock.log(`[Guide] .selectGuides (filters: ${l.formatFilters(s)}; state: ${l.formatState(e)})`);const i=this.selectGuide(e,s,{...t,recordSelectQuery:!1}),{recordSelectQuery:n=!!((c=e.debug)!=null&&c.debugging)}=t,r={limit:"all",opts:{...t,recordSelectQuery:n}},a=b(e,s,r);if(this.maybeRecordSelectResult(a),!i&&!t.includeThrottled)return[];const o=[...a.values()];if(!t.includeThrottled&&l.checkStateIfThrottled(e)){const d=o.filter(k=>k.bypass_global_group_limit),g=o.length-d.length;return this.knock.log(`[Guide] Throttling ${g} guides from selection, and returning ${d.length} guides`),d}return this.knock.log(`[Guide] Returning ${o.length} guides from selection`),o}selectGuide(e,s={},t={}){var g,k,S;if(this.knock.log(`[Guide] .selectGuide (filters: ${l.formatFilters(s)}; state: ${l.formatState(e)})`),Object.keys(e.guides).length===0&&Object.keys(e.previewGuides).length===0){this.knock.log("[Guide] Exiting selection (no guides)");return}this.stage||(this.stage=this.openGroupStage());const{recordSelectQuery:i=!!((g=e.debug)!=null&&g.debugging)}=t,n={limit:"one",opts:{...t,recordSelectQuery:i}},r=b(e,s,n);if(this.maybeRecordSelectResult(r),r.size===0){this.knock.log("[Guide] Selection found zero result");return}const[a,o]=[...r][0];if(this.knock.log(`[Guide] Selection found: \`${o.key}\` (total: ${r.size})`),o.bypass_global_group_limit)return this.knock.log(`[Guide] Returning the unthrottled guide: ${o.key}`),o;const c=(S=(k=e.debug)==null?void 0:k.focusedGuideKeys)==null?void 0:S[o.key],d=!t.includeThrottled&&l.checkStateIfThrottled(e);switch(this.stage.status){case"open":{this.knock.log(`[Guide] Adding to the group stage: ${o.key}`),this.stage.ordered[a]=o.key;return}case"patch":{if(this.knock.log(`[Guide] Patching the group stage: ${o.key}`),this.stage.ordered[a]=o.key,c)return this.knock.log(`[Guide] Focused to return \`${o.key}\` (stage: ${l.formatGroupStage(this.stage)})`),o;if(d){this.knock.log(`[Guide] Throttling the selected guide: ${o.key}`);return}const p=this.stage.resolved===o.key?o:void 0;return this.knock.log(`[Guide] Returning \`${p==null?void 0:p.key}\` (stage: ${l.formatGroupStage(this.stage)})`),p}case"closed":{if(c)return this.knock.log(`[Guide] Focused to return \`${o.key}\` (stage: ${l.formatGroupStage(this.stage)})`),o;if(d){this.knock.log(`[Guide] Throttling the selected guide: ${o.key}`);return}const p=this.stage.resolved===o.key?o:void 0;return this.knock.log(`[Guide] Returning \`${p==null?void 0:p.key}\` (stage: ${l.formatGroupStage(this.stage)})`),p}}}maybeRecordSelectResult(e){if(!e.metadata)return;const{opts:s,filters:t,limit:i}=e.metadata;if(!s.recordSelectQuery||!t.key&&!t.type||!this.stage||this.stage.status==="closed")return;const n=this.stage.results.key||{};t.key&&(n[t.key]={...n[t.key]||{},[i]:e});const r=this.stage.results.type||{};t.type&&(r[t.type]={...r[t.type]||{},[i]:e}),this.stage={...this.stage,results:{key:n,type:r}}}getStage(){return this.stage}openGroupStage(){this.knock.log("[Guide] Opening a new group stage");const{orderResolutionDuration:e=w}=this.options,s=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.stage={status:"open",ordered:[],results:{},timeoutId:s},this.stage}closePendingGroupStage(){if(this.knock.log("[Guide] .closePendingGroupStage"),!this.stage||this.stage.status==="closed")return;this.ensureClearTimeout();const e=this.stage.ordered.find(s=>s!==void 0);return this.knock.log(`[Guide] Closing the current group stage: resolved=${e}`),this.stage={...this.stage,status:"closed",resolved:e,timeoutId:null},this.stage}patchClosedGroupStage(){var t;if(this.knock.log("[Guide] .patchClosedGroupStage"),((t=this.stage)==null?void 0:t.status)!=="closed")return;const{orderResolutionDuration:e=0}=this.options,s=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.ensureClearTimeout(),this.knock.log("[Guide] Patching the current group stage"),this.stage={...this.stage,status:"patch",ordered:[],timeoutId:s},this.stage}clearGroupStage(){this.knock.log("[Guide] .clearGroupStage"),this.stage&&(this.knock.log("[Guide] Clearing the current group stage"),this.ensureClearTimeout(),this.stage=void 0)}ensureClearTimeout(){var e;(e=this.stage)!=null&&e.timeoutId&&clearTimeout(this.stage.timeoutId)}_selectGuide(e,s={},t={}){return this.openGroupStage(),this.selectGuide(e,s,t),this.closePendingGroupStage(),this.selectGuide(e,s,t)}_selectGuides(e,s={},t={}){return this.openGroupStage(),this.selectGuides(e,s,t),this.closePendingGroupStage(),this.selectGuides(e,s,t)}async markAsSeen(e,s){if(s.message.seen_at)return;this.knock.log(`[Guide] Marking as seen (Guide key: ${e.key}, Step ref:${s.ref})`);const t=this.setStepMessageAttrs(e.key,s.ref,{seen_at:new Date().toISOString()});if(!t)return;if(this.shouldSkipEngagementApi())return this.knock.log("[Guide] Skipping engagement API call for markAsSeen (debug mode)"),t;const i={...this.buildEngagementEventBaseParams(e,t),content:t.content,data:this.targetParams.data};return this.knock.user.markGuideStepAs("seen",i),t}async markAsInteracted(e,s,t){this.knock.log(`[Guide] Marking as interacted (Guide key: ${e.key}; Step ref:${s.ref})`);const i=new Date().toISOString(),n=this.setStepMessageAttrs(e.key,s.ref,{read_at:i,interacted_at:i});if(!n)return;if(this.shouldSkipEngagementApi())return this.knock.log("[Guide] Skipping engagement API call for markAsInteracted (debug mode)"),n;const r={...this.buildEngagementEventBaseParams(e,n),metadata:t};return this.knock.user.markGuideStepAs("interacted",r),n}async markAsArchived(e,s){if(s.message.archived_at)return;this.knock.log(`[Guide] Marking as archived (Guide key: ${e.key}, Step ref:${s.ref})`);const t=this.setStepMessageAttrs(e.key,s.ref,{archived_at:new Date().toISOString()});if(!t)return;if(this.shouldSkipEngagementApi())return this.knock.log("[Guide] Skipping engagement API call for markAsArchived (debug mode)"),t;const i=this.buildEngagementEventBaseParams(e,t);return this.knock.user.markGuideStepAs("archived",{...i,unthrottled:e.bypass_global_group_limit}),t}shouldSkipEngagementApi(){var e;return!!((e=this.store.state.debug)!=null&&e.skipEngagementTracking)}localCopy(e){const s=this,t={...e,getStep(){var i,n,r;return((i=s.store.state.debug)==null?void 0:i.forcedGuideKey)===this.key||(r=(n=s.store.state.debug)==null?void 0:n.focusedGuideKeys)!=null&&r[this.key]?this.steps[0]:this.steps.find(a=>!a.message.archived_at)}};return t.getStep=t.getStep.bind(t),t.steps=e.steps.map(({message:i,...n})=>{const r={...n,message:{...i},markAsSeen(){return s.markAsSeen(t,this)},markAsInteracted({metadata:a}={}){return s.markAsInteracted(t,this,a)},markAsArchived(){return s.markAsArchived(t,this)}};return r.markAsSeen=r.markAsSeen.bind(r),r.markAsInteracted=r.markAsInteracted.bind(r),r.markAsArchived=r.markAsArchived.bind(r),r}),t.activation_url_patterns=e.activation_url_patterns.map(i=>({...i,pattern:new R.URLPattern({pathname:i.pathname??void 0,search:i.search??void 0})})),t}buildQueryParams(e={}){const s={...this.targetParams,...e},t=this.store.state.debug;(t!=null&&t.forcedGuideKey||t!=null&&t.debugging)&&(s.force_all_guides=!0);let i=Object.fromEntries(Object.entries(s).filter(([n,r])=>r!=null));return i=i.data?{...i,data:JSON.stringify(i.data)}:i,i}formatQueryKey(e){const t=Object.keys(e).sort().map(n=>`${encodeURIComponent(n)}=${encodeURIComponent(e[n])}`).join("&"),i=v(this.knock.userId);return t?`${i}?${t}`:i}setStepMessageAttrs(e,s,t){let i;return t.archived_at&&this.clearGroupStage(),this.store.setState(n=>{let r=n.guides[e];if(!r)return n;const a=r.steps.map(d=>(d.ref!==s||(d.message={...d.message,...t},i=d),d));r=i?{...r,steps:a}:r;const o={...n.guides,[r.key]:r},c=t.archived_at&&!r.bypass_global_group_limit?{...n.guideGroupDisplayLogs,[l.DEFAULT_GROUP_KEY]:t.archived_at}:n.guideGroupDisplayLogs;return{...n,guides:o,guideGroupDisplayLogs:c}}),i}buildEngagementEventBaseParams(e,s){return{channel_id:e.channel_id,guide_key:e.key,guide_id:e.id,guide_step_ref:s.ref,tenant:this.targetParams.tenant}}addOrReplaceGuide({data:e}){this.patchClosedGroupStage();const s=this.localCopy(e.guide);this.store.setState(t=>{const i={...t.guides,[s.key]:s};return{...t,guides:i}})}removeGuide({data:e}){this.patchClosedGroupStage(),this.store.setState(s=>{const{[e.guide.key]:t,...i}=s.guides;return{...s,guides:i}})}addOrReplaceGuideGroup({data:e}){this.patchClosedGroupStage(),this.store.setState(s=>{const t=[e.guide_group],i=e.guide_group.display_sequence_unthrottled||[],n=e.guide_group.display_sequence_throttled||[];let r=s.guides;return r=i.reduce((a,o)=>{if(!a[o])return a;const c={...a[o],bypass_global_group_limit:!0};return{...a,[o]:c}},r),r=n.reduce((a,o)=>{if(!a[o])return a;const c={...a[o],bypass_global_group_limit:!1};return{...a,[o]:c}},r),{...s,guides:r,guideGroups:t}})}updatePreviewGuide({data:e}){const s=this.localCopy(e.guide);this.store.setState(t=>{const i={...t.previewGuides,[s.key]:s};return{...t,previewGuides:i}})}checkDebugStateChanged(e,s){return!!e.forcedGuideKey!=!!s.forcedGuideKey||e.previewSessionId!==s.previewSessionId}listenForLocationChangesFromWindow(){const e=y();if(e!=null&&e.history&&(e!=null&&e.addEventListener)){e.addEventListener("popstate",this.handleLocationChange),e.addEventListener("hashchange",this.handleLocationChange);const s=e.history.pushState,t=e.history.replaceState;e.history.pushState=new Proxy(s,{apply:(i,n,r)=>{Reflect.apply(i,n,r),setTimeout(()=>{this.handleLocationChange()},0)}}),e.history.replaceState=new Proxy(t,{apply:(i,n,r)=>{Reflect.apply(i,n,r),setTimeout(()=>{this.handleLocationChange()},0)}}),this.pushStateFn=s,this.replaceStateFn=t}else this.knock.log("[Guide] Unable to access the `window.history` object to detect location changes")}removeLocationChangeEventListeners(){const e=y();!(e!=null&&e.history)||!(e!=null&&e.removeEventListener)||(e.removeEventListener("popstate",this.handleLocationChange),e.removeEventListener("hashchange",this.handleLocationChange),this.pushStateFn&&(e.history.pushState=this.pushStateFn,this.pushStateFn=void 0),this.replaceStateFn&&(e.history.replaceState=this.replaceStateFn,this.replaceStateFn=void 0))}}exports.DEBUG_QUERY_PARAMS=f;exports.KnockGuideClient=T;exports.checkActivatable=_;exports.guidesApiRootPath=v;
|
|
2
2
|
//# sourceMappingURL=client.js.map
|